code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
horizon.tabs = {
_init_load_functions: []
};
horizon.tabs.addTabLoadFunction = function (f) {
horizon.tabs._init_load_functions.push(f);
};
horizon.tabs.initTabLoad = function (tab) {
$(horizon.tabs._init_load_functions).each(function (index, f) {
f(tab);
});
};
horizon.tabs.load_tab = function (evt) {
var $this = $(this),
tab_id = $this.attr('data-target'),
tab_pane = $(tab_id);
// FIXME(gabriel): This style mucking shouldn't be in the javascript.
tab_pane.append("<span style='margin-left: 30px;'>" + gettext("Loading") + "…</span>");
tab_pane.spin(horizon.conf.spinner_options.inline);
$(tab_pane.data().spinner.el).css('top', '9px');
$(tab_pane.data().spinner.el).css('left', '15px');
// If query params exist, append tab id.
if(window.location.search.length > 0) {
tab_pane.load(window.location.search + "&tab=" + tab_id.replace('#', ''), function() {
horizon.tabs.initTabLoad(tab_pane);
});
} else {
tab_pane.load("?tab=" + tab_id.replace('#', ''), function() {
horizon.tabs.initTabLoad(tab_pane);
});
}
$this.attr("data-loaded", "true");
evt.preventDefault();
};
horizon.addInitFunction(function () {
var data = horizon.cookies.get("tabs") || {};
$(".tab-content").find(".js-tab-pane").addClass("tab-pane");
horizon.modals.addModalInitFunction(function (el) {
$(el).find(".js-tab-pane").addClass("tab-pane");
});
$(document).on("show", ".ajax-tabs a[data-loaded='false']", horizon.tabs.load_tab);
$(document).on("shown", ".nav-tabs a[data-toggle='tab']", function (evt) {
var $tab = $(evt.target),
$content = $($(evt.target).attr('data-target'));
$content.find("table.datatable").each(function () {
horizon.datatables.update_footer_count($(this));
});
data[$tab.closest(".nav-tabs").attr("id")] = $tab.attr('data-target');
horizon.cookies.put("tabs", data);
});
// Initialize stored tab state for tab groups on this page.
$(".nav-tabs[data-sticky-tabs='sticky']").each(function (index, item) {
var $this = $(this),
id = $this.attr("id"),
active_tab = data[id];
// Set the tab from memory if we have a "sticky" tab and the tab wasn't explicitly requested via GET.
if (active_tab && window.location.search.indexOf("tab=") < 0) {
$this.find("a[data-target='" + active_tab + "']").tab('show');
}
});
// Enable keyboard navigation between tabs in a form.
$(document).on("keydown", ".tab-pane :input:visible:last", function (evt) {
var $this = $(this),
next_pane = $this.closest(".tab-pane").next(".tab-pane");
// Capture the forward-tab keypress if we have a next tab to go to.
if (evt.which === 9 && !event.shiftKey && next_pane.length) {
evt.preventDefault();
$(".nav-tabs a[data-target='#" + next_pane.attr("id") + "']").tab('show');
}
});
$(document).on("keydown", ".tab-pane :input:visible:first", function (evt) {
var $this = $(this),
prev_pane = $this.closest(".tab-pane").prev(".tab-pane");
// Capture the forward-tab keypress if we have a next tab to go to.
if (event.shiftKey && evt.which === 9 && prev_pane.length) {
evt.preventDefault();
$(".nav-tabs a[data-target='#" + prev_pane.attr("id") + "']").tab('show');
prev_pane.find(":input:last").focus();
}
});
$(document).on("focus", ".tab-content :input", function () {
var $this = $(this),
tab_pane = $this.closest(".tab-pane"),
tab_id = tab_pane.attr('id');
if (!tab_pane.hasClass("active")) {
$(".nav-tabs a[data-target='#" + tab_id + "']").tab('show');
}
});
});
| spandanb/horizon | horizon/static/horizon/js/horizon.tabs.js | JavaScript | apache-2.0 | 3,633 |
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
#include <sstream>
#include "service_instance.h"
#include "ifmap/ifmap_node.h"
#include "schema/vnc_cfg_types.h"
#include "oper/ifmap_dependency_manager.h"
#include "oper/operdb_init.h"
#include <cfg/cfg_init.h>
#include <cmn/agent.h>
#include <init/agent_param.h>
#include <oper/agent_sandesh.h>
#include <oper/agent_types.h>
#include "oper/instance_manager.h"
using boost::uuids::uuid;
/*
* ServiceInstanceTable create requests contain the IFMapNode that this
* entry corresponds to.
*/
class ServiceInstanceCreate : public AgentData {
public:
ServiceInstanceCreate(IFMapNode *node) :
node_(node) {
}
IFMapNode *node() { return node_; }
private:
IFMapNode *node_;
};
class ServiceInstanceTypesMapping {
public:
static const std::string kOtherType;
static int StrServiceTypeToInt(const std::string &type);
static const std::string &IntServiceTypeToStr(
const ServiceInstance::ServiceType &type);
static int StrVirtualizationTypeToInt(const std::string &type);
static const std::string &IntVirtualizationTypeToStr(
const ServiceInstance::VirtualizationType &type);
static int StrVRouterInstanceTypeToInt(const std::string &type);
static const std::string &IntVRouterInstanceTypeToStr(
const ServiceInstance::VRouterInstanceType &type);
private:
typedef std::map<std::string, int> StrTypeToIntMap;
typedef std::pair<std::string, int> StrTypeToIntPair;
static StrTypeToIntMap service_type_map_;
static StrTypeToIntMap virtualization_type_map_;
static StrTypeToIntMap vrouter_instance_type_map_;
static StrTypeToIntMap InitServiceTypeMap() {
StrTypeToIntMap types;
types.insert(StrTypeToIntPair("source-nat", ServiceInstance::SourceNAT));
types.insert(StrTypeToIntPair("loadbalancer", ServiceInstance::LoadBalancer));
return types;
};
static StrTypeToIntMap InitVirtualizationTypeMap() {
StrTypeToIntMap types;
types.insert(StrTypeToIntPair("virtual-machine", ServiceInstance::VirtualMachine));
types.insert(StrTypeToIntPair("network-namespace", ServiceInstance::NetworkNamespace));
types.insert(StrTypeToIntPair("vrouter-instance", ServiceInstance::VRouterInstance));
return types;
};
static StrTypeToIntMap InitVRouterInstanceTypeMap() {
StrTypeToIntMap types;
types.insert(StrTypeToIntPair("libvirt-qemu", ServiceInstance::KVM));
types.insert(StrTypeToIntPair("docker", ServiceInstance::Docker));
return types;
};
};
static uuid IdPermsGetUuid(const autogen::IdPermsType &id) {
uuid uuid;
CfgUuidSet(id.uuid.uuid_mslong, id.uuid.uuid_lslong, uuid);
return uuid;
}
static bool IsNodeType(IFMapNode *node, const char *node_typename) {
return (strcmp(node->table()->Typename(), node_typename) == 0);
}
/*
* Walks through the graph starting from the service instance in order to
* find the Virtual Machine associated. Set the vm_id of the ServiceInstanceData
* object and return the VM node.
*/
static IFMapNode *FindAndSetVirtualMachine(
DBGraph *graph, IFMapNode *si_node,
ServiceInstance::Properties *properties) {
for (DBGraphVertex::adjacency_iterator iter = si_node->begin(graph);
iter != si_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (IsNodeType(adj, "virtual-machine")) {
autogen::VirtualMachine *vm =
static_cast<autogen::VirtualMachine *>(adj->GetObject());
properties->instance_id = IdPermsGetUuid(vm->id_perms());
return adj;
}
}
return NULL;
}
static IFMapNode *FindNetworkIpam(DBGraph *graph, IFMapNode *vn_ipam_node) {
for (DBGraphVertex::adjacency_iterator iter = vn_ipam_node->begin(graph);
iter != vn_ipam_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (IsNodeType(adj, "network-ipam")) {
return adj;
}
}
return NULL;
}
static IFMapNode *FindNetwork(DBGraph *graph, IFMapNode *vmi_node) {
/*
* Lookup for VirtualNetwork nodes
*/
for (DBGraphVertex::adjacency_iterator iter = vmi_node->begin(graph);
iter != vmi_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (IsNodeType(adj, "virtual-network")) {
return adj;
}
}
return NULL;
}
static std::string FindInterfaceIp(DBGraph *graph, IFMapNode *vmi_node) {
for (DBGraphVertex::adjacency_iterator iter = vmi_node->begin(graph);
iter != vmi_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (IsNodeType(adj, "instance-ip")) {
autogen::InstanceIp *ip =
static_cast<autogen::InstanceIp *>(adj->GetObject());
return ip->address();
}
}
return std::string();
}
static bool SubNetContainsIpv4(const autogen::IpamSubnetType &subnet,
const std::string &ip) {
typedef boost::asio::ip::address_v4 Ipv4Address;
std::string prefix = subnet.subnet.ip_prefix;
int prefix_len = subnet.subnet.ip_prefix_len;
boost::system::error_code ec;
Ipv4Address ipv4 = Ipv4Address::from_string(ip, ec);
Ipv4Address ipv4_prefix = Ipv4Address::from_string(prefix, ec);
unsigned long mask = (0xFFFFFFFF << (32 - prefix_len)) & 0xFFFFFFFF;
if ((ipv4.to_ulong() & mask) == (ipv4_prefix.to_ulong() & mask)) {
return true;
}
return false;
}
static void FindAndSetInterfaces(
DBGraph *graph, IFMapNode *vm_node,
autogen::ServiceInstance *svc_instance,
ServiceInstance::Properties *properties) {
/*
* The outside virtual-network is always specified (by the
* process that creates the service-instance).
* The inside virtual-network is optional for loadbalancer.
* For VRouter instance there can be up to 3 interfaces.
* TODO: support more than 3 interfaces for VRouter instances.
* Lookup for VMI nodes
*/
properties->interface_count = 0;
for (DBGraphVertex::adjacency_iterator iter = vm_node->begin(graph);
iter != vm_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (!IsNodeType(adj, "virtual-machine-interface")) {
continue;
}
autogen::VirtualMachineInterface *vmi =
static_cast<autogen::VirtualMachineInterface *>(
adj->GetObject());
const autogen::VirtualMachineInterfacePropertiesType &vmi_props =
vmi->properties();
IFMapNode *vn_node = FindNetwork(graph, adj);
if (vn_node == NULL) {
continue;
}
properties->interface_count++;
if(vmi_props.service_interface_type == "left") {
properties->vmi_inside = IdPermsGetUuid(vmi->id_perms());
if (vmi->mac_addresses().size())
properties->mac_addr_inside = vmi->mac_addresses().at(0);
properties->ip_addr_inside = FindInterfaceIp(graph, adj);
}
else if(vmi_props.service_interface_type == "right") {
properties->vmi_outside = IdPermsGetUuid(vmi->id_perms());
if (vmi->mac_addresses().size())
properties->mac_addr_outside = vmi->mac_addresses().at(0);
properties->ip_addr_outside = FindInterfaceIp(graph, adj);
}
else if(vmi_props.service_interface_type == "management") {
properties->vmi_management = IdPermsGetUuid(vmi->id_perms());
if (vmi->mac_addresses().size())
properties->mac_addr_management = vmi->mac_addresses().at(0);
properties->ip_addr_management = FindInterfaceIp(graph, adj);
}
for (DBGraphVertex::adjacency_iterator iter = vn_node->begin(graph);
iter != vn_node->end(graph); ++iter) {
IFMapNode *vn_ipam_node =
static_cast<IFMapNode *>(iter.operator->());
if (!IsNodeType(vn_ipam_node, "virtual-network-network-ipam")) {
continue;
}
autogen::VirtualNetworkNetworkIpam *ipam =
static_cast<autogen::VirtualNetworkNetworkIpam *>
(vn_ipam_node->GetObject());
IFMapNode *ipam_node = FindNetworkIpam(graph, vn_ipam_node);
if (ipam_node == NULL) {
continue;
}
autogen::NetworkIpam *network_ipam =
static_cast<autogen::NetworkIpam *>(ipam_node->GetObject());
const std::string subnet_method =
boost::to_lower_copy(network_ipam->ipam_subnet_method());
const std::vector<autogen::IpamSubnetType> &subnets =
(subnet_method == "flat-subnet") ?
network_ipam->ipam_subnets() : ipam->data().ipam_subnets;
for (unsigned int i = 0; i < subnets.size(); ++i) {
int prefix_len = subnets[i].subnet.ip_prefix_len;
int service_type = properties->service_type;
if (vmi_props.service_interface_type == "left") {
std::string &ip_addr = properties->ip_addr_inside;
if (SubNetContainsIpv4(subnets[i], ip_addr)) {
properties->ip_prefix_len_inside = prefix_len;
if (service_type == ServiceInstance::SourceNAT)
properties->gw_ip = subnets[i].default_gateway;
}
} else if (vmi_props.service_interface_type == "right") {
std::string &ip_addr = properties->ip_addr_outside;
if (SubNetContainsIpv4(subnets[i], ip_addr)) {
properties->ip_prefix_len_outside = prefix_len;
if (service_type == ServiceInstance::LoadBalancer)
properties->gw_ip = subnets[i].default_gateway;
}
} else if (vmi_props.service_interface_type == "management") {
std::string &ip_addr = properties->ip_addr_management;
if (SubNetContainsIpv4(subnets[i], ip_addr))
properties->ip_prefix_len_management = prefix_len;
}
}
}
}
}
/*
* Walks through the graph in order to get the template associated to the
* Service Instance Node and set the types in the ServiceInstanceData object.
*/
static void FindAndSetTypes(DBGraph *graph, IFMapNode *si_node,
ServiceInstance::Properties *properties) {
IFMapNode *st_node = NULL;
for (DBGraphVertex::adjacency_iterator iter = si_node->begin(graph);
iter != si_node->end(graph); ++iter) {
IFMapNode *adj = static_cast<IFMapNode *>(iter.operator->());
if (IsNodeType(adj, "service-template")) {
st_node = adj;
break;
}
}
if (st_node == NULL) {
return;
}
autogen::ServiceTemplate *svc_template =
static_cast<autogen::ServiceTemplate *>(st_node->GetObject());
autogen::ServiceTemplateType svc_template_props =
svc_template->properties();
properties->service_type =
ServiceInstanceTypesMapping::StrServiceTypeToInt(
svc_template_props.service_type);
properties->virtualization_type =
ServiceInstanceTypesMapping::StrVirtualizationTypeToInt(
svc_template_props.service_virtualization_type);
properties->vrouter_instance_type =
ServiceInstanceTypesMapping::StrVRouterInstanceTypeToInt(
svc_template_props.vrouter_instance_type);
properties->image_name = svc_template_props.image_name;
properties->instance_data = svc_template_props.instance_data;
}
static void FindAndSetLoadbalancer(ServiceInstance::Properties *properties) {
const std::vector<autogen::KeyValuePair> &kvps = properties->instance_kvps;
std::vector<autogen::KeyValuePair>::const_iterator iter;
for (iter = kvps.begin(); iter != kvps.end(); ++iter) {
autogen::KeyValuePair kvp = *iter;
if (kvp.key == "lb_uuid") {
properties->loadbalancer_id = kvp.value;
break;
}
}
}
/*
* ServiceInstance Properties
*/
void ServiceInstance::Properties::Clear() {
service_type = 0;
virtualization_type = 0;
vrouter_instance_type = 0;
instance_id = boost::uuids::nil_uuid();
vmi_inside = boost::uuids::nil_uuid();
vmi_outside = boost::uuids::nil_uuid();
vmi_management = boost::uuids::nil_uuid();
mac_addr_inside.clear();
mac_addr_outside.clear();
mac_addr_management.clear();
ip_addr_inside.clear();
ip_addr_outside.clear();
ip_addr_management.clear();
gw_ip.clear();
image_name.clear();
ip_prefix_len_inside = -1;
ip_prefix_len_outside = -1;
ip_prefix_len_management = -1;
interface_count = 0;
instance_data.clear();
std::vector<autogen::KeyValuePair>::const_iterator iter;
for (iter = instance_kvps.begin(); iter != instance_kvps.end(); ++iter) {
autogen::KeyValuePair kvp = *iter;
kvp.Clear();
}
loadbalancer_id.clear();
}
static int compare_kvps(const std::vector<autogen::KeyValuePair> &lhs,
const std::vector<autogen::KeyValuePair> &rhs) {
int ret = 0;
int match;
int remining_rhs_items;
std::vector<autogen::KeyValuePair>::const_iterator iter1;
std::vector<autogen::KeyValuePair>::const_iterator iter2;
iter1 = lhs.begin();
iter2 = rhs.begin();
match = 0;
remining_rhs_items = rhs.end() - rhs.begin();
while (iter1 != lhs.end()) {
while (iter2 != rhs.end()) {
if (iter1->key.compare(iter2->key) == 0) {
if ((ret = iter1->value.compare(iter2->value)) != 0) {
return ret;
}
remining_rhs_items--;
match = 1;
break;
}
iter2++;
}
if (match == 0) {
return 1;
}
match = 0;
iter2 = rhs.begin();
iter1++;
}
if (remining_rhs_items)
return -1;
return 0;
}
template <typename Type>
static int compare(const Type &lhs, const Type &rhs) {
if (lhs < rhs) {
return -1;
}
if (rhs < lhs) {
return 1;
}
return 0;
}
int ServiceInstance::Properties::CompareTo(const Properties &rhs) const {
int cmp = 0;
cmp = compare(service_type, rhs.service_type);
if (cmp != 0) {
return cmp;
}
cmp = compare(vrouter_instance_type, rhs.vrouter_instance_type);
if (cmp != 0) {
return cmp;
}
cmp = compare(virtualization_type, rhs.virtualization_type);
if (cmp != 0) {
return cmp;
}
cmp = compare(instance_id, rhs.instance_id);
if (cmp != 0) {
return cmp;
}
cmp = compare(vmi_inside, rhs.vmi_inside);
if (cmp != 0) {
return cmp;
}
cmp = compare(vmi_outside, rhs.vmi_outside);
if (cmp != 0) {
return cmp;
}
cmp = compare(ip_addr_inside, rhs.ip_addr_inside);
if (cmp != 0) {
return cmp;
}
cmp = compare(ip_addr_outside, rhs.ip_addr_outside);
if (cmp != 0) {
return cmp;
}
cmp = compare(ip_prefix_len_inside, rhs.ip_prefix_len_inside);
if (cmp != 0) {
return cmp;
}
cmp = compare(ip_prefix_len_outside, rhs.ip_prefix_len_outside);
if (cmp != 0) {
return cmp;
}
cmp = compare(interface_count, rhs.interface_count);
if (cmp != 0) {
return cmp;
}
cmp = compare(gw_ip, rhs.gw_ip);
if (cmp != 0) {
return cmp;
}
cmp = compare(image_name, rhs.image_name);
if (cmp != 0) {
return cmp;
}
cmp = compare(instance_data, rhs.instance_data);
if (cmp != 0) {
return cmp;
}
cmp = compare_kvps(instance_kvps, rhs.instance_kvps);
if (cmp != 0) {
return cmp;
}
cmp = compare(loadbalancer_id, rhs.loadbalancer_id);
if (cmp != 0) {
return cmp;
}
return cmp;
}
void InstanceKvpsDiffString(const std::vector<autogen::KeyValuePair> &lhs,
const std::vector<autogen::KeyValuePair> &rhs,
std::stringstream *ss) {
int ret = 0;
int match;
int remining_rhs_items;
std::vector<autogen::KeyValuePair>::const_iterator iter1;
std::vector<autogen::KeyValuePair>::const_iterator iter2;
iter1 = lhs.begin();
iter2 = rhs.begin();
match = 0;
remining_rhs_items = rhs.size();
while (iter1 != lhs.end()) {
while (iter2 != rhs.end()) {
if (iter1->key.compare(iter2->key) == 0) {
remining_rhs_items--;
match = 1;
if ((ret = iter1->value.compare(iter2->value)) != 0) {
*ss << iter1->key << ": -" << iter1->value;
*ss << " +" << iter2->value;
break;
}
}
iter2++;
}
if (match == 0) {
*ss << " -" << iter1->key << ": " << iter1->value;
}
match = 0;
iter2 = rhs.begin();
iter1++;
}
if (remining_rhs_items == 0)
return;
iter1 = rhs.begin();
iter2 = lhs.begin();
match = 0;
while (iter1 != rhs.end()) {
while (iter2 != lhs.end()) {
if (iter1->key.compare(iter2->key) == 0) {
match = 1;
break;
}
iter2++;
}
if (match == 0) {
*ss << " +" << iter1->key << ": " << iter1->value;
}
match = 0;
iter2 = lhs.begin();
iter1++;
}
}
std::string ServiceInstance::Properties::DiffString(
const Properties &rhs) const {
std::stringstream ss;
if (compare(service_type, rhs.service_type)) {
ss << " type: -" << service_type << " +" << rhs.service_type;
}
if (compare(virtualization_type, rhs.virtualization_type)) {
ss << " virtualization: -" << virtualization_type
<< " +" << rhs.virtualization_type;
}
if (compare(vrouter_instance_type, rhs.vrouter_instance_type)) {
ss << " vrouter-instance-type: -" << vrouter_instance_type
<< " +" << rhs.vrouter_instance_type;
}
if (compare(instance_id, rhs.instance_id)) {
ss << " id: -" << instance_id << " +" << rhs.instance_id;
}
if (compare(vmi_inside, rhs.vmi_inside)) {
ss << " vmi-inside: -" << vmi_inside << " +" << rhs.vmi_inside;
}
if (compare(vmi_outside, rhs.vmi_outside)) {
ss << " vmi-outside: -" << vmi_outside << " +" << rhs.vmi_outside;
}
if (compare(ip_addr_inside, rhs.ip_addr_inside)) {
ss << " ip-inside: -" << ip_addr_inside
<< " +" << rhs.ip_addr_inside;
}
if (compare(ip_addr_outside, rhs.ip_addr_outside)) {
ss << " ip-outside: -" << ip_addr_outside
<< " +" << rhs.ip_addr_outside;
}
if (compare(ip_prefix_len_inside, rhs.ip_prefix_len_inside)) {
ss << " pfx-inside: -" << ip_prefix_len_inside
<< " +" << rhs.ip_prefix_len_inside;
}
if (compare(ip_prefix_len_outside, rhs.ip_prefix_len_outside)) {
ss << " pfx-outside: -" << ip_prefix_len_outside
<< " +" << rhs.ip_prefix_len_outside;
}
if (compare(loadbalancer_id, rhs.loadbalancer_id)) {
ss << " loadbalancer_id: -" << loadbalancer_id << " +"
<< rhs.loadbalancer_id;
}
if (compare(gw_ip, rhs.gw_ip)) {
ss << " gw_ip: -" << gw_ip << " +" << rhs.gw_ip;
}
if (compare(image_name, rhs.image_name)) {
ss << " image: -" << image_name << " +" << rhs.image_name;
}
if (compare(instance_data, rhs.instance_data)) {
ss << " image: -" << instance_data << " +" << rhs.instance_data;
}
if (compare_kvps(instance_kvps, rhs.instance_kvps)) {
InstanceKvpsDiffString(instance_kvps, rhs.instance_kvps, &ss);
}
return ss.str();
}
bool ServiceInstance::Properties::Usable() const {
if (instance_id.is_nil()) {
return false;
}
if (virtualization_type == ServiceInstance::VRouterInstance) {
//TODO: investigate for docker
return true;
}
bool common = (!vmi_outside.is_nil() &&
!ip_addr_outside.empty() &&
(ip_prefix_len_outside >= 0));
if (!common) {
return false;
}
if (service_type == SourceNAT || interface_count == 2) {
bool outside = (!vmi_inside.is_nil() &&
!ip_addr_inside.empty() &&
(ip_prefix_len_inside >= 0));
if (!outside) {
return false;
}
}
if (gw_ip.empty())
return false;
if (service_type == LoadBalancer) {
if (loadbalancer_id.empty())
return false;
}
return true;
}
const std::string &ServiceInstance::Properties::ServiceTypeString() const {
return ServiceInstanceTypesMapping::IntServiceTypeToStr(
static_cast<ServiceType>(service_type));
}
/*
* ServiceInstance class
*/
ServiceInstance::ServiceInstance() {
properties_.Clear();
}
bool ServiceInstance::IsLess(const DBEntry &rhs) const {
const ServiceInstance &si = static_cast<const ServiceInstance &>(rhs);
return uuid_ < si.uuid_;
}
std::string ServiceInstance::ToString() const {
return UuidToString(uuid_);
}
void ServiceInstance::SetKey(const DBRequestKey *key) {
const ServiceInstanceKey *si_key =
static_cast<const ServiceInstanceKey *>(key);
uuid_ = si_key->instance_id();
}
DBEntryBase::KeyPtr ServiceInstance::GetDBRequestKey() const {
ServiceInstanceKey *key = new ServiceInstanceKey(uuid_);
return KeyPtr(key);
}
bool ServiceInstance::DBEntrySandesh(Sandesh *sresp, std::string &name) const {
ServiceInstanceResp *resp = static_cast<ServiceInstanceResp *> (sresp);
std::string str_uuid = UuidToString(uuid_);
if (! name.empty() && str_uuid != name) {
return false;
}
ServiceInstanceSandeshData data;
data.set_uuid(str_uuid);
data.set_instance_id(UuidToString(properties_.instance_id));
data.set_service_type(ServiceInstanceTypesMapping::IntServiceTypeToStr(
static_cast<ServiceType>(properties_.service_type)));
data.set_virtualization_type(
ServiceInstanceTypesMapping::IntVirtualizationTypeToStr(
static_cast<VirtualizationType>(
properties_.virtualization_type)));
data.set_vmi_inside(UuidToString(properties_.vmi_inside));
data.set_vmi_outside(UuidToString(properties_.vmi_outside));
Agent *agent = Agent::GetInstance();
DBTableBase *si_table = agent->db()->FindTable("db.service-instance.0");
assert(si_table);
InstanceManager *manager = agent->oper_db()->instance_manager();
assert(manager);
InstanceState *state = manager->GetState(const_cast<ServiceInstance *>(this));
if (state != NULL) {
NamespaceStateSandeshData state_data;
state_data.set_cmd(state->cmd());
state_data.set_errors(state->errors());
state_data.set_pid(state->pid());
state_data.set_status(state->status());
state_data.set_status_type(state->status_type());
data.set_ns_state(state_data);
}
std::vector<ServiceInstanceSandeshData> &list =
const_cast<std::vector<ServiceInstanceSandeshData>&>
(resp->get_service_instance_list());
list.push_back(data);
return true;
}
bool ServiceInstance::IsUsable() const {
return properties_.Usable();
}
void ServiceInstanceReq::HandleRequest() const {
AgentSandeshPtr sand(new AgentServiceInstanceSandesh(context(),
get_uuid()));
sand->DoSandesh(sand);
}
AgentSandeshPtr ServiceInstanceTable::GetAgentSandesh
(const AgentSandeshArguments *args, const std::string &context){
return AgentSandeshPtr
(new AgentServiceInstanceSandesh(context, args->GetString("name")));
}
/*
* ServiceInstanceTable class
*/
ServiceInstanceTable::ServiceInstanceTable(DB *db, const std::string &name)
: AgentDBTable(db, name),
graph_(NULL), dependency_manager_(NULL) {
}
std::auto_ptr<DBEntry> ServiceInstanceTable::AllocEntry(
const DBRequestKey *key) const {
std::auto_ptr<DBEntry> entry(new ServiceInstance());
entry->SetKey(key);
return entry;
}
bool ServiceInstanceTable::HandleAddChange(ServiceInstance
**svc_instancep, const DBRequest *request) {
ServiceInstanceCreate *data =
static_cast<ServiceInstanceCreate *>(request->data.get());
if (!data)
return false;
IFMapNode *node = data->node();
ServiceInstance *svc_instance = *svc_instancep;
assert(graph_);
ServiceInstance::Properties properties;
properties.Clear();
CalculateProperties(graph_, node, &properties);
assert(dependency_manager_);
if (!svc_instance) {
svc_instance = new ServiceInstance();
*svc_instancep = svc_instance;
}
if (!svc_instance->ifmap_node()) {
svc_instance->SetKey(request->key.get());
svc_instance->SetIFMapNodeState
(dependency_manager_->SetState(node));
dependency_manager_->SetObject(node, svc_instance);
}
if (properties.CompareTo(svc_instance->properties()) == 0)
return false;
if (svc_instance->properties().Usable() != properties.Usable()) {
LOG(DEBUG, "service-instance properties change" <<
svc_instance->properties().DiffString(properties));
}
svc_instance->set_properties(properties);
return true;
}
DBEntry *ServiceInstanceTable::Add(const DBRequest *request) {
ServiceInstance *svc_instance = NULL;
HandleAddChange(&svc_instance, request);
return svc_instance;
}
bool ServiceInstanceTable::Delete(DBEntry *entry, const DBRequest *request) {
ServiceInstance *svc_instance = static_cast<ServiceInstance *>(entry);
assert(dependency_manager_);
if (svc_instance->ifmap_node()) {
dependency_manager_->SetObject(svc_instance->ifmap_node(), NULL);
svc_instance->SetIFMapNodeState(NULL);
}
return true;
}
bool ServiceInstanceTable::OnChange(DBEntry *entry, const DBRequest *request) {
ServiceInstance *svc_instance = static_cast<ServiceInstance *>(entry);
return HandleAddChange(&svc_instance, request);
}
void ServiceInstanceTable::Initialize(
DBGraph *graph, IFMapDependencyManager *dependency_manager) {
graph_ = graph;
dependency_manager_ = dependency_manager;
dependency_manager_->Register(
"service-instance",
boost::bind(&ServiceInstanceTable::ChangeEventHandler, this, _1, _2));
}
bool ServiceInstanceTable::IFNodeToReq(IFMapNode *node, DBRequest
&request, const boost::uuids::uuid &id) {
assert(!id.is_nil());
request.key.reset(new ServiceInstanceKey(id));
if ((request.oper == DBRequest::DB_ENTRY_DELETE) || node->IsDeleted()) {
request.oper = DBRequest::DB_ENTRY_DELETE;
return true;
}
request.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
request.data.reset(new ServiceInstanceCreate(node));
return true;
}
void ServiceInstanceTable::CalculateProperties(
DBGraph *graph, IFMapNode *node, ServiceInstance::Properties *properties) {
properties->Clear();
if (node->IsDeleted()) {
return;
}
FindAndSetTypes(graph, node, properties);
/*
* The vrouter agent is only interest in the properties of service
* instances that are implemented as a network-namespace.
*/
if ((properties->virtualization_type != ServiceInstance::NetworkNamespace) &&
(properties->virtualization_type != ServiceInstance::VRouterInstance)) {
return;
}
IFMapNode *vm_node = FindAndSetVirtualMachine(graph, node, properties);
if (vm_node == NULL) {
return;
}
autogen::ServiceInstance *svc_instance =
static_cast<autogen::ServiceInstance *>(node->GetObject());
properties->instance_kvps = svc_instance->bindings();
FindAndSetInterfaces(graph, vm_node, svc_instance, properties);
if (properties->service_type == ServiceInstance::LoadBalancer) {
FindAndSetLoadbalancer(properties);
}
}
bool ServiceInstanceTable::IFNodeToUuid(IFMapNode *node, uuid &idperms_uuid) {
autogen::ServiceInstance *svc_instance =
static_cast<autogen::ServiceInstance *>(node->GetObject());
const autogen::IdPermsType &id = svc_instance->id_perms();
idperms_uuid = IdPermsGetUuid(id);
return true;
}
void ServiceInstanceTable::ChangeEventHandler(IFMapNode *node, DBEntry *entry) {
DBRequest req;
boost::uuids::uuid new_uuid;
IFNodeToUuid(node, new_uuid);
IFMapNodeState *state = dependency_manager_->IFMapNodeGet(node);
boost::uuids::uuid old_uuid = state->uuid();
if (!node->IsDeleted()) {
if (entry) {
if ((old_uuid != new_uuid)) {
if (old_uuid != boost::uuids::nil_uuid()) {
req.oper = DBRequest::DB_ENTRY_DELETE;
if (IFNodeToReq(node, req, old_uuid) == true) {
assert(req.oper == DBRequest::DB_ENTRY_DELETE);
Enqueue(&req);
}
}
}
}
assert(new_uuid != boost::uuids::nil_uuid());
state->set_uuid(new_uuid);
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
} else {
if (old_uuid == boost::uuids::nil_uuid()) {
//Node was never added so no point sending delete
return;
}
req.oper = DBRequest::DB_ENTRY_DELETE;
new_uuid = old_uuid;
}
if (IFNodeToReq(node, req, new_uuid) == true) {
Enqueue(&req);
}
}
DBTableBase *ServiceInstanceTable::CreateTable(
DB *db, const std::string &name) {
ServiceInstanceTable *table = new ServiceInstanceTable(db, name);
table->Init();
return table;
}
/*
* ServiceInstanceTypeMapping class
*/
ServiceInstanceTypesMapping::StrTypeToIntMap
ServiceInstanceTypesMapping::service_type_map_ = InitServiceTypeMap();
ServiceInstanceTypesMapping::StrTypeToIntMap
ServiceInstanceTypesMapping::virtualization_type_map_ = InitVirtualizationTypeMap();
ServiceInstanceTypesMapping::StrTypeToIntMap
ServiceInstanceTypesMapping::vrouter_instance_type_map_ = InitVRouterInstanceTypeMap();
const std::string ServiceInstanceTypesMapping::kOtherType = "Other";
int ServiceInstanceTypesMapping::StrServiceTypeToInt(const std::string &type) {
StrTypeToIntMap::const_iterator it = service_type_map_.find(type);
if (it != service_type_map_.end()) {
return it->second;
}
return 0;
}
int ServiceInstanceTypesMapping::StrVirtualizationTypeToInt(
const std::string &type) {
StrTypeToIntMap::const_iterator it = virtualization_type_map_.find(type);
if (it != virtualization_type_map_.end()) {
return it->second;
}
return 0;
}
int ServiceInstanceTypesMapping::StrVRouterInstanceTypeToInt(
const std::string &type) {
StrTypeToIntMap::const_iterator it = vrouter_instance_type_map_.find(type);
if (it != vrouter_instance_type_map_.end()) {
return it->second;
}
return 0;
}
const std::string &ServiceInstanceTypesMapping::IntServiceTypeToStr(
const ServiceInstance::ServiceType &type) {
for (StrTypeToIntMap::const_iterator it = service_type_map_.begin();
it != service_type_map_.end(); ++it) {
if (it->second == type) {
return it->first;
}
}
return kOtherType;
}
const std::string &ServiceInstanceTypesMapping::IntVirtualizationTypeToStr(
const ServiceInstance::VirtualizationType &type) {
for (StrTypeToIntMap::const_iterator it = virtualization_type_map_.begin();
it != virtualization_type_map_.end(); ++it) {
if (it->second == type) {
return it->first;
}
}
return kOtherType;
}
const std::string &ServiceInstanceTypesMapping::IntVRouterInstanceTypeToStr(
const ServiceInstance::VRouterInstanceType &type) {
for (StrTypeToIntMap::const_iterator it = vrouter_instance_type_map_.begin();
it != virtualization_type_map_.end(); ++it) {
if (it->second == type) {
return it->first;
}
}
return kOtherType;
}
| nischalsheth/contrail-controller | src/vnsw/agent/oper/service_instance.cc | C++ | apache-2.0 | 32,777 |
"""Support for monitoring juicenet/juicepoint/juicebox based EVSE sensors."""
from __future__ import annotations
from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT,
STATE_CLASS_TOTAL_INCREASING,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import (
DEVICE_CLASS_CURRENT,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
ELECTRIC_CURRENT_AMPERE,
ELECTRIC_POTENTIAL_VOLT,
ENERGY_WATT_HOUR,
POWER_WATT,
TEMP_CELSIUS,
TIME_SECONDS,
)
from .const import DOMAIN, JUICENET_API, JUICENET_COORDINATOR
from .entity import JuiceNetDevice
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="status",
name="Charging Status",
),
SensorEntityDescription(
key="temperature",
name="Temperature",
native_unit_of_measurement=TEMP_CELSIUS,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
SensorEntityDescription(
key="voltage",
name="Voltage",
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
device_class=DEVICE_CLASS_VOLTAGE,
),
SensorEntityDescription(
key="amps",
name="Amps",
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
device_class=DEVICE_CLASS_CURRENT,
state_class=STATE_CLASS_MEASUREMENT,
),
SensorEntityDescription(
key="watts",
name="Watts",
native_unit_of_measurement=POWER_WATT,
device_class=DEVICE_CLASS_POWER,
state_class=STATE_CLASS_MEASUREMENT,
),
SensorEntityDescription(
key="charge_time",
name="Charge time",
native_unit_of_measurement=TIME_SECONDS,
icon="mdi:timer-outline",
),
SensorEntityDescription(
key="energy_added",
name="Energy added",
native_unit_of_measurement=ENERGY_WATT_HOUR,
device_class=DEVICE_CLASS_ENERGY,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the JuiceNet Sensors."""
juicenet_data = hass.data[DOMAIN][config_entry.entry_id]
api = juicenet_data[JUICENET_API]
coordinator = juicenet_data[JUICENET_COORDINATOR]
entities = [
JuiceNetSensorDevice(device, coordinator, description)
for device in api.devices
for description in SENSOR_TYPES
]
async_add_entities(entities)
class JuiceNetSensorDevice(JuiceNetDevice, SensorEntity):
"""Implementation of a JuiceNet sensor."""
def __init__(self, device, coordinator, description: SensorEntityDescription):
"""Initialise the sensor."""
super().__init__(device, description.key, coordinator)
self.entity_description = description
self._attr_name = f"{self.device.name} {description.name}"
@property
def icon(self):
"""Return the icon of the sensor."""
icon = None
if self.entity_description.key == "status":
status = self.device.status
if status == "standby":
icon = "mdi:power-plug-off"
elif status == "plugged":
icon = "mdi:power-plug"
elif status == "charging":
icon = "mdi:battery-positive"
else:
icon = self.entity_description.icon
return icon
@property
def native_value(self):
"""Return the state."""
return getattr(self.device, self.entity_description.key, None)
| lukas-hetzenecker/home-assistant | homeassistant/components/juicenet/sensor.py | Python | apache-2.0 | 3,607 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/dynamodb/DynamoDB_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace DynamoDB
{
namespace Model
{
enum class IndexStatus
{
NOT_SET,
CREATING,
UPDATING,
DELETING,
ACTIVE
};
namespace IndexStatusMapper
{
AWS_DYNAMODB_API IndexStatus GetIndexStatusForName(const Aws::String& name);
AWS_DYNAMODB_API Aws::String GetNameForIndexStatus(IndexStatus value);
} // namespace IndexStatusMapper
} // namespace Model
} // namespace DynamoDB
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-dynamodb/include/aws/dynamodb/model/IndexStatus.h | C | apache-2.0 | 660 |
package org.docksidestage.app.web.lido.auth;
import org.lastaflute.web.validation.Required;
/**
* @author s.tadokoro
* @author jflute
*/
public class SigninBody {
@Required
public String account;
@Required
public String password;
} | dbflute-example/dbflute-example-with-non-rdb | src/main/java/org/docksidestage/app/web/lido/auth/SigninBody.java | Java | apache-2.0 | 253 |
#!/bin/bash
# nginx -s reload
logger "altprobe: run of iprepup-modsec.sh"
| olegzhr/altprobe | src/scripts/iprepup-modsec.sh | Shell | apache-2.0 | 76 |
package linprogMPC.helper;
public class OptimizationProblem {
public double[] lambda;
public double[] h;
public double[][] g;
public double[] b_eq;
public double[][] a_eq;
public double[] x_lb;
public double[] x_ub;
public String[] namesUB;
int nrOfProducers;
int nrOfStorages;
int nrOfCouplers;
int marketmatrices = 4; // selling/buying(2) of electricity/heat(2) und das ganze mal Anzahl nMPC
public OptimizationProblem(int nStepsMPC, int nrOfProducers, int nrOfStorages, int nrOfCouplers) {
this.nrOfProducers = nrOfProducers;
this.nrOfStorages = nrOfStorages;
this.nrOfCouplers = nrOfCouplers;
lambda = new double[nStepsMPC*(nrOfProducers+(2*nrOfStorages) + nrOfCouplers + marketmatrices)];
h = new double[nStepsMPC*2*nrOfStorages];
g = new double[nStepsMPC*2*nrOfStorages][nStepsMPC*(nrOfProducers+(2*nrOfStorages)+nrOfCouplers+marketmatrices)];
b_eq = new double[2*nStepsMPC];
a_eq = new double[2*nStepsMPC][nStepsMPC*(nrOfProducers+(2*nrOfStorages)+nrOfCouplers+marketmatrices)];
x_lb = new double[nStepsMPC*(nrOfProducers+(2*nrOfStorages)+nrOfCouplers+marketmatrices)];
x_ub = new double[nStepsMPC*(nrOfProducers+(2*nrOfStorages)+nrOfCouplers+marketmatrices)];
namesUB = new String[nStepsMPC*(nrOfProducers+(2*nrOfStorages)+nrOfCouplers+marketmatrices)];
//System.out.println(nStepsMPC + " * ( " + nrOfProducers + " " + nrOfStorages + " " + nrOfCouplers + " und " + marketmatrices + ")");
}
public int getNumberofProducers() {
return nrOfProducers;
}
public int getNumberofStorages() {
return nrOfStorages;
}
public int getNumberofCouplers() {
return nrOfCouplers;
}
@Override
public String toString() {
String result = "";
/*
result += "OptimizationProblem:\n";
result += "Producers: "+this.nrOfProducers;
result += " Storages: "+this.nrOfStorages;
result += " Couplers: "+this.nrOfCouplers + "\n";
*/
result += "A: " + a_eq.length + " x " + a_eq[0].length + "\n";
result += "b: " + b_eq.length + "\n";
/*
result += "h: " + h.length + "\n";
if (g.length == 0) {
result += "G: 0 x 0\n";
} else result += "G: " + g.length + " x " + g[0].length + "\n";
result += "lb: " + x_lb.length + "\n";
result += "ub: " + x_ub.length + "\n";
*/
return result;
}
}
| SES-fortiss/SmartGridCoSimulation | projects/previousProjects/memapLinProgDenisThesis_2Houses/src/main/java/linprogMPC/helper/OptimizationProblem.java | Java | apache-2.0 | 2,325 |
/*
* Copyright 2008 The Closure Compiler Authors.
*
* 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 com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.ObjectTypeI;
import com.google.javascript.rhino.StaticSourceFile;
import com.google.javascript.rhino.TypeI;
import com.google.javascript.rhino.TypeIRegistry;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.ObjectType;
import java.util.ArrayDeque;
import javax.annotation.Nullable;
/**
* A compiler pass that checks that the programmer has obeyed all the access
* control restrictions indicated by JSDoc annotations, like
* {@code @private} and {@code @deprecated}.
*
* Because access control restrictions are attached to type information,
* it's important that TypedScopeCreator, TypeInference, and InferJSDocInfo
* all run before this pass. TypedScopeCreator creates and resolves types,
* TypeInference propagates those types across the AST, and InferJSDocInfo
* propagates JSDoc across the types.
*
* @author [email protected] (Nick Santos)
*/
class CheckAccessControls implements ScopedCallback, HotSwapCompilerPass {
static final DiagnosticType DEPRECATED_NAME = DiagnosticType.disabled(
"JSC_DEPRECATED_VAR",
"Variable {0} has been deprecated.");
static final DiagnosticType DEPRECATED_NAME_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_VAR_REASON",
"Variable {0} has been deprecated: {1}");
static final DiagnosticType DEPRECATED_PROP = DiagnosticType.disabled(
"JSC_DEPRECATED_PROP",
"Property {0} of type {1} has been deprecated.");
static final DiagnosticType DEPRECATED_PROP_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_PROP_REASON",
"Property {0} of type {1} has been deprecated: {2}");
static final DiagnosticType DEPRECATED_CLASS = DiagnosticType.disabled(
"JSC_DEPRECATED_CLASS",
"Class {0} has been deprecated.");
static final DiagnosticType DEPRECATED_CLASS_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_CLASS_REASON",
"Class {0} has been deprecated: {1}");
static final DiagnosticType BAD_PACKAGE_PROPERTY_ACCESS =
DiagnosticType.error(
"JSC_BAD_PACKAGE_PROPERTY_ACCESS",
"Access to package-private property {0} of {1} not allowed here.");
static final DiagnosticType BAD_PRIVATE_GLOBAL_ACCESS =
DiagnosticType.error(
"JSC_BAD_PRIVATE_GLOBAL_ACCESS",
"Access to private variable {0} not allowed outside file {1}.");
static final DiagnosticType BAD_PRIVATE_PROPERTY_ACCESS =
DiagnosticType.warning(
"JSC_BAD_PRIVATE_PROPERTY_ACCESS",
"Access to private property {0} of {1} not allowed here.");
static final DiagnosticType BAD_PROTECTED_PROPERTY_ACCESS =
DiagnosticType.warning(
"JSC_BAD_PROTECTED_PROPERTY_ACCESS",
"Access to protected property {0} of {1} not allowed here.");
static final DiagnosticType
BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY =
DiagnosticType.error(
"JSC_BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY",
"Overridden property {0} in file with fileoverview visibility {1}" +
" must explicitly redeclare superclass visibility");
static final DiagnosticType PRIVATE_OVERRIDE =
DiagnosticType.warning(
"JSC_PRIVATE_OVERRIDE",
"Overriding private property of {0}.");
static final DiagnosticType EXTEND_FINAL_CLASS =
DiagnosticType.error(
"JSC_EXTEND_FINAL_CLASS",
"{0} is not allowed to extend final class {1}.");
static final DiagnosticType VISIBILITY_MISMATCH =
DiagnosticType.warning(
"JSC_VISIBILITY_MISMATCH",
"Overriding {0} property of {1} with {2} property.");
static final DiagnosticType CONST_PROPERTY_REASSIGNED_VALUE =
DiagnosticType.warning(
"JSC_CONSTANT_PROPERTY_REASSIGNED_VALUE",
"constant property {0} assigned a value more than once");
static final DiagnosticType CONST_PROPERTY_DELETED =
DiagnosticType.warning(
"JSC_CONSTANT_PROPERTY_DELETED",
"constant property {0} cannot be deleted");
static final DiagnosticType CONVENTION_MISMATCH =
DiagnosticType.warning(
"JSC_CONVENTION_MISMATCH",
"Declared access conflicts with access convention.");
private final AbstractCompiler compiler;
private final TypeIRegistry typeRegistry;
private final boolean enforceCodingConventions;
// State about the current traversal.
private int deprecatedDepth = 0;
private final ArrayDeque<TypeI> currentClassStack = new ArrayDeque<>();
private final TypeI noTypeSentinel;
private ImmutableMap<StaticSourceFile, Visibility> defaultVisibilityForFiles;
private final Multimap<TypeI, String> initializedConstantProperties;
CheckAccessControls(
AbstractCompiler compiler, boolean enforceCodingConventions) {
this.compiler = compiler;
this.typeRegistry = compiler.getTypeIRegistry();
this.initializedConstantProperties = HashMultimap.create();
this.enforceCodingConventions = enforceCodingConventions;
this.noTypeSentinel = typeRegistry.getNativeType(JSTypeNative.NO_TYPE);
}
@Override
public void process(Node externs, Node root) {
CollectFileOverviewVisibility collectPass =
new CollectFileOverviewVisibility(compiler);
collectPass.process(externs, root);
defaultVisibilityForFiles = collectPass.getFileOverviewVisibilityMap();
NodeTraversal.traverseTyped(compiler, externs, this);
NodeTraversal.traverseTyped(compiler, root, this);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
CollectFileOverviewVisibility collectPass =
new CollectFileOverviewVisibility(compiler);
collectPass.hotSwapScript(scriptRoot, originalRoot);
defaultVisibilityForFiles = collectPass.getFileOverviewVisibilityMap();
NodeTraversal.traverseTyped(compiler, scriptRoot, this);
}
@Override
public void enterScope(NodeTraversal t) {
if (!t.inGlobalScope()) {
Node n = t.getScopeRoot();
Node parent = n.getParent();
if (isDeprecatedFunction(n)) {
deprecatedDepth++;
}
TypeI prevClass = getCurrentClass();
TypeI currentClass = prevClass == null
? getClassOfMethod(n, parent)
: prevClass;
// ArrayDeques can't handle nulls, so we reuse the bottom type
// as a null sentinel.
currentClassStack.addFirst(currentClass == null
? noTypeSentinel
: currentClass);
}
}
@Override
public void exitScope(NodeTraversal t) {
if (!t.inGlobalScope()) {
Node n = t.getScopeRoot();
if (isDeprecatedFunction(n)) {
deprecatedDepth--;
}
currentClassStack.pop();
}
}
/**
* Gets the type of the class that "owns" a method, or null if
* we know that its un-owned.
*/
private TypeI getClassOfMethod(Node n, Node parent) {
if (parent.isAssign()) {
Node lValue = parent.getFirstChild();
if (NodeUtil.isGet(lValue)) {
// We have an assignment of the form "a.b = ...".
TypeI lValueType = lValue.getTypeI();
if (lValueType != null && lValueType.isOriginalConstructor()) {
// If a.b is a constructor, then everything in this function
// belongs to the "a.b" type.
return (lValueType.toMaybeFunctionType()).getInstanceType();
} else {
// If a.b is not a constructor, then treat this as a method
// of whatever type is on "a".
return normalizeClassType(lValue.getFirstChild().getTypeI());
}
} else {
// We have an assignment of the form "a = ...", so pull the
// type off the "a".
return normalizeClassType(lValue.getTypeI());
}
} else if (NodeUtil.isFunctionDeclaration(n) ||
parent.isName()) {
return normalizeClassType(n.getTypeI());
} else if (parent.isStringKey()
|| parent.isGetterDef() || parent.isSetterDef()) {
Node objectLitParent = parent.getGrandparent();
if (!objectLitParent.isAssign()) {
return null;
}
Node className = NodeUtil.getPrototypeClassName(objectLitParent.getFirstChild());
if (className != null) {
return normalizeClassType(className.getTypeI());
}
}
return null;
}
/**
* Normalize the type of a constructor, its instance, and its prototype
* all down to the same type (the instance type).
*/
private static TypeI normalizeClassType(TypeI type) {
if (type == null || type.isUnknownType()) {
return type;
} else if (type.isOriginalConstructor()) {
return (type.toMaybeFunctionType()).getInstanceType();
} else if (type.isPrototypeObject()) {
// newtypes.JSType should never enter this codepath
Preconditions.checkState(type instanceof ObjectType);
FunctionType owner = ((ObjectType) type).getOwnerFunction();
if (owner.isConstructor()) {
return owner.getInstanceType();
}
}
return type;
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getType()) {
case NAME:
checkNameDeprecation(t, n, parent);
checkNameVisibility(t, n, parent);
break;
case GETPROP:
checkPropertyDeprecation(t, n, parent);
checkPropertyVisibility(t, n, parent);
checkConstantProperty(t, n);
break;
case STRING_KEY:
case GETTER_DEF:
case SETTER_DEF:
checkKeyVisibilityConvention(t, n, parent);
break;
case NEW:
checkConstructorDeprecation(t, n, parent);
break;
case FUNCTION:
checkFinalClassOverrides(t, n, parent);
break;
default:
break;
}
}
/**
* Checks the given NEW node to ensure that access restrictions are obeyed.
*/
private void checkConstructorDeprecation(NodeTraversal t, Node n,
Node parent) {
TypeI type = n.getTypeI();
if (type != null) {
String deprecationInfo = getTypeDeprecationInfo(type);
if (deprecationInfo != null &&
shouldEmitDeprecationWarning(t, n, parent)) {
if (!deprecationInfo.isEmpty()) {
compiler.report(
t.makeError(n, DEPRECATED_CLASS_REASON,
type.toString(), deprecationInfo));
} else {
compiler.report(
t.makeError(n, DEPRECATED_CLASS, type.toString()));
}
}
}
}
/**
* Checks the given NAME node to ensure that access restrictions are obeyed.
*/
private void checkNameDeprecation(NodeTraversal t, Node n, Node parent) {
// Don't bother checking definitions or constructors.
if (parent.isFunction() || parent.isVar() ||
parent.isNew()) {
return;
}
TypedVar var = t.getTypedScope().getVar(n.getString());
JSDocInfo docInfo = var == null ? null : var.getJSDocInfo();
if (docInfo != null && docInfo.isDeprecated() &&
shouldEmitDeprecationWarning(t, n, parent)) {
if (docInfo.getDeprecationReason() != null) {
compiler.report(
t.makeError(n, DEPRECATED_NAME_REASON, n.getString(),
docInfo.getDeprecationReason()));
} else {
compiler.report(
t.makeError(n, DEPRECATED_NAME, n.getString()));
}
}
}
/**
* Checks the given GETPROP node to ensure that access restrictions are
* obeyed.
*/
private void checkPropertyDeprecation(NodeTraversal t, Node n, Node parent) {
// Don't bother checking constructors.
if (parent.isNew()) {
return;
}
ObjectTypeI objectType = castToObject(dereference(n.getFirstChild().getTypeI()));
String propertyName = n.getLastChild().getString();
if (objectType != null) {
String deprecationInfo
= getPropertyDeprecationInfo(objectType, propertyName);
if (deprecationInfo != null &&
shouldEmitDeprecationWarning(t, n, parent)) {
if (!deprecationInfo.isEmpty()) {
compiler.report(
t.makeError(n, DEPRECATED_PROP_REASON, propertyName,
typeRegistry.getReadableTypeName(n.getFirstChild()),
deprecationInfo));
} else {
compiler.report(
t.makeError(n, DEPRECATED_PROP, propertyName,
typeRegistry.getReadableTypeName(n.getFirstChild())));
}
}
}
}
private boolean isPrivateByConvention(String name) {
return enforceCodingConventions
&& compiler.getCodingConvention().isPrivate(name);
}
/**
* Determines whether the given OBJECTLIT property visibility
* violates the coding convention.
* @param t The current traversal.
* @param key The objectlit key node (STRING_KEY, GETTER_DEF, SETTER_DEF).
*/
private void checkKeyVisibilityConvention(NodeTraversal t,
Node key, Node parent) {
JSDocInfo info = key.getJSDocInfo();
if (info == null) {
return;
}
if (!isPrivateByConvention(key.getString())) {
return;
}
Node assign = parent.getParent();
if (assign == null || !assign.isAssign()) {
return;
}
Node left = assign.getFirstChild();
if (!left.isGetProp()
|| !left.getLastChild().getString().equals("prototype")) {
return;
}
Visibility declaredVisibility = info.getVisibility();
// Visibility is declared to be something other than private.
if (declaredVisibility != Visibility.INHERITED
&& declaredVisibility != Visibility.PRIVATE) {
compiler.report(t.makeError(key, CONVENTION_MISMATCH));
}
}
/**
* Reports an error if the given name is not visible in the current context.
* @param t The current traversal.
* @param name The name node.
*/
private void checkNameVisibility(NodeTraversal t, Node name, Node parent) {
TypedVar var = t.getTypedScope().getVar(name.getString());
if (var == null) {
return;
}
Visibility v = checkPrivateNameConvention(
AccessControlUtils.getEffectiveNameVisibility(
name, var, defaultVisibilityForFiles), name);
switch (v) {
case PACKAGE:
if (!isPackageAccessAllowed(var, name)) {
compiler.report(
t.makeError(name, BAD_PACKAGE_PROPERTY_ACCESS,
name.getString(), var.getSourceFile().getName()));
}
break;
case PRIVATE:
if (!isPrivateAccessAllowed(var, name, parent)) {
compiler.report(
t.makeError(name, BAD_PRIVATE_GLOBAL_ACCESS,
name.getString(), var.getSourceFile().getName()));
}
break;
default:
// Nothing to do for PUBLIC and PROTECTED
// (which is irrelevant for names).
break;
}
}
/**
* Returns the effective visibility of the given name, reporting an error
* if there is a contradiction in the various sources of visibility
* (example: a variable with a trailing underscore that is declared
* {@code @public}).
*/
private Visibility checkPrivateNameConvention(Visibility v, Node name) {
if (isPrivateByConvention(name.getString())) {
if (v != Visibility.PRIVATE && v != Visibility.INHERITED) {
compiler.report(JSError.make(name, CONVENTION_MISMATCH));
}
return Visibility.PRIVATE;
}
return v;
}
private static boolean isPrivateAccessAllowed(TypedVar var, Node name, Node parent) {
StaticSourceFile varSrc = var.getSourceFile();
StaticSourceFile refSrc = name.getStaticSourceFile();
JSDocInfo docInfo = var.getJSDocInfo();
if (varSrc != null
&& refSrc != null
&& !varSrc.getName().equals(refSrc.getName())) {
return docInfo != null && docInfo.isConstructor()
&& isValidPrivateConstructorAccess(parent);
} else {
return true;
}
}
private boolean isPackageAccessAllowed(TypedVar var, Node name) {
StaticSourceFile varSrc = var.getSourceFile();
StaticSourceFile refSrc = name.getStaticSourceFile();
CodingConvention codingConvention = compiler.getCodingConvention();
if (varSrc != null && refSrc != null) {
String srcPackage = codingConvention.getPackageName(varSrc);
String refPackage = codingConvention.getPackageName(refSrc);
return srcPackage != null
&& refPackage != null
&& srcPackage.equals(refPackage);
} else {
// If the source file of either var or name is unavailable, conservatively
// assume they belong to different packages.
// TODO(brndn): by contrast, isPrivateAccessAllowed does allow
// private access when a source file is unknown. I didn't change it
// in order not to break existing code.
return false;
}
}
private void checkOverriddenPropertyVisibilityMismatch(
Visibility overriding,
Visibility overridden,
@Nullable Visibility fileOverview,
NodeTraversal t,
Node getprop) {
if (overriding == Visibility.INHERITED
&& overriding != overridden
&& fileOverview != null
&& fileOverview != Visibility.INHERITED) {
String propertyName = getprop.getLastChild().getString();
compiler.report(
t.makeError(getprop,
BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY,
propertyName,
fileOverview.name()));
}
}
@Nullable private static Visibility getOverridingPropertyVisibility(Node parent) {
JSDocInfo overridingInfo = parent.getJSDocInfo();
return overridingInfo == null || !overridingInfo.isOverride()
? null
: overridingInfo.getVisibility();
}
/**
* Checks if a constructor is trying to override a final class.
*/
private void checkFinalClassOverrides(NodeTraversal t, Node fn, Node parent) {
TypeI type = fn.getTypeI().toMaybeFunctionType();
if (type != null && type.isConstructor()) {
TypeI finalParentClass = getFinalParentClass(getClassOfMethod(fn, parent));
if (finalParentClass != null) {
compiler.report(
t.makeError(fn, EXTEND_FINAL_CLASS,
type.getDisplayName(), finalParentClass.getDisplayName()));
}
}
}
/**
* Determines whether the given constant property got reassigned
* @param t The current traversal.
* @param getprop The getprop node.
*/
private void checkConstantProperty(NodeTraversal t,
Node getprop) {
// Check whether the property is modified
Node parent = getprop.getParent();
boolean isDelete = parent.isDelProp();
if (!(NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == getprop)
&& !parent.isInc() && !parent.isDec()
&& !isDelete) {
return;
}
ObjectTypeI objectType = castToObject(dereference(getprop.getFirstChild().getTypeI()));
String propertyName = getprop.getLastChild().getString();
boolean isConstant = isPropertyDeclaredConstant(objectType, propertyName);
// Check whether constant properties are reassigned
if (isConstant) {
JSDocInfo info = parent.getJSDocInfo();
if (info != null && info.getSuppressions().contains("const")) {
return;
}
if (isDelete) {
compiler.report(
t.makeError(getprop, CONST_PROPERTY_DELETED, propertyName));
return;
}
// Can't check for constant properties on generic function types.
// TODO(johnlenz): I'm not 100% certain this is necessary, or if
// the type is being inspected incorrectly.
if (objectType == null
|| (objectType.isFunctionType()
&& !objectType.toMaybeFunctionType().isConstructor())) {
return;
}
ObjectTypeI oType = objectType;
while (oType != null) {
if (initializedConstantProperties.containsEntry(
oType, propertyName)) {
compiler.report(
t.makeError(getprop, CONST_PROPERTY_REASSIGNED_VALUE,
propertyName));
break;
}
oType = oType.getPrototypeObject();
}
initializedConstantProperties.put(objectType,
propertyName);
// Add the prototype when we're looking at an instance object
if (objectType.isInstanceType()) {
ObjectTypeI prototype = objectType.getPrototypeObject();
if (prototype != null && prototype.hasProperty(propertyName)) {
initializedConstantProperties.put(prototype, propertyName);
}
}
}
}
/**
* Reports an error if the given property is not visible in the current
* context.
* @param t The current traversal.
* @param getprop The getprop node.
*/
private void checkPropertyVisibility(NodeTraversal t,
Node getprop, Node parent) {
JSDocInfo jsdoc = parent.getJSDocInfo();
if (jsdoc != null && jsdoc.getSuppressions().contains("visibility")) {
return;
}
ObjectTypeI referenceType = castToObject(dereference(getprop.getFirstChild().getTypeI()));
String propertyName = getprop.getLastChild().getString();
boolean isPrivateByConvention = isPrivateByConvention(propertyName);
if (isPrivateByConvention
&& propertyIsDeclaredButNotPrivate(getprop, parent)) {
compiler.report(t.makeError(getprop, CONVENTION_MISMATCH));
return;
}
StaticSourceFile definingSource = AccessControlUtils.getDefiningSource(
getprop, referenceType, propertyName);
boolean isClassType = false;
// Is this a normal property access, or are we trying to override
// an existing property?
boolean isOverride = jsdoc != null
&& parent.isAssign()
&& parent.getFirstChild() == getprop;
ObjectTypeI objectType = AccessControlUtils.getObjectType(
referenceType, isOverride, propertyName);
Visibility fileOverviewVisibility =
defaultVisibilityForFiles.get(definingSource);
Visibility visibility = AccessControlUtils.getEffectivePropertyVisibility(
getprop,
referenceType,
defaultVisibilityForFiles,
enforceCodingConventions ? compiler.getCodingConvention() : null);
if (isOverride) {
Visibility overriding = getOverridingPropertyVisibility(parent);
if (overriding != null) {
checkOverriddenPropertyVisibilityMismatch(
overriding, visibility, fileOverviewVisibility, t, getprop);
}
}
if (objectType != null) {
Node node = objectType.getOwnPropertyDefsite(propertyName);
if (node == null) {
// Assume the property is public.
return;
}
definingSource = node.getStaticSourceFile();
isClassType = objectType.getOwnPropertyJSDocInfo(propertyName).isConstructor();
} else if (isPrivateByConvention) {
// We can only check visibility references if we know what file
// it was defined in.
objectType = referenceType;
} else if (fileOverviewVisibility == null) {
// Otherwise just assume the property is public.
return;
}
StaticSourceFile referenceSource = getprop.getStaticSourceFile();
if (isOverride) {
boolean sameInput = referenceSource != null
&& referenceSource.getName().equals(definingSource.getName());
checkOverriddenPropertyVisibility(
t,
getprop,
parent,
visibility,
fileOverviewVisibility,
objectType,
sameInput);
} else {
checkNonOverriddenPropertyVisibility(
t,
getprop,
parent,
visibility,
isClassType,
objectType,
referenceSource,
definingSource);
}
}
private static boolean propertyIsDeclaredButNotPrivate(Node getprop, Node parent) {
// This is a declaration with JSDoc
JSDocInfo info = NodeUtil.getBestJSDocInfo(getprop);
if ((parent.isAssign() || parent.isExprResult())
&& parent.getFirstChild() == getprop
&& info != null) {
Visibility declaredVisibility = info.getVisibility();
if (declaredVisibility != Visibility.PRIVATE
&& declaredVisibility != Visibility.INHERITED) {
return true;
}
}
return false;
}
private void checkOverriddenPropertyVisibility(
NodeTraversal t,
Node getprop,
Node parent,
Visibility visibility,
Visibility fileOverviewVisibility,
ObjectTypeI objectType,
boolean sameInput) {
// Check an ASSIGN statement that's trying to override a property
// on a superclass.
JSDocInfo overridingInfo = parent.getJSDocInfo();
Visibility overridingVisibility = overridingInfo == null
? Visibility.INHERITED
: overridingInfo.getVisibility();
// Check that:
// (a) the property *can* be overridden,
// (b) the visibility of the override is the same as the
// visibility of the original property,
// (c) the visibility is explicitly redeclared if the override is in
// a file with default visibility in the @fileoverview block.
if (visibility == Visibility.PRIVATE && !sameInput) {
compiler.report(
t.makeError(getprop, PRIVATE_OVERRIDE,
objectType.toString()));
} else if (overridingVisibility != Visibility.INHERITED
&& overridingVisibility != visibility
&& fileOverviewVisibility == null) {
compiler.report(
t.makeError(getprop, VISIBILITY_MISMATCH,
visibility.name(), objectType.toString(),
overridingVisibility.name()));
}
}
private void checkNonOverriddenPropertyVisibility(
NodeTraversal t,
Node getprop,
Node parent,
Visibility visibility,
boolean isClassType,
ObjectTypeI objectType,
StaticSourceFile referenceSource,
StaticSourceFile definingSource) {
// private access is always allowed in the same file.
if (referenceSource != null
&& definingSource != null
&& referenceSource.getName().equals(definingSource.getName())) {
return;
}
TypeI ownerType = normalizeClassType(objectType);
switch (visibility) {
case PACKAGE:
checkPackagePropertyVisibility(t, getprop, referenceSource, definingSource);
break;
case PRIVATE:
checkPrivatePropertyVisibility(t, getprop, parent, isClassType, ownerType);
break;
case PROTECTED:
checkProtectedPropertyVisibility(t, getprop, ownerType);
break;
default:
break;
}
}
private void checkPackagePropertyVisibility(
NodeTraversal t,
Node getprop,
StaticSourceFile referenceSource,
StaticSourceFile definingSource) {
CodingConvention codingConvention = compiler.getCodingConvention();
String refPackage = codingConvention.getPackageName(referenceSource);
String defPackage = codingConvention.getPackageName(definingSource);
if (refPackage == null
|| defPackage == null
|| !refPackage.equals(defPackage)) {
String propertyName = getprop.getLastChild().getString();
compiler.report(
t.makeError(getprop, BAD_PACKAGE_PROPERTY_ACCESS,
propertyName,
typeRegistry.getReadableTypeName(getprop.getFirstChild())));
}
}
@Nullable private TypeI getCurrentClass() {
TypeI cur = currentClassStack.peekFirst();
return cur == noTypeSentinel
? null
: cur;
}
private void checkPrivatePropertyVisibility(
NodeTraversal t,
Node getprop,
Node parent,
boolean isClassType,
TypeI ownerType) {
TypeI currentClass = getCurrentClass();
if (currentClass != null && ownerType.isEquivalentTo(currentClass)) {
return;
}
if (isClassType && isValidPrivateConstructorAccess(parent)) {
return;
}
// private access is not allowed outside the file from a different
// enclosing class.
TypeI accessedType = getprop.getFirstChild().getTypeI();
String propertyName = getprop.getLastChild().getString();
String readableTypeName = ownerType.equals(accessedType)
? typeRegistry.getReadableTypeName(getprop.getFirstChild())
: ownerType.toString();
compiler.report(
t.makeError(getprop,
BAD_PRIVATE_PROPERTY_ACCESS,
propertyName,
readableTypeName));
}
private void checkProtectedPropertyVisibility(
NodeTraversal t,
Node getprop,
TypeI ownerType) {
// There are 3 types of legal accesses of a protected property:
// 1) Accesses in the same file
// 2) Overriding the property in a subclass
// 3) Accessing the property from inside a subclass
// The first two have already been checked for.
TypeI currentClass = getCurrentClass();
if (currentClass == null || !currentClass.isSubtypeOf(ownerType)) {
String propertyName = getprop.getLastChild().getString();
compiler.report(
t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS,
propertyName,
typeRegistry.getReadableTypeName(getprop.getFirstChild())));
}
}
/**
* Whether the given access of a private constructor is legal.
*
* For example,
* new PrivateCtor_(); // not legal
* PrivateCtor_.newInstance(); // legal
* x instanceof PrivateCtor_ // legal
*
* This is a weird special case, because our visibility system is inherited
* from Java, and JavaScript has no distinction between classes and
* constructors like Java does.
*
* We may want to revisit this if we decide to make the restrictions tighter.
*/
private static boolean isValidPrivateConstructorAccess(Node parent) {
return !parent.isNew();
}
/**
* Determines whether a deprecation warning should be emitted.
* @param t The current traversal.
* @param n The node which we are checking.
* @param parent The parent of the node which we are checking.
*/
private boolean shouldEmitDeprecationWarning(
NodeTraversal t, Node n, Node parent) {
// In the global scope, there are only two kinds of accesses that should
// be flagged for warnings:
// 1) Calls of deprecated functions and methods.
// 2) Instantiations of deprecated classes.
// For now, we just let everything else by.
if (t.inGlobalScope()) {
if (!((parent.isCall() && parent.getFirstChild() == n) ||
n.isNew())) {
return false;
}
}
// We can always assign to a deprecated property, to keep it up to date.
if (n.isGetProp() && n == parent.getFirstChild() &&
NodeUtil.isAssignmentOp(parent)) {
return false;
}
// Don't warn if the node is just declaring the property, not reading it.
if (n.isGetProp() && parent.isExprResult() &&
n.getJSDocInfo().isDeprecated()) {
return false;
}
return !canAccessDeprecatedTypes(t);
}
/**
* Returns whether it's currently OK to access deprecated names and
* properties.
*
* There are 3 exceptions when we're allowed to use a deprecated
* type or property:
* 1) When we're in a deprecated function.
* 2) When we're in a deprecated class.
* 3) When we're in a static method of a deprecated class.
*/
private boolean canAccessDeprecatedTypes(NodeTraversal t) {
Node scopeRoot = t.getScopeRoot();
Node scopeRootParent = scopeRoot.getParent();
return
// Case #1
(deprecatedDepth > 0) ||
// Case #2
(getTypeDeprecationInfo(t.getTypedScope().getTypeOfThis()) != null) ||
// Case #3
(scopeRootParent != null && scopeRootParent.isAssign() &&
getTypeDeprecationInfo(
getClassOfMethod(scopeRoot, scopeRootParent)) != null);
}
/**
* Returns whether this is a function node annotated as deprecated.
*/
private static boolean isDeprecatedFunction(Node n) {
if (n.isFunction()) {
TypeI type = n.getTypeI();
if (type != null) {
return getTypeDeprecationInfo(type) != null;
}
}
return false;
}
/**
* Returns the deprecation reason for the type if it is marked
* as being deprecated. Returns empty string if the type is deprecated
* but no reason was given. Returns null if the type is not deprecated.
*/
private static String getTypeDeprecationInfo(TypeI type) {
if (type == null) {
return null;
}
JSDocInfo info = type.getJSDocInfo();
if (info != null && info.isDeprecated()) {
if (info.getDeprecationReason() != null) {
return info.getDeprecationReason();
}
return "";
}
ObjectTypeI objType = castToObject(type);
if (objType != null) {
ObjectTypeI implicitProto = objType.getPrototypeObject();
if (implicitProto != null) {
return getTypeDeprecationInfo(implicitProto);
}
}
return null;
}
/**
* Returns if a property is declared constant.
*/
private boolean isPropertyDeclaredConstant(
ObjectTypeI objectType, String prop) {
if (enforceCodingConventions
&& compiler.getCodingConvention().isConstant(prop)) {
return true;
}
for (;
objectType != null;
objectType = objectType.getPrototypeObject()) {
JSDocInfo docInfo = objectType.getOwnPropertyJSDocInfo(prop);
if (docInfo != null && docInfo.isConstant()) {
return true;
}
}
return false;
}
/**
* Returns the deprecation reason for the property if it is marked
* as being deprecated. Returns empty string if the property is deprecated
* but no reason was given. Returns null if the property is not deprecated.
*/
private static String getPropertyDeprecationInfo(ObjectTypeI type,
String prop) {
JSDocInfo info = type.getOwnPropertyJSDocInfo(prop);
if (info != null && info.isDeprecated()) {
if (info.getDeprecationReason() != null) {
return info.getDeprecationReason();
}
return "";
}
ObjectTypeI implicitProto = type.getPrototypeObject();
if (implicitProto != null) {
return getPropertyDeprecationInfo(implicitProto, prop);
}
return null;
}
/**
* Dereference a type, autoboxing it and filtering out null.
*/
private static ObjectTypeI dereference(TypeI type) {
return type == null ? null : type.autoboxAndGetObject();
}
/**
* Returns the super class of the given type that has a constructor.
*/
private static ObjectTypeI getFinalParentClass(TypeI type) {
if (type != null) {
ObjectTypeI iproto = castToObject(type).getPrototypeObject();
while (iproto != null && iproto.getConstructor() == null) {
iproto = iproto.getPrototypeObject();
}
if (iproto != null) {
Node source = iproto.getConstructor().getSource();
JSDocInfo jsDoc = source != null ? NodeUtil.getBestJSDocInfo(source) : null;
if (jsDoc != null && jsDoc.isConstant()) {
return iproto;
}
}
}
return null;
}
@Nullable
private static ObjectTypeI castToObject(@Nullable TypeI type) {
return type == null ? null : type.toMaybeObjectType();
}
}
| Medium/closure-compiler | src/com/google/javascript/jscomp/CheckAccessControls.java | Java | apache-2.0 | 36,332 |
# -*- coding: utf-8 -*-
import unittest
import string
from . import tests
from .tests import *
from . import binding
from .binding import Context
from . import contenthandling
from .contenthandling import ContentHandler
from . import generators
PYTHON_MAJOR_VERSION = sys.version_info[0]
if PYTHON_MAJOR_VERSION > 2:
from unittest import mock
else:
import mock
# Python 3 compatibility shims
from . import six
from .six import binary_type
from .six import text_type
class TestsTest(unittest.TestCase):
""" Testing for basic REST test methods, how meta! """
# Parsing methods
def test_coerce_to_string(self):
self.assertEqual(u'1', coerce_to_string(1))
self.assertEqual(u'stuff', coerce_to_string(u'stuff'))
self.assertEqual(u'stuff', coerce_to_string('stuff'))
self.assertEqual(u'st😽uff', coerce_to_string(u'st😽uff'))
self.assertRaises(TypeError, coerce_to_string, {'key': 'value'})
self.assertRaises(TypeError, coerce_to_string, None)
def test_coerce_http_method(self):
self.assertEqual(u'HEAD', coerce_http_method(u'hEaD'))
self.assertEqual(u'HEAD', coerce_http_method(b'hEaD'))
self.assertRaises(TypeError, coerce_http_method, 5)
self.assertRaises(TypeError, coerce_http_method, None)
self.assertRaises(TypeError, coerce_http_method, u'')
def test_coerce_string_to_ascii(self):
self.assertEqual(b'stuff', coerce_string_to_ascii(u'stuff'))
self.assertRaises(UnicodeEncodeError, coerce_string_to_ascii, u'st😽uff')
self.assertRaises(TypeError, coerce_string_to_ascii, 1)
self.assertRaises(TypeError, coerce_string_to_ascii, None)
def test_coerce_list_of_ints(self):
self.assertEqual([1], coerce_list_of_ints(1))
self.assertEqual([2], coerce_list_of_ints('2'))
self.assertEqual([18], coerce_list_of_ints(u'18'))
self.assertEqual([1, 2], coerce_list_of_ints([1, 2]))
self.assertEqual([1, 2], coerce_list_of_ints([1, '2']))
try:
val = coerce_list_of_ints('goober')
fail("Shouldn't allow coercing a random string to a list of ints")
except:
pass
def test_parse_curloption(self):
""" Verify issue with curloption handling from https://github.com/svanoort/pyresttest/issues/138 """
testdefinition = {"url": "/ping", "curl_option_timeout": 14, 'curl_Option_interface': 'doesnotexist'}
test = Test.parse_test('', testdefinition)
print(test.curl_options)
self.assertTrue('TIMEOUT' in test.curl_options)
self.assertTrue('INTERFACE' in test.curl_options)
self.assertEqual(14, test.curl_options['TIMEOUT'])
self.assertEqual('doesnotexist', test.curl_options['INTERFACE'])
def test_parse_illegalcurloption(self):
testdefinition = {"url": "/ping", 'curl_Option_special': 'value'}
try:
test = Test.parse_test('', testdefinition)
fail("Error: test parsing should fail when given illegal curl option")
except ValueError:
pass
def test_parse_test(self):
""" Test basic ways of creating test objects from input object structure """
# Most basic case
myinput = {"url": "/ping", "method": "DELETE", "NAME": "foo", "group": "bar",
"body": "<xml>input</xml>", "headers": {"Accept": "Application/json"}}
test = Test.parse_test('', myinput)
self.assertEqual(test.url, myinput['url'])
self.assertEqual(test.method, myinput['method'])
self.assertEqual(test.name, myinput['NAME'])
self.assertEqual(test.group, myinput['group'])
self.assertEqual(test.body, myinput['body'])
# Test headers match
self.assertFalse(set(test.headers.values()) ^
set(myinput['headers'].values()))
# Happy path, only gotcha is that it's a POST, so must accept 200 or
# 204 response code
myinput = {"url": "/ping", "meThod": "POST"}
test = Test.parse_test('', myinput)
self.assertEqual(test.url, myinput['url'])
self.assertEqual(test.method, myinput['meThod'])
self.assertEqual(test.expected_status, [200, 201, 204])
# Authentication
myinput = {"url": "/ping", "method": "GET",
"auth_username": "foo", "auth_password": "bar"}
test = Test.parse_test('', myinput)
self.assertEqual('foo', myinput['auth_username'])
self.assertEqual('bar', myinput['auth_password'])
self.assertEqual(test.expected_status, [200])
# Test that headers propagate
myinput = {"url": "/ping", "method": "GET",
"headers": [{"Accept": "application/json"}, {"Accept-Encoding": "gzip"}]}
test = Test.parse_test('', myinput)
expected_headers = {"Accept": "application/json",
"Accept-Encoding": "gzip"}
self.assertEqual(test.url, myinput['url'])
self.assertEqual(test.method, 'GET')
self.assertEqual(test.expected_status, [200])
self.assertTrue(isinstance(test.headers, dict))
# Test no header mappings differ
self.assertFalse(set(test.headers.values()) ^
set(expected_headers.values()))
# Test expected status propagates and handles conversion to integer
myinput = [{"url": "/ping"}, {"name": "cheese"},
{"expected_status": ["200", 204, "202"]}]
test = Test.parse_test('', myinput)
self.assertEqual(test.name, "cheese")
self.assertEqual(test.expected_status, [200, 204, 202])
self.assertFalse(test.is_context_modifier())
def test_parse_nonstandard_http_method(self):
myinput = {"url": "/ping", "method": "PATCH", "NAME": "foo", "group": "bar",
"body": "<xml>input</xml>", "headers": {"Accept": "Application/json"}}
test = Test.parse_test('', myinput)
self.assertEqual("PATCH", test.method)
try:
myinput['method'] = 1
test.parse_test('', myinput)
fail("Should fail to pass a nonstring HTTP method")
except TypeError:
pass
try:
myinput['method'] = ''
test.parse_test('', myinput)
fail("Should fail to pass a nonstring HTTP method")
except (TypeError, AssertionError):
pass
def test_parse_custom_curl(self):
# Basic case
myinput = {'url': '/ping', 'name': 'basic',
'curl_option_followLocatION': True}
test = Test.parse_test('', myinput)
options = test.curl_options
self.assertEqual(1, len(options))
self.assertEqual(True, options['FOLLOWLOCATION'])
# Test parsing with two options
myinput['curl_option_maxredirs'] = 99
test = Test.parse_test('', myinput)
options = test.curl_options
self.assertEqual(2, len(options))
self.assertEqual(True, options['FOLLOWLOCATION'])
self.assertEqual(99, options['MAXREDIRS'])
# Invalid curl option
myinput['curl_option_BOGUSOPTION'] = 'i_fail'
try:
test.parse_test('', myinput)
fail("Should throw an exception when invalid curl option used, but didn't!")
except ValueError:
pass
# We can't use version specific skipIf decorator b/c python 2.6 unittest lacks it
def test_use_custom_curl(self):
""" Test that test method really does configure correctly """
if PYTHON_MAJOR_VERSION > 2:
# In python 3, use of mocks for the curl setopt version (or via setattr)
# Will not modify the actual curl object... so test fails
print("Skipping test of CURL configuration for redirects because the mocks fail")
raise unittest.SkipTest("Skipping test of CURL configuration for redirects because the mocks fail")
test = Test()
test.curl_options = {'FOLLOWLOCATION': True, 'MAXREDIRS': 5}
mock_handle = pycurl.Curl()
mock_handle.setopt = mock.MagicMock(return_value=True)
test.configure_curl(curl_handle=mock_handle)
# print mock_handle.setopt.call_args_list # Debugging
mock_handle.setopt.assert_any_call(mock_handle.FOLLOWLOCATION, True)
mock_handle.setopt.assert_any_call(mock_handle.MAXREDIRS, 5)
mock_handle.close()
def test_basic_auth(self):
""" Test that basic auth configures correctly """
if PYTHON_MAJOR_VERSION > 2:
# In python 3, use of mocks for the curl setopt version (or via setattr)
# Will not modify the actual curl object... so test fails
print("Skipping test of CURL configuration for basic auth because the mocks fail in Py3")
return
test = Test()
test.auth_username = u'bobbyg'
test.auth_password = 'password'
mock_handle = pycurl.Curl()
mock_handle.setopt = mock.MagicMock(return_value=True)
test.configure_curl(curl_handle=mock_handle)
# print mock_handle.setopt.call_args_list # Debugging
mock_handle.setopt.assert_any_call(mock_handle.USERPWD, b'bobbyg:password')
mock_handle.close()
def test_parse_test_templated_headers(self):
""" Test parsing with templated headers """
heads = {"Accept": "Application/json", "$AuthHeader": "$AuthString"}
templated_heads = {"Accept": "Application/json",
"apikey": "magic_passWord"}
context = Context()
context.bind_variables(
{'AuthHeader': 'apikey', 'AuthString': 'magic_passWord'})
# If this doesn't throw errors we have silent failures
input_invalid = {"url": "/ping", "method": "DELETE", "NAME": "foo",
"group": "bar", "body": "<xml>input</xml>", "headers": 'goat'}
try:
test = Test.parse_test('', input_invalid)
test.fail("Expected error not thrown")
except TypeError:
pass
def assert_dict_eq(dict1, dict2):
""" Test dicts are equal """
self.assertEqual(2, len(set(dict1.items()) & set(dict2.items())))
# Before templating is used
input = {"url": "/ping", "method": "DELETE", "NAME": "foo",
"group": "bar", "body": "<xml>input</xml>", "headers": heads}
test = Test.parse_test('', input)
assert_dict_eq(heads, test.headers)
assert_dict_eq(heads, test.get_headers(context=context))
# After templating applied
input_templated = {"url": "/ping", "method": "DELETE", "NAME": "foo",
"group": "bar", "body": "<xml>input</xml>", "headers": {'tEmplate': heads}}
test2 = Test.parse_test('', input_templated)
assert_dict_eq(heads, test2.get_headers())
assert_dict_eq(templated_heads, test2.get_headers(context=context))
def test_parse_test_validators(self):
""" Test that for a test it can parse the validators section correctly """
input = {"url": '/test', 'validators': [
{'comparator': {
'jsonpath_mini': 'key.val',
'comparator': 'eq',
'expected': 3
}},
{'extract_test': {'jsonpath_mini': 'key.val', 'test': 'exists'}}
]}
test = Test.parse_test('', input)
self.assertTrue(test.validators)
self.assertEqual(2, len(test.validators))
self.assertTrue(isinstance(
test.validators[0], validators.ComparatorValidator))
self.assertTrue(isinstance(
test.validators[1], validators.ExtractTestValidator))
# Check the validators really work
self.assertTrue(test.validators[0].validate(
'{"id": 3, "key": {"val": 3}}'))
def test_parse_validators_fail(self):
""" Test an invalid validator syntax throws exception """
input = {"url": '/test', 'validators': ['comparator']}
try:
test = Test.parse_test('', input)
self.fail(
"Should throw exception if not giving a dictionary-type comparator")
except TypeError:
pass
def test_parse_extractor_bind(self):
""" Test parsing of extractors """
test_config = {
"url": '/api',
'extract_binds': {
'id': {'jsonpath_mini': 'idfield'},
'name': {'jsonpath_mini': 'firstname'}
}
}
test = Test.parse_test('', test_config)
self.assertTrue(test.extract_binds)
self.assertEqual(2, len(test.extract_binds))
self.assertTrue('id' in test.extract_binds)
self.assertTrue('name' in test.extract_binds)
# Test extractors config'd correctly for extraction
myjson = '{"idfield": 3, "firstname": "bob"}'
extracted = test.extract_binds['id'].extract(myjson)
self.assertEqual(3, extracted)
extracted = test.extract_binds['name'].extract(myjson)
self.assertEqual('bob', extracted)
def test_parse_extractor_errors(self):
""" Test that expected errors are thrown on parsing """
test_config = {
"url": '/api',
'extract_binds': {'id': {}}
}
try:
test = Test.parse_test('', test_config)
self.fail("Should throw an error when doing empty mapping")
except TypeError:
pass
test_config['extract_binds']['id'] = {
'jsonpath_mini': 'query',
'test': 'anotherquery'
}
try:
test = Test.parse_test('', test_config)
self.fail("Should throw an error when given multiple extractors")
except ValueError as te:
pass
def test_parse_validator_comparator(self):
""" Test parsing a comparator validator """
test_config = {
'name': 'Default',
'url': '/api',
'validators': [
{'comparator': {'jsonpath_mini': 'id',
'comparator': 'eq',
'expected': {'template': '$id'}}}
]
}
test = Test.parse_test('', test_config)
self.assertTrue(test.validators)
self.assertEqual(1, len(test.validators))
context = Context()
context.bind_variable('id', 3)
myjson = '{"id": "3"}'
failure = test.validators[0].validate(myjson, context=context)
self.assertTrue(test.validators[0].validate(myjson, context=context))
self.assertFalse(test.validators[0].validate(myjson))
def test_parse_validator_extract_test(self):
""" Tests parsing extract-test validator """
test_config = {
'name': 'Default',
'url': '/api',
'validators': [
{'extract_test': {'jsonpath_mini': 'login',
'test': 'exists'}}
]
}
test = Test.parse_test('', test_config)
self.assertTrue(test.validators)
self.assertEqual(1, len(test.validators))
myjson = '{"login": "testval"}'
self.assertTrue(test.validators[0].validate(myjson))
def test_variable_binding(self):
""" Test that tests successfully bind variables """
element = 3
input = [{"url": "/ping"}, {"name": "cheese"},
{"expected_status": ["200", 204, "202"]}]
input.append({"variable_binds": {'var': 'value'}})
test = Test.parse_test('', input)
binds = test.variable_binds
self.assertEqual(1, len(binds))
self.assertEqual('value', binds['var'])
# Test that updates context correctly
context = Context()
test.update_context_before(context)
self.assertEqual('value', context.get_value('var'))
self.assertTrue(test.is_context_modifier())
def test_test_url_templating(self):
test = Test()
test.set_url('$cheese', isTemplate=True)
self.assertTrue(test.is_dynamic())
self.assertEqual('$cheese', test.get_url())
self.assertTrue(test.templates['url'])
context = Context()
context.bind_variable('cheese', 'stilton')
self.assertEqual('stilton', test.get_url(context=context))
realized = test.realize(context)
self.assertEqual('stilton', realized.url)
def test_test_content_templating(self):
test = Test()
handler = ContentHandler()
handler.is_template_content = True
handler.content = '{"first_name": "Gaius","id": "$id","last_name": "Baltar","login": "$login"}'
context = Context()
context.bind_variables({'id': 9, 'login': 'kvothe'})
test.set_body(handler)
templated = test.realize(context=context)
self.assertEqual(string.Template(handler.content).safe_substitute(context.get_values()),
templated.body)
def test_header_templating(self):
test = Test()
head_templated = {'$key': "$val"}
context = Context()
context.bind_variables({'key': 'cheese', 'val': 'gouda'})
# No templating applied
test.headers = head_templated
head = test.get_headers()
self.assertEqual(1, len(head))
self.assertEqual('$val', head['$key'])
test.set_headers(head_templated, isTemplate=True)
self.assertTrue(test.templates)
self.assertTrue(test.NAME_HEADERS in test.templates)
# No context, no templating
head = test.headers
self.assertEqual(1, len(head))
self.assertEqual('$val', head['$key'])
# Templated with context
head = test.get_headers(context=context)
self.assertEqual(1, len(head))
self.assertEqual('gouda', head['cheese'])
def test_update_context_variables(self):
test = Test()
context = Context()
context.bind_variable('foo', 'broken')
test.variable_binds = {'foo': 'correct', 'test': 'value'}
test.update_context_before(context)
self.assertEqual('correct', context.get_value('foo'))
self.assertEqual('value', context.get_value('test'))
def test_update_context_generators(self):
""" Test updating context variables using generator """
test = Test()
context = Context()
context.bind_variable('foo', 'broken')
test.variable_binds = {'foo': 'initial_value'}
test.generator_binds = {'foo': 'gen'}
context.add_generator('gen', generators.generator_basic_ids())
test.update_context_before(context)
self.assertEqual(1, context.get_value('foo'))
test.update_context_before(context)
self.assertEqual(2, context.get_value('foo'))
if __name__ == '__main__':
unittest.main()
| netjunki/pyresttest | pyresttest/test_tests.py | Python | apache-2.0 | 18,914 |
package com.jboss.soap.service.acmedemo;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="out" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"out"
})
@XmlRootElement(name = "bookFlightsResponse")
public class BookFlightsResponse
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlElement(required = true)
protected String out;
/**
* Gets the value of the out property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOut() {
return out;
}
/**
* Sets the value of the out property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOut(String value) {
this.out = value;
}
}
| baldimir/droolsjbpm-integration | kie-server-parent/kie-server-tests/kie-server-integ-tests-jbpm/src/test/filtered-resources/kjars-sources/webservice-project/src/main/java/com/jboss/soap/service/acmedemo/BookFlightsResponse.java | Java | apache-2.0 | 1,584 |
// Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package fakes
import (
"context"
"sync"
"time"
"github.com/rancher/norman/controller"
"github.com/rancher/norman/objectclient"
v3 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
v31 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
var (
lockSettingListerMockGet sync.RWMutex
lockSettingListerMockList sync.RWMutex
)
// Ensure, that SettingListerMock does implement v31.SettingLister.
// If this is not the case, regenerate this file with moq.
var _ v31.SettingLister = &SettingListerMock{}
// SettingListerMock is a mock implementation of v31.SettingLister.
//
// func TestSomethingThatUsesSettingLister(t *testing.T) {
//
// // make and configure a mocked v31.SettingLister
// mockedSettingLister := &SettingListerMock{
// GetFunc: func(namespace string, name string) (*v3.Setting, error) {
// panic("mock out the Get method")
// },
// ListFunc: func(namespace string, selector labels.Selector) ([]*v3.Setting, error) {
// panic("mock out the List method")
// },
// }
//
// // use mockedSettingLister in code that requires v31.SettingLister
// // and then make assertions.
//
// }
type SettingListerMock struct {
// GetFunc mocks the Get method.
GetFunc func(namespace string, name string) (*v3.Setting, error)
// ListFunc mocks the List method.
ListFunc func(namespace string, selector labels.Selector) ([]*v3.Setting, error)
// calls tracks calls to the methods.
calls struct {
// Get holds details about calls to the Get method.
Get []struct {
// Namespace is the namespace argument value.
Namespace string
// Name is the name argument value.
Name string
}
// List holds details about calls to the List method.
List []struct {
// Namespace is the namespace argument value.
Namespace string
// Selector is the selector argument value.
Selector labels.Selector
}
}
}
// Get calls GetFunc.
func (mock *SettingListerMock) Get(namespace string, name string) (*v3.Setting, error) {
if mock.GetFunc == nil {
panic("SettingListerMock.GetFunc: method is nil but SettingLister.Get was just called")
}
callInfo := struct {
Namespace string
Name string
}{
Namespace: namespace,
Name: name,
}
lockSettingListerMockGet.Lock()
mock.calls.Get = append(mock.calls.Get, callInfo)
lockSettingListerMockGet.Unlock()
return mock.GetFunc(namespace, name)
}
// GetCalls gets all the calls that were made to Get.
// Check the length with:
// len(mockedSettingLister.GetCalls())
func (mock *SettingListerMock) GetCalls() []struct {
Namespace string
Name string
} {
var calls []struct {
Namespace string
Name string
}
lockSettingListerMockGet.RLock()
calls = mock.calls.Get
lockSettingListerMockGet.RUnlock()
return calls
}
// List calls ListFunc.
func (mock *SettingListerMock) List(namespace string, selector labels.Selector) ([]*v3.Setting, error) {
if mock.ListFunc == nil {
panic("SettingListerMock.ListFunc: method is nil but SettingLister.List was just called")
}
callInfo := struct {
Namespace string
Selector labels.Selector
}{
Namespace: namespace,
Selector: selector,
}
lockSettingListerMockList.Lock()
mock.calls.List = append(mock.calls.List, callInfo)
lockSettingListerMockList.Unlock()
return mock.ListFunc(namespace, selector)
}
// ListCalls gets all the calls that were made to List.
// Check the length with:
// len(mockedSettingLister.ListCalls())
func (mock *SettingListerMock) ListCalls() []struct {
Namespace string
Selector labels.Selector
} {
var calls []struct {
Namespace string
Selector labels.Selector
}
lockSettingListerMockList.RLock()
calls = mock.calls.List
lockSettingListerMockList.RUnlock()
return calls
}
var (
lockSettingControllerMockAddClusterScopedFeatureHandler sync.RWMutex
lockSettingControllerMockAddClusterScopedHandler sync.RWMutex
lockSettingControllerMockAddFeatureHandler sync.RWMutex
lockSettingControllerMockAddHandler sync.RWMutex
lockSettingControllerMockEnqueue sync.RWMutex
lockSettingControllerMockEnqueueAfter sync.RWMutex
lockSettingControllerMockGeneric sync.RWMutex
lockSettingControllerMockInformer sync.RWMutex
lockSettingControllerMockLister sync.RWMutex
)
// Ensure, that SettingControllerMock does implement v31.SettingController.
// If this is not the case, regenerate this file with moq.
var _ v31.SettingController = &SettingControllerMock{}
// SettingControllerMock is a mock implementation of v31.SettingController.
//
// func TestSomethingThatUsesSettingController(t *testing.T) {
//
// // make and configure a mocked v31.SettingController
// mockedSettingController := &SettingControllerMock{
// AddClusterScopedFeatureHandlerFunc: func(ctx context.Context, enabled func() bool, name string, clusterName string, handler v31.SettingHandlerFunc) {
// panic("mock out the AddClusterScopedFeatureHandler method")
// },
// AddClusterScopedHandlerFunc: func(ctx context.Context, name string, clusterName string, handler v31.SettingHandlerFunc) {
// panic("mock out the AddClusterScopedHandler method")
// },
// AddFeatureHandlerFunc: func(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc) {
// panic("mock out the AddFeatureHandler method")
// },
// AddHandlerFunc: func(ctx context.Context, name string, handler v31.SettingHandlerFunc) {
// panic("mock out the AddHandler method")
// },
// EnqueueFunc: func(namespace string, name string) {
// panic("mock out the Enqueue method")
// },
// EnqueueAfterFunc: func(namespace string, name string, after time.Duration) {
// panic("mock out the EnqueueAfter method")
// },
// GenericFunc: func() controller.GenericController {
// panic("mock out the Generic method")
// },
// InformerFunc: func() cache.SharedIndexInformer {
// panic("mock out the Informer method")
// },
// ListerFunc: func() v31.SettingLister {
// panic("mock out the Lister method")
// },
// }
//
// // use mockedSettingController in code that requires v31.SettingController
// // and then make assertions.
//
// }
type SettingControllerMock struct {
// AddClusterScopedFeatureHandlerFunc mocks the AddClusterScopedFeatureHandler method.
AddClusterScopedFeatureHandlerFunc func(ctx context.Context, enabled func() bool, name string, clusterName string, handler v31.SettingHandlerFunc)
// AddClusterScopedHandlerFunc mocks the AddClusterScopedHandler method.
AddClusterScopedHandlerFunc func(ctx context.Context, name string, clusterName string, handler v31.SettingHandlerFunc)
// AddFeatureHandlerFunc mocks the AddFeatureHandler method.
AddFeatureHandlerFunc func(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc)
// AddHandlerFunc mocks the AddHandler method.
AddHandlerFunc func(ctx context.Context, name string, handler v31.SettingHandlerFunc)
// EnqueueFunc mocks the Enqueue method.
EnqueueFunc func(namespace string, name string)
// EnqueueAfterFunc mocks the EnqueueAfter method.
EnqueueAfterFunc func(namespace string, name string, after time.Duration)
// GenericFunc mocks the Generic method.
GenericFunc func() controller.GenericController
// InformerFunc mocks the Informer method.
InformerFunc func() cache.SharedIndexInformer
// ListerFunc mocks the Lister method.
ListerFunc func() v31.SettingLister
// calls tracks calls to the methods.
calls struct {
// AddClusterScopedFeatureHandler holds details about calls to the AddClusterScopedFeatureHandler method.
AddClusterScopedFeatureHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Handler is the handler argument value.
Handler v31.SettingHandlerFunc
}
// AddClusterScopedHandler holds details about calls to the AddClusterScopedHandler method.
AddClusterScopedHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Handler is the handler argument value.
Handler v31.SettingHandlerFunc
}
// AddFeatureHandler holds details about calls to the AddFeatureHandler method.
AddFeatureHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// Sync is the sync argument value.
Sync v31.SettingHandlerFunc
}
// AddHandler holds details about calls to the AddHandler method.
AddHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// Handler is the handler argument value.
Handler v31.SettingHandlerFunc
}
// Enqueue holds details about calls to the Enqueue method.
Enqueue []struct {
// Namespace is the namespace argument value.
Namespace string
// Name is the name argument value.
Name string
}
// EnqueueAfter holds details about calls to the EnqueueAfter method.
EnqueueAfter []struct {
// Namespace is the namespace argument value.
Namespace string
// Name is the name argument value.
Name string
// After is the after argument value.
After time.Duration
}
// Generic holds details about calls to the Generic method.
Generic []struct {
}
// Informer holds details about calls to the Informer method.
Informer []struct {
}
// Lister holds details about calls to the Lister method.
Lister []struct {
}
}
}
// AddClusterScopedFeatureHandler calls AddClusterScopedFeatureHandlerFunc.
func (mock *SettingControllerMock) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name string, clusterName string, handler v31.SettingHandlerFunc) {
if mock.AddClusterScopedFeatureHandlerFunc == nil {
panic("SettingControllerMock.AddClusterScopedFeatureHandlerFunc: method is nil but SettingController.AddClusterScopedFeatureHandler was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Handler v31.SettingHandlerFunc
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
ClusterName: clusterName,
Handler: handler,
}
lockSettingControllerMockAddClusterScopedFeatureHandler.Lock()
mock.calls.AddClusterScopedFeatureHandler = append(mock.calls.AddClusterScopedFeatureHandler, callInfo)
lockSettingControllerMockAddClusterScopedFeatureHandler.Unlock()
mock.AddClusterScopedFeatureHandlerFunc(ctx, enabled, name, clusterName, handler)
}
// AddClusterScopedFeatureHandlerCalls gets all the calls that were made to AddClusterScopedFeatureHandler.
// Check the length with:
// len(mockedSettingController.AddClusterScopedFeatureHandlerCalls())
func (mock *SettingControllerMock) AddClusterScopedFeatureHandlerCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Handler v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Handler v31.SettingHandlerFunc
}
lockSettingControllerMockAddClusterScopedFeatureHandler.RLock()
calls = mock.calls.AddClusterScopedFeatureHandler
lockSettingControllerMockAddClusterScopedFeatureHandler.RUnlock()
return calls
}
// AddClusterScopedHandler calls AddClusterScopedHandlerFunc.
func (mock *SettingControllerMock) AddClusterScopedHandler(ctx context.Context, name string, clusterName string, handler v31.SettingHandlerFunc) {
if mock.AddClusterScopedHandlerFunc == nil {
panic("SettingControllerMock.AddClusterScopedHandlerFunc: method is nil but SettingController.AddClusterScopedHandler was just called")
}
callInfo := struct {
Ctx context.Context
Name string
ClusterName string
Handler v31.SettingHandlerFunc
}{
Ctx: ctx,
Name: name,
ClusterName: clusterName,
Handler: handler,
}
lockSettingControllerMockAddClusterScopedHandler.Lock()
mock.calls.AddClusterScopedHandler = append(mock.calls.AddClusterScopedHandler, callInfo)
lockSettingControllerMockAddClusterScopedHandler.Unlock()
mock.AddClusterScopedHandlerFunc(ctx, name, clusterName, handler)
}
// AddClusterScopedHandlerCalls gets all the calls that were made to AddClusterScopedHandler.
// Check the length with:
// len(mockedSettingController.AddClusterScopedHandlerCalls())
func (mock *SettingControllerMock) AddClusterScopedHandlerCalls() []struct {
Ctx context.Context
Name string
ClusterName string
Handler v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Name string
ClusterName string
Handler v31.SettingHandlerFunc
}
lockSettingControllerMockAddClusterScopedHandler.RLock()
calls = mock.calls.AddClusterScopedHandler
lockSettingControllerMockAddClusterScopedHandler.RUnlock()
return calls
}
// AddFeatureHandler calls AddFeatureHandlerFunc.
func (mock *SettingControllerMock) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc) {
if mock.AddFeatureHandlerFunc == nil {
panic("SettingControllerMock.AddFeatureHandlerFunc: method is nil but SettingController.AddFeatureHandler was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
Sync: syncMoqParam,
}
lockSettingControllerMockAddFeatureHandler.Lock()
mock.calls.AddFeatureHandler = append(mock.calls.AddFeatureHandler, callInfo)
lockSettingControllerMockAddFeatureHandler.Unlock()
mock.AddFeatureHandlerFunc(ctx, enabled, name, syncMoqParam)
}
// AddFeatureHandlerCalls gets all the calls that were made to AddFeatureHandler.
// Check the length with:
// len(mockedSettingController.AddFeatureHandlerCalls())
func (mock *SettingControllerMock) AddFeatureHandlerCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
}
lockSettingControllerMockAddFeatureHandler.RLock()
calls = mock.calls.AddFeatureHandler
lockSettingControllerMockAddFeatureHandler.RUnlock()
return calls
}
// AddHandler calls AddHandlerFunc.
func (mock *SettingControllerMock) AddHandler(ctx context.Context, name string, handler v31.SettingHandlerFunc) {
if mock.AddHandlerFunc == nil {
panic("SettingControllerMock.AddHandlerFunc: method is nil but SettingController.AddHandler was just called")
}
callInfo := struct {
Ctx context.Context
Name string
Handler v31.SettingHandlerFunc
}{
Ctx: ctx,
Name: name,
Handler: handler,
}
lockSettingControllerMockAddHandler.Lock()
mock.calls.AddHandler = append(mock.calls.AddHandler, callInfo)
lockSettingControllerMockAddHandler.Unlock()
mock.AddHandlerFunc(ctx, name, handler)
}
// AddHandlerCalls gets all the calls that were made to AddHandler.
// Check the length with:
// len(mockedSettingController.AddHandlerCalls())
func (mock *SettingControllerMock) AddHandlerCalls() []struct {
Ctx context.Context
Name string
Handler v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Name string
Handler v31.SettingHandlerFunc
}
lockSettingControllerMockAddHandler.RLock()
calls = mock.calls.AddHandler
lockSettingControllerMockAddHandler.RUnlock()
return calls
}
// Enqueue calls EnqueueFunc.
func (mock *SettingControllerMock) Enqueue(namespace string, name string) {
if mock.EnqueueFunc == nil {
panic("SettingControllerMock.EnqueueFunc: method is nil but SettingController.Enqueue was just called")
}
callInfo := struct {
Namespace string
Name string
}{
Namespace: namespace,
Name: name,
}
lockSettingControllerMockEnqueue.Lock()
mock.calls.Enqueue = append(mock.calls.Enqueue, callInfo)
lockSettingControllerMockEnqueue.Unlock()
mock.EnqueueFunc(namespace, name)
}
// EnqueueCalls gets all the calls that were made to Enqueue.
// Check the length with:
// len(mockedSettingController.EnqueueCalls())
func (mock *SettingControllerMock) EnqueueCalls() []struct {
Namespace string
Name string
} {
var calls []struct {
Namespace string
Name string
}
lockSettingControllerMockEnqueue.RLock()
calls = mock.calls.Enqueue
lockSettingControllerMockEnqueue.RUnlock()
return calls
}
// EnqueueAfter calls EnqueueAfterFunc.
func (mock *SettingControllerMock) EnqueueAfter(namespace string, name string, after time.Duration) {
if mock.EnqueueAfterFunc == nil {
panic("SettingControllerMock.EnqueueAfterFunc: method is nil but SettingController.EnqueueAfter was just called")
}
callInfo := struct {
Namespace string
Name string
After time.Duration
}{
Namespace: namespace,
Name: name,
After: after,
}
lockSettingControllerMockEnqueueAfter.Lock()
mock.calls.EnqueueAfter = append(mock.calls.EnqueueAfter, callInfo)
lockSettingControllerMockEnqueueAfter.Unlock()
mock.EnqueueAfterFunc(namespace, name, after)
}
// EnqueueAfterCalls gets all the calls that were made to EnqueueAfter.
// Check the length with:
// len(mockedSettingController.EnqueueAfterCalls())
func (mock *SettingControllerMock) EnqueueAfterCalls() []struct {
Namespace string
Name string
After time.Duration
} {
var calls []struct {
Namespace string
Name string
After time.Duration
}
lockSettingControllerMockEnqueueAfter.RLock()
calls = mock.calls.EnqueueAfter
lockSettingControllerMockEnqueueAfter.RUnlock()
return calls
}
// Generic calls GenericFunc.
func (mock *SettingControllerMock) Generic() controller.GenericController {
if mock.GenericFunc == nil {
panic("SettingControllerMock.GenericFunc: method is nil but SettingController.Generic was just called")
}
callInfo := struct {
}{}
lockSettingControllerMockGeneric.Lock()
mock.calls.Generic = append(mock.calls.Generic, callInfo)
lockSettingControllerMockGeneric.Unlock()
return mock.GenericFunc()
}
// GenericCalls gets all the calls that were made to Generic.
// Check the length with:
// len(mockedSettingController.GenericCalls())
func (mock *SettingControllerMock) GenericCalls() []struct {
} {
var calls []struct {
}
lockSettingControllerMockGeneric.RLock()
calls = mock.calls.Generic
lockSettingControllerMockGeneric.RUnlock()
return calls
}
// Informer calls InformerFunc.
func (mock *SettingControllerMock) Informer() cache.SharedIndexInformer {
if mock.InformerFunc == nil {
panic("SettingControllerMock.InformerFunc: method is nil but SettingController.Informer was just called")
}
callInfo := struct {
}{}
lockSettingControllerMockInformer.Lock()
mock.calls.Informer = append(mock.calls.Informer, callInfo)
lockSettingControllerMockInformer.Unlock()
return mock.InformerFunc()
}
// InformerCalls gets all the calls that were made to Informer.
// Check the length with:
// len(mockedSettingController.InformerCalls())
func (mock *SettingControllerMock) InformerCalls() []struct {
} {
var calls []struct {
}
lockSettingControllerMockInformer.RLock()
calls = mock.calls.Informer
lockSettingControllerMockInformer.RUnlock()
return calls
}
// Lister calls ListerFunc.
func (mock *SettingControllerMock) Lister() v31.SettingLister {
if mock.ListerFunc == nil {
panic("SettingControllerMock.ListerFunc: method is nil but SettingController.Lister was just called")
}
callInfo := struct {
}{}
lockSettingControllerMockLister.Lock()
mock.calls.Lister = append(mock.calls.Lister, callInfo)
lockSettingControllerMockLister.Unlock()
return mock.ListerFunc()
}
// ListerCalls gets all the calls that were made to Lister.
// Check the length with:
// len(mockedSettingController.ListerCalls())
func (mock *SettingControllerMock) ListerCalls() []struct {
} {
var calls []struct {
}
lockSettingControllerMockLister.RLock()
calls = mock.calls.Lister
lockSettingControllerMockLister.RUnlock()
return calls
}
var (
lockSettingInterfaceMockAddClusterScopedFeatureHandler sync.RWMutex
lockSettingInterfaceMockAddClusterScopedFeatureLifecycle sync.RWMutex
lockSettingInterfaceMockAddClusterScopedHandler sync.RWMutex
lockSettingInterfaceMockAddClusterScopedLifecycle sync.RWMutex
lockSettingInterfaceMockAddFeatureHandler sync.RWMutex
lockSettingInterfaceMockAddFeatureLifecycle sync.RWMutex
lockSettingInterfaceMockAddHandler sync.RWMutex
lockSettingInterfaceMockAddLifecycle sync.RWMutex
lockSettingInterfaceMockController sync.RWMutex
lockSettingInterfaceMockCreate sync.RWMutex
lockSettingInterfaceMockDelete sync.RWMutex
lockSettingInterfaceMockDeleteCollection sync.RWMutex
lockSettingInterfaceMockDeleteNamespaced sync.RWMutex
lockSettingInterfaceMockGet sync.RWMutex
lockSettingInterfaceMockGetNamespaced sync.RWMutex
lockSettingInterfaceMockList sync.RWMutex
lockSettingInterfaceMockListNamespaced sync.RWMutex
lockSettingInterfaceMockObjectClient sync.RWMutex
lockSettingInterfaceMockUpdate sync.RWMutex
lockSettingInterfaceMockWatch sync.RWMutex
)
// Ensure, that SettingInterfaceMock does implement v31.SettingInterface.
// If this is not the case, regenerate this file with moq.
var _ v31.SettingInterface = &SettingInterfaceMock{}
// SettingInterfaceMock is a mock implementation of v31.SettingInterface.
//
// func TestSomethingThatUsesSettingInterface(t *testing.T) {
//
// // make and configure a mocked v31.SettingInterface
// mockedSettingInterface := &SettingInterfaceMock{
// AddClusterScopedFeatureHandlerFunc: func(ctx context.Context, enabled func() bool, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc) {
// panic("mock out the AddClusterScopedFeatureHandler method")
// },
// AddClusterScopedFeatureLifecycleFunc: func(ctx context.Context, enabled func() bool, name string, clusterName string, lifecycle v31.SettingLifecycle) {
// panic("mock out the AddClusterScopedFeatureLifecycle method")
// },
// AddClusterScopedHandlerFunc: func(ctx context.Context, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc) {
// panic("mock out the AddClusterScopedHandler method")
// },
// AddClusterScopedLifecycleFunc: func(ctx context.Context, name string, clusterName string, lifecycle v31.SettingLifecycle) {
// panic("mock out the AddClusterScopedLifecycle method")
// },
// AddFeatureHandlerFunc: func(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc) {
// panic("mock out the AddFeatureHandler method")
// },
// AddFeatureLifecycleFunc: func(ctx context.Context, enabled func() bool, name string, lifecycle v31.SettingLifecycle) {
// panic("mock out the AddFeatureLifecycle method")
// },
// AddHandlerFunc: func(ctx context.Context, name string, syncMoqParam v31.SettingHandlerFunc) {
// panic("mock out the AddHandler method")
// },
// AddLifecycleFunc: func(ctx context.Context, name string, lifecycle v31.SettingLifecycle) {
// panic("mock out the AddLifecycle method")
// },
// ControllerFunc: func() v31.SettingController {
// panic("mock out the Controller method")
// },
// CreateFunc: func(in1 *v3.Setting) (*v3.Setting, error) {
// panic("mock out the Create method")
// },
// DeleteFunc: func(name string, options *metav1.DeleteOptions) error {
// panic("mock out the Delete method")
// },
// DeleteCollectionFunc: func(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error {
// panic("mock out the DeleteCollection method")
// },
// DeleteNamespacedFunc: func(namespace string, name string, options *metav1.DeleteOptions) error {
// panic("mock out the DeleteNamespaced method")
// },
// GetFunc: func(name string, opts metav1.GetOptions) (*v3.Setting, error) {
// panic("mock out the Get method")
// },
// GetNamespacedFunc: func(namespace string, name string, opts metav1.GetOptions) (*v3.Setting, error) {
// panic("mock out the GetNamespaced method")
// },
// ListFunc: func(opts metav1.ListOptions) (*v3.SettingList, error) {
// panic("mock out the List method")
// },
// ListNamespacedFunc: func(namespace string, opts metav1.ListOptions) (*v3.SettingList, error) {
// panic("mock out the ListNamespaced method")
// },
// ObjectClientFunc: func() *objectclient.ObjectClient {
// panic("mock out the ObjectClient method")
// },
// UpdateFunc: func(in1 *v3.Setting) (*v3.Setting, error) {
// panic("mock out the Update method")
// },
// WatchFunc: func(opts metav1.ListOptions) (watch.Interface, error) {
// panic("mock out the Watch method")
// },
// }
//
// // use mockedSettingInterface in code that requires v31.SettingInterface
// // and then make assertions.
//
// }
type SettingInterfaceMock struct {
// AddClusterScopedFeatureHandlerFunc mocks the AddClusterScopedFeatureHandler method.
AddClusterScopedFeatureHandlerFunc func(ctx context.Context, enabled func() bool, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc)
// AddClusterScopedFeatureLifecycleFunc mocks the AddClusterScopedFeatureLifecycle method.
AddClusterScopedFeatureLifecycleFunc func(ctx context.Context, enabled func() bool, name string, clusterName string, lifecycle v31.SettingLifecycle)
// AddClusterScopedHandlerFunc mocks the AddClusterScopedHandler method.
AddClusterScopedHandlerFunc func(ctx context.Context, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc)
// AddClusterScopedLifecycleFunc mocks the AddClusterScopedLifecycle method.
AddClusterScopedLifecycleFunc func(ctx context.Context, name string, clusterName string, lifecycle v31.SettingLifecycle)
// AddFeatureHandlerFunc mocks the AddFeatureHandler method.
AddFeatureHandlerFunc func(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc)
// AddFeatureLifecycleFunc mocks the AddFeatureLifecycle method.
AddFeatureLifecycleFunc func(ctx context.Context, enabled func() bool, name string, lifecycle v31.SettingLifecycle)
// AddHandlerFunc mocks the AddHandler method.
AddHandlerFunc func(ctx context.Context, name string, syncMoqParam v31.SettingHandlerFunc)
// AddLifecycleFunc mocks the AddLifecycle method.
AddLifecycleFunc func(ctx context.Context, name string, lifecycle v31.SettingLifecycle)
// ControllerFunc mocks the Controller method.
ControllerFunc func() v31.SettingController
// CreateFunc mocks the Create method.
CreateFunc func(in1 *v3.Setting) (*v3.Setting, error)
// DeleteFunc mocks the Delete method.
DeleteFunc func(name string, options *metav1.DeleteOptions) error
// DeleteCollectionFunc mocks the DeleteCollection method.
DeleteCollectionFunc func(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error
// DeleteNamespacedFunc mocks the DeleteNamespaced method.
DeleteNamespacedFunc func(namespace string, name string, options *metav1.DeleteOptions) error
// GetFunc mocks the Get method.
GetFunc func(name string, opts metav1.GetOptions) (*v3.Setting, error)
// GetNamespacedFunc mocks the GetNamespaced method.
GetNamespacedFunc func(namespace string, name string, opts metav1.GetOptions) (*v3.Setting, error)
// ListFunc mocks the List method.
ListFunc func(opts metav1.ListOptions) (*v3.SettingList, error)
// ListNamespacedFunc mocks the ListNamespaced method.
ListNamespacedFunc func(namespace string, opts metav1.ListOptions) (*v3.SettingList, error)
// ObjectClientFunc mocks the ObjectClient method.
ObjectClientFunc func() *objectclient.ObjectClient
// UpdateFunc mocks the Update method.
UpdateFunc func(in1 *v3.Setting) (*v3.Setting, error)
// WatchFunc mocks the Watch method.
WatchFunc func(opts metav1.ListOptions) (watch.Interface, error)
// calls tracks calls to the methods.
calls struct {
// AddClusterScopedFeatureHandler holds details about calls to the AddClusterScopedFeatureHandler method.
AddClusterScopedFeatureHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Sync is the sync argument value.
Sync v31.SettingHandlerFunc
}
// AddClusterScopedFeatureLifecycle holds details about calls to the AddClusterScopedFeatureLifecycle method.
AddClusterScopedFeatureLifecycle []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Lifecycle is the lifecycle argument value.
Lifecycle v31.SettingLifecycle
}
// AddClusterScopedHandler holds details about calls to the AddClusterScopedHandler method.
AddClusterScopedHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Sync is the sync argument value.
Sync v31.SettingHandlerFunc
}
// AddClusterScopedLifecycle holds details about calls to the AddClusterScopedLifecycle method.
AddClusterScopedLifecycle []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// ClusterName is the clusterName argument value.
ClusterName string
// Lifecycle is the lifecycle argument value.
Lifecycle v31.SettingLifecycle
}
// AddFeatureHandler holds details about calls to the AddFeatureHandler method.
AddFeatureHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// Sync is the sync argument value.
Sync v31.SettingHandlerFunc
}
// AddFeatureLifecycle holds details about calls to the AddFeatureLifecycle method.
AddFeatureLifecycle []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Enabled is the enabled argument value.
Enabled func() bool
// Name is the name argument value.
Name string
// Lifecycle is the lifecycle argument value.
Lifecycle v31.SettingLifecycle
}
// AddHandler holds details about calls to the AddHandler method.
AddHandler []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// Sync is the sync argument value.
Sync v31.SettingHandlerFunc
}
// AddLifecycle holds details about calls to the AddLifecycle method.
AddLifecycle []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// Lifecycle is the lifecycle argument value.
Lifecycle v31.SettingLifecycle
}
// Controller holds details about calls to the Controller method.
Controller []struct {
}
// Create holds details about calls to the Create method.
Create []struct {
// In1 is the in1 argument value.
In1 *v3.Setting
}
// Delete holds details about calls to the Delete method.
Delete []struct {
// Name is the name argument value.
Name string
// Options is the options argument value.
Options *metav1.DeleteOptions
}
// DeleteCollection holds details about calls to the DeleteCollection method.
DeleteCollection []struct {
// DeleteOpts is the deleteOpts argument value.
DeleteOpts *metav1.DeleteOptions
// ListOpts is the listOpts argument value.
ListOpts metav1.ListOptions
}
// DeleteNamespaced holds details about calls to the DeleteNamespaced method.
DeleteNamespaced []struct {
// Namespace is the namespace argument value.
Namespace string
// Name is the name argument value.
Name string
// Options is the options argument value.
Options *metav1.DeleteOptions
}
// Get holds details about calls to the Get method.
Get []struct {
// Name is the name argument value.
Name string
// Opts is the opts argument value.
Opts metav1.GetOptions
}
// GetNamespaced holds details about calls to the GetNamespaced method.
GetNamespaced []struct {
// Namespace is the namespace argument value.
Namespace string
// Name is the name argument value.
Name string
// Opts is the opts argument value.
Opts metav1.GetOptions
}
// List holds details about calls to the List method.
List []struct {
// Opts is the opts argument value.
Opts metav1.ListOptions
}
// ListNamespaced holds details about calls to the ListNamespaced method.
ListNamespaced []struct {
// Namespace is the namespace argument value.
Namespace string
// Opts is the opts argument value.
Opts metav1.ListOptions
}
// ObjectClient holds details about calls to the ObjectClient method.
ObjectClient []struct {
}
// Update holds details about calls to the Update method.
Update []struct {
// In1 is the in1 argument value.
In1 *v3.Setting
}
// Watch holds details about calls to the Watch method.
Watch []struct {
// Opts is the opts argument value.
Opts metav1.ListOptions
}
}
}
// AddClusterScopedFeatureHandler calls AddClusterScopedFeatureHandlerFunc.
func (mock *SettingInterfaceMock) AddClusterScopedFeatureHandler(ctx context.Context, enabled func() bool, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc) {
if mock.AddClusterScopedFeatureHandlerFunc == nil {
panic("SettingInterfaceMock.AddClusterScopedFeatureHandlerFunc: method is nil but SettingInterface.AddClusterScopedFeatureHandler was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Sync v31.SettingHandlerFunc
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
ClusterName: clusterName,
Sync: syncMoqParam,
}
lockSettingInterfaceMockAddClusterScopedFeatureHandler.Lock()
mock.calls.AddClusterScopedFeatureHandler = append(mock.calls.AddClusterScopedFeatureHandler, callInfo)
lockSettingInterfaceMockAddClusterScopedFeatureHandler.Unlock()
mock.AddClusterScopedFeatureHandlerFunc(ctx, enabled, name, clusterName, syncMoqParam)
}
// AddClusterScopedFeatureHandlerCalls gets all the calls that were made to AddClusterScopedFeatureHandler.
// Check the length with:
// len(mockedSettingInterface.AddClusterScopedFeatureHandlerCalls())
func (mock *SettingInterfaceMock) AddClusterScopedFeatureHandlerCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Sync v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Sync v31.SettingHandlerFunc
}
lockSettingInterfaceMockAddClusterScopedFeatureHandler.RLock()
calls = mock.calls.AddClusterScopedFeatureHandler
lockSettingInterfaceMockAddClusterScopedFeatureHandler.RUnlock()
return calls
}
// AddClusterScopedFeatureLifecycle calls AddClusterScopedFeatureLifecycleFunc.
func (mock *SettingInterfaceMock) AddClusterScopedFeatureLifecycle(ctx context.Context, enabled func() bool, name string, clusterName string, lifecycle v31.SettingLifecycle) {
if mock.AddClusterScopedFeatureLifecycleFunc == nil {
panic("SettingInterfaceMock.AddClusterScopedFeatureLifecycleFunc: method is nil but SettingInterface.AddClusterScopedFeatureLifecycle was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
ClusterName: clusterName,
Lifecycle: lifecycle,
}
lockSettingInterfaceMockAddClusterScopedFeatureLifecycle.Lock()
mock.calls.AddClusterScopedFeatureLifecycle = append(mock.calls.AddClusterScopedFeatureLifecycle, callInfo)
lockSettingInterfaceMockAddClusterScopedFeatureLifecycle.Unlock()
mock.AddClusterScopedFeatureLifecycleFunc(ctx, enabled, name, clusterName, lifecycle)
}
// AddClusterScopedFeatureLifecycleCalls gets all the calls that were made to AddClusterScopedFeatureLifecycle.
// Check the length with:
// len(mockedSettingInterface.AddClusterScopedFeatureLifecycleCalls())
func (mock *SettingInterfaceMock) AddClusterScopedFeatureLifecycleCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
}
lockSettingInterfaceMockAddClusterScopedFeatureLifecycle.RLock()
calls = mock.calls.AddClusterScopedFeatureLifecycle
lockSettingInterfaceMockAddClusterScopedFeatureLifecycle.RUnlock()
return calls
}
// AddClusterScopedHandler calls AddClusterScopedHandlerFunc.
func (mock *SettingInterfaceMock) AddClusterScopedHandler(ctx context.Context, name string, clusterName string, syncMoqParam v31.SettingHandlerFunc) {
if mock.AddClusterScopedHandlerFunc == nil {
panic("SettingInterfaceMock.AddClusterScopedHandlerFunc: method is nil but SettingInterface.AddClusterScopedHandler was just called")
}
callInfo := struct {
Ctx context.Context
Name string
ClusterName string
Sync v31.SettingHandlerFunc
}{
Ctx: ctx,
Name: name,
ClusterName: clusterName,
Sync: syncMoqParam,
}
lockSettingInterfaceMockAddClusterScopedHandler.Lock()
mock.calls.AddClusterScopedHandler = append(mock.calls.AddClusterScopedHandler, callInfo)
lockSettingInterfaceMockAddClusterScopedHandler.Unlock()
mock.AddClusterScopedHandlerFunc(ctx, name, clusterName, syncMoqParam)
}
// AddClusterScopedHandlerCalls gets all the calls that were made to AddClusterScopedHandler.
// Check the length with:
// len(mockedSettingInterface.AddClusterScopedHandlerCalls())
func (mock *SettingInterfaceMock) AddClusterScopedHandlerCalls() []struct {
Ctx context.Context
Name string
ClusterName string
Sync v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Name string
ClusterName string
Sync v31.SettingHandlerFunc
}
lockSettingInterfaceMockAddClusterScopedHandler.RLock()
calls = mock.calls.AddClusterScopedHandler
lockSettingInterfaceMockAddClusterScopedHandler.RUnlock()
return calls
}
// AddClusterScopedLifecycle calls AddClusterScopedLifecycleFunc.
func (mock *SettingInterfaceMock) AddClusterScopedLifecycle(ctx context.Context, name string, clusterName string, lifecycle v31.SettingLifecycle) {
if mock.AddClusterScopedLifecycleFunc == nil {
panic("SettingInterfaceMock.AddClusterScopedLifecycleFunc: method is nil but SettingInterface.AddClusterScopedLifecycle was just called")
}
callInfo := struct {
Ctx context.Context
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
}{
Ctx: ctx,
Name: name,
ClusterName: clusterName,
Lifecycle: lifecycle,
}
lockSettingInterfaceMockAddClusterScopedLifecycle.Lock()
mock.calls.AddClusterScopedLifecycle = append(mock.calls.AddClusterScopedLifecycle, callInfo)
lockSettingInterfaceMockAddClusterScopedLifecycle.Unlock()
mock.AddClusterScopedLifecycleFunc(ctx, name, clusterName, lifecycle)
}
// AddClusterScopedLifecycleCalls gets all the calls that were made to AddClusterScopedLifecycle.
// Check the length with:
// len(mockedSettingInterface.AddClusterScopedLifecycleCalls())
func (mock *SettingInterfaceMock) AddClusterScopedLifecycleCalls() []struct {
Ctx context.Context
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
} {
var calls []struct {
Ctx context.Context
Name string
ClusterName string
Lifecycle v31.SettingLifecycle
}
lockSettingInterfaceMockAddClusterScopedLifecycle.RLock()
calls = mock.calls.AddClusterScopedLifecycle
lockSettingInterfaceMockAddClusterScopedLifecycle.RUnlock()
return calls
}
// AddFeatureHandler calls AddFeatureHandlerFunc.
func (mock *SettingInterfaceMock) AddFeatureHandler(ctx context.Context, enabled func() bool, name string, syncMoqParam v31.SettingHandlerFunc) {
if mock.AddFeatureHandlerFunc == nil {
panic("SettingInterfaceMock.AddFeatureHandlerFunc: method is nil but SettingInterface.AddFeatureHandler was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
Sync: syncMoqParam,
}
lockSettingInterfaceMockAddFeatureHandler.Lock()
mock.calls.AddFeatureHandler = append(mock.calls.AddFeatureHandler, callInfo)
lockSettingInterfaceMockAddFeatureHandler.Unlock()
mock.AddFeatureHandlerFunc(ctx, enabled, name, syncMoqParam)
}
// AddFeatureHandlerCalls gets all the calls that were made to AddFeatureHandler.
// Check the length with:
// len(mockedSettingInterface.AddFeatureHandlerCalls())
func (mock *SettingInterfaceMock) AddFeatureHandlerCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
Sync v31.SettingHandlerFunc
}
lockSettingInterfaceMockAddFeatureHandler.RLock()
calls = mock.calls.AddFeatureHandler
lockSettingInterfaceMockAddFeatureHandler.RUnlock()
return calls
}
// AddFeatureLifecycle calls AddFeatureLifecycleFunc.
func (mock *SettingInterfaceMock) AddFeatureLifecycle(ctx context.Context, enabled func() bool, name string, lifecycle v31.SettingLifecycle) {
if mock.AddFeatureLifecycleFunc == nil {
panic("SettingInterfaceMock.AddFeatureLifecycleFunc: method is nil but SettingInterface.AddFeatureLifecycle was just called")
}
callInfo := struct {
Ctx context.Context
Enabled func() bool
Name string
Lifecycle v31.SettingLifecycle
}{
Ctx: ctx,
Enabled: enabled,
Name: name,
Lifecycle: lifecycle,
}
lockSettingInterfaceMockAddFeatureLifecycle.Lock()
mock.calls.AddFeatureLifecycle = append(mock.calls.AddFeatureLifecycle, callInfo)
lockSettingInterfaceMockAddFeatureLifecycle.Unlock()
mock.AddFeatureLifecycleFunc(ctx, enabled, name, lifecycle)
}
// AddFeatureLifecycleCalls gets all the calls that were made to AddFeatureLifecycle.
// Check the length with:
// len(mockedSettingInterface.AddFeatureLifecycleCalls())
func (mock *SettingInterfaceMock) AddFeatureLifecycleCalls() []struct {
Ctx context.Context
Enabled func() bool
Name string
Lifecycle v31.SettingLifecycle
} {
var calls []struct {
Ctx context.Context
Enabled func() bool
Name string
Lifecycle v31.SettingLifecycle
}
lockSettingInterfaceMockAddFeatureLifecycle.RLock()
calls = mock.calls.AddFeatureLifecycle
lockSettingInterfaceMockAddFeatureLifecycle.RUnlock()
return calls
}
// AddHandler calls AddHandlerFunc.
func (mock *SettingInterfaceMock) AddHandler(ctx context.Context, name string, syncMoqParam v31.SettingHandlerFunc) {
if mock.AddHandlerFunc == nil {
panic("SettingInterfaceMock.AddHandlerFunc: method is nil but SettingInterface.AddHandler was just called")
}
callInfo := struct {
Ctx context.Context
Name string
Sync v31.SettingHandlerFunc
}{
Ctx: ctx,
Name: name,
Sync: syncMoqParam,
}
lockSettingInterfaceMockAddHandler.Lock()
mock.calls.AddHandler = append(mock.calls.AddHandler, callInfo)
lockSettingInterfaceMockAddHandler.Unlock()
mock.AddHandlerFunc(ctx, name, syncMoqParam)
}
// AddHandlerCalls gets all the calls that were made to AddHandler.
// Check the length with:
// len(mockedSettingInterface.AddHandlerCalls())
func (mock *SettingInterfaceMock) AddHandlerCalls() []struct {
Ctx context.Context
Name string
Sync v31.SettingHandlerFunc
} {
var calls []struct {
Ctx context.Context
Name string
Sync v31.SettingHandlerFunc
}
lockSettingInterfaceMockAddHandler.RLock()
calls = mock.calls.AddHandler
lockSettingInterfaceMockAddHandler.RUnlock()
return calls
}
// AddLifecycle calls AddLifecycleFunc.
func (mock *SettingInterfaceMock) AddLifecycle(ctx context.Context, name string, lifecycle v31.SettingLifecycle) {
if mock.AddLifecycleFunc == nil {
panic("SettingInterfaceMock.AddLifecycleFunc: method is nil but SettingInterface.AddLifecycle was just called")
}
callInfo := struct {
Ctx context.Context
Name string
Lifecycle v31.SettingLifecycle
}{
Ctx: ctx,
Name: name,
Lifecycle: lifecycle,
}
lockSettingInterfaceMockAddLifecycle.Lock()
mock.calls.AddLifecycle = append(mock.calls.AddLifecycle, callInfo)
lockSettingInterfaceMockAddLifecycle.Unlock()
mock.AddLifecycleFunc(ctx, name, lifecycle)
}
// AddLifecycleCalls gets all the calls that were made to AddLifecycle.
// Check the length with:
// len(mockedSettingInterface.AddLifecycleCalls())
func (mock *SettingInterfaceMock) AddLifecycleCalls() []struct {
Ctx context.Context
Name string
Lifecycle v31.SettingLifecycle
} {
var calls []struct {
Ctx context.Context
Name string
Lifecycle v31.SettingLifecycle
}
lockSettingInterfaceMockAddLifecycle.RLock()
calls = mock.calls.AddLifecycle
lockSettingInterfaceMockAddLifecycle.RUnlock()
return calls
}
// Controller calls ControllerFunc.
func (mock *SettingInterfaceMock) Controller() v31.SettingController {
if mock.ControllerFunc == nil {
panic("SettingInterfaceMock.ControllerFunc: method is nil but SettingInterface.Controller was just called")
}
callInfo := struct {
}{}
lockSettingInterfaceMockController.Lock()
mock.calls.Controller = append(mock.calls.Controller, callInfo)
lockSettingInterfaceMockController.Unlock()
return mock.ControllerFunc()
}
// ControllerCalls gets all the calls that were made to Controller.
// Check the length with:
// len(mockedSettingInterface.ControllerCalls())
func (mock *SettingInterfaceMock) ControllerCalls() []struct {
} {
var calls []struct {
}
lockSettingInterfaceMockController.RLock()
calls = mock.calls.Controller
lockSettingInterfaceMockController.RUnlock()
return calls
}
// Create calls CreateFunc.
func (mock *SettingInterfaceMock) Create(in1 *v3.Setting) (*v3.Setting, error) {
if mock.CreateFunc == nil {
panic("SettingInterfaceMock.CreateFunc: method is nil but SettingInterface.Create was just called")
}
callInfo := struct {
In1 *v3.Setting
}{
In1: in1,
}
lockSettingInterfaceMockCreate.Lock()
mock.calls.Create = append(mock.calls.Create, callInfo)
lockSettingInterfaceMockCreate.Unlock()
return mock.CreateFunc(in1)
}
// CreateCalls gets all the calls that were made to Create.
// Check the length with:
// len(mockedSettingInterface.CreateCalls())
func (mock *SettingInterfaceMock) CreateCalls() []struct {
In1 *v3.Setting
} {
var calls []struct {
In1 *v3.Setting
}
lockSettingInterfaceMockCreate.RLock()
calls = mock.calls.Create
lockSettingInterfaceMockCreate.RUnlock()
return calls
}
// Delete calls DeleteFunc.
func (mock *SettingInterfaceMock) Delete(name string, options *metav1.DeleteOptions) error {
if mock.DeleteFunc == nil {
panic("SettingInterfaceMock.DeleteFunc: method is nil but SettingInterface.Delete was just called")
}
callInfo := struct {
Name string
Options *metav1.DeleteOptions
}{
Name: name,
Options: options,
}
lockSettingInterfaceMockDelete.Lock()
mock.calls.Delete = append(mock.calls.Delete, callInfo)
lockSettingInterfaceMockDelete.Unlock()
return mock.DeleteFunc(name, options)
}
// DeleteCalls gets all the calls that were made to Delete.
// Check the length with:
// len(mockedSettingInterface.DeleteCalls())
func (mock *SettingInterfaceMock) DeleteCalls() []struct {
Name string
Options *metav1.DeleteOptions
} {
var calls []struct {
Name string
Options *metav1.DeleteOptions
}
lockSettingInterfaceMockDelete.RLock()
calls = mock.calls.Delete
lockSettingInterfaceMockDelete.RUnlock()
return calls
}
// DeleteCollection calls DeleteCollectionFunc.
func (mock *SettingInterfaceMock) DeleteCollection(deleteOpts *metav1.DeleteOptions, listOpts metav1.ListOptions) error {
if mock.DeleteCollectionFunc == nil {
panic("SettingInterfaceMock.DeleteCollectionFunc: method is nil but SettingInterface.DeleteCollection was just called")
}
callInfo := struct {
DeleteOpts *metav1.DeleteOptions
ListOpts metav1.ListOptions
}{
DeleteOpts: deleteOpts,
ListOpts: listOpts,
}
lockSettingInterfaceMockDeleteCollection.Lock()
mock.calls.DeleteCollection = append(mock.calls.DeleteCollection, callInfo)
lockSettingInterfaceMockDeleteCollection.Unlock()
return mock.DeleteCollectionFunc(deleteOpts, listOpts)
}
// DeleteCollectionCalls gets all the calls that were made to DeleteCollection.
// Check the length with:
// len(mockedSettingInterface.DeleteCollectionCalls())
func (mock *SettingInterfaceMock) DeleteCollectionCalls() []struct {
DeleteOpts *metav1.DeleteOptions
ListOpts metav1.ListOptions
} {
var calls []struct {
DeleteOpts *metav1.DeleteOptions
ListOpts metav1.ListOptions
}
lockSettingInterfaceMockDeleteCollection.RLock()
calls = mock.calls.DeleteCollection
lockSettingInterfaceMockDeleteCollection.RUnlock()
return calls
}
// DeleteNamespaced calls DeleteNamespacedFunc.
func (mock *SettingInterfaceMock) DeleteNamespaced(namespace string, name string, options *metav1.DeleteOptions) error {
if mock.DeleteNamespacedFunc == nil {
panic("SettingInterfaceMock.DeleteNamespacedFunc: method is nil but SettingInterface.DeleteNamespaced was just called")
}
callInfo := struct {
Namespace string
Name string
Options *metav1.DeleteOptions
}{
Namespace: namespace,
Name: name,
Options: options,
}
lockSettingInterfaceMockDeleteNamespaced.Lock()
mock.calls.DeleteNamespaced = append(mock.calls.DeleteNamespaced, callInfo)
lockSettingInterfaceMockDeleteNamespaced.Unlock()
return mock.DeleteNamespacedFunc(namespace, name, options)
}
// DeleteNamespacedCalls gets all the calls that were made to DeleteNamespaced.
// Check the length with:
// len(mockedSettingInterface.DeleteNamespacedCalls())
func (mock *SettingInterfaceMock) DeleteNamespacedCalls() []struct {
Namespace string
Name string
Options *metav1.DeleteOptions
} {
var calls []struct {
Namespace string
Name string
Options *metav1.DeleteOptions
}
lockSettingInterfaceMockDeleteNamespaced.RLock()
calls = mock.calls.DeleteNamespaced
lockSettingInterfaceMockDeleteNamespaced.RUnlock()
return calls
}
// Get calls GetFunc.
func (mock *SettingInterfaceMock) Get(name string, opts metav1.GetOptions) (*v3.Setting, error) {
if mock.GetFunc == nil {
panic("SettingInterfaceMock.GetFunc: method is nil but SettingInterface.Get was just called")
}
callInfo := struct {
Name string
Opts metav1.GetOptions
}{
Name: name,
Opts: opts,
}
lockSettingInterfaceMockGet.Lock()
mock.calls.Get = append(mock.calls.Get, callInfo)
lockSettingInterfaceMockGet.Unlock()
return mock.GetFunc(name, opts)
}
// GetCalls gets all the calls that were made to Get.
// Check the length with:
// len(mockedSettingInterface.GetCalls())
func (mock *SettingInterfaceMock) GetCalls() []struct {
Name string
Opts metav1.GetOptions
} {
var calls []struct {
Name string
Opts metav1.GetOptions
}
lockSettingInterfaceMockGet.RLock()
calls = mock.calls.Get
lockSettingInterfaceMockGet.RUnlock()
return calls
}
// GetNamespaced calls GetNamespacedFunc.
func (mock *SettingInterfaceMock) GetNamespaced(namespace string, name string, opts metav1.GetOptions) (*v3.Setting, error) {
if mock.GetNamespacedFunc == nil {
panic("SettingInterfaceMock.GetNamespacedFunc: method is nil but SettingInterface.GetNamespaced was just called")
}
callInfo := struct {
Namespace string
Name string
Opts metav1.GetOptions
}{
Namespace: namespace,
Name: name,
Opts: opts,
}
lockSettingInterfaceMockGetNamespaced.Lock()
mock.calls.GetNamespaced = append(mock.calls.GetNamespaced, callInfo)
lockSettingInterfaceMockGetNamespaced.Unlock()
return mock.GetNamespacedFunc(namespace, name, opts)
}
// GetNamespacedCalls gets all the calls that were made to GetNamespaced.
// Check the length with:
// len(mockedSettingInterface.GetNamespacedCalls())
func (mock *SettingInterfaceMock) GetNamespacedCalls() []struct {
Namespace string
Name string
Opts metav1.GetOptions
} {
var calls []struct {
Namespace string
Name string
Opts metav1.GetOptions
}
lockSettingInterfaceMockGetNamespaced.RLock()
calls = mock.calls.GetNamespaced
lockSettingInterfaceMockGetNamespaced.RUnlock()
return calls
}
// List calls ListFunc.
func (mock *SettingInterfaceMock) List(opts metav1.ListOptions) (*v3.SettingList, error) {
if mock.ListFunc == nil {
panic("SettingInterfaceMock.ListFunc: method is nil but SettingInterface.List was just called")
}
callInfo := struct {
Opts metav1.ListOptions
}{
Opts: opts,
}
lockSettingInterfaceMockList.Lock()
mock.calls.List = append(mock.calls.List, callInfo)
lockSettingInterfaceMockList.Unlock()
return mock.ListFunc(opts)
}
// ListCalls gets all the calls that were made to List.
// Check the length with:
// len(mockedSettingInterface.ListCalls())
func (mock *SettingInterfaceMock) ListCalls() []struct {
Opts metav1.ListOptions
} {
var calls []struct {
Opts metav1.ListOptions
}
lockSettingInterfaceMockList.RLock()
calls = mock.calls.List
lockSettingInterfaceMockList.RUnlock()
return calls
}
// ListNamespaced calls ListNamespacedFunc.
func (mock *SettingInterfaceMock) ListNamespaced(namespace string, opts metav1.ListOptions) (*v3.SettingList, error) {
if mock.ListNamespacedFunc == nil {
panic("SettingInterfaceMock.ListNamespacedFunc: method is nil but SettingInterface.ListNamespaced was just called")
}
callInfo := struct {
Namespace string
Opts metav1.ListOptions
}{
Namespace: namespace,
Opts: opts,
}
lockSettingInterfaceMockListNamespaced.Lock()
mock.calls.ListNamespaced = append(mock.calls.ListNamespaced, callInfo)
lockSettingInterfaceMockListNamespaced.Unlock()
return mock.ListNamespacedFunc(namespace, opts)
}
// ListNamespacedCalls gets all the calls that were made to ListNamespaced.
// Check the length with:
// len(mockedSettingInterface.ListNamespacedCalls())
func (mock *SettingInterfaceMock) ListNamespacedCalls() []struct {
Namespace string
Opts metav1.ListOptions
} {
var calls []struct {
Namespace string
Opts metav1.ListOptions
}
lockSettingInterfaceMockListNamespaced.RLock()
calls = mock.calls.ListNamespaced
lockSettingInterfaceMockListNamespaced.RUnlock()
return calls
}
// ObjectClient calls ObjectClientFunc.
func (mock *SettingInterfaceMock) ObjectClient() *objectclient.ObjectClient {
if mock.ObjectClientFunc == nil {
panic("SettingInterfaceMock.ObjectClientFunc: method is nil but SettingInterface.ObjectClient was just called")
}
callInfo := struct {
}{}
lockSettingInterfaceMockObjectClient.Lock()
mock.calls.ObjectClient = append(mock.calls.ObjectClient, callInfo)
lockSettingInterfaceMockObjectClient.Unlock()
return mock.ObjectClientFunc()
}
// ObjectClientCalls gets all the calls that were made to ObjectClient.
// Check the length with:
// len(mockedSettingInterface.ObjectClientCalls())
func (mock *SettingInterfaceMock) ObjectClientCalls() []struct {
} {
var calls []struct {
}
lockSettingInterfaceMockObjectClient.RLock()
calls = mock.calls.ObjectClient
lockSettingInterfaceMockObjectClient.RUnlock()
return calls
}
// Update calls UpdateFunc.
func (mock *SettingInterfaceMock) Update(in1 *v3.Setting) (*v3.Setting, error) {
if mock.UpdateFunc == nil {
panic("SettingInterfaceMock.UpdateFunc: method is nil but SettingInterface.Update was just called")
}
callInfo := struct {
In1 *v3.Setting
}{
In1: in1,
}
lockSettingInterfaceMockUpdate.Lock()
mock.calls.Update = append(mock.calls.Update, callInfo)
lockSettingInterfaceMockUpdate.Unlock()
return mock.UpdateFunc(in1)
}
// UpdateCalls gets all the calls that were made to Update.
// Check the length with:
// len(mockedSettingInterface.UpdateCalls())
func (mock *SettingInterfaceMock) UpdateCalls() []struct {
In1 *v3.Setting
} {
var calls []struct {
In1 *v3.Setting
}
lockSettingInterfaceMockUpdate.RLock()
calls = mock.calls.Update
lockSettingInterfaceMockUpdate.RUnlock()
return calls
}
// Watch calls WatchFunc.
func (mock *SettingInterfaceMock) Watch(opts metav1.ListOptions) (watch.Interface, error) {
if mock.WatchFunc == nil {
panic("SettingInterfaceMock.WatchFunc: method is nil but SettingInterface.Watch was just called")
}
callInfo := struct {
Opts metav1.ListOptions
}{
Opts: opts,
}
lockSettingInterfaceMockWatch.Lock()
mock.calls.Watch = append(mock.calls.Watch, callInfo)
lockSettingInterfaceMockWatch.Unlock()
return mock.WatchFunc(opts)
}
// WatchCalls gets all the calls that were made to Watch.
// Check the length with:
// len(mockedSettingInterface.WatchCalls())
func (mock *SettingInterfaceMock) WatchCalls() []struct {
Opts metav1.ListOptions
} {
var calls []struct {
Opts metav1.ListOptions
}
lockSettingInterfaceMockWatch.RLock()
calls = mock.calls.Watch
lockSettingInterfaceMockWatch.RUnlock()
return calls
}
var (
lockSettingsGetterMockSettings sync.RWMutex
)
// Ensure, that SettingsGetterMock does implement v31.SettingsGetter.
// If this is not the case, regenerate this file with moq.
var _ v31.SettingsGetter = &SettingsGetterMock{}
// SettingsGetterMock is a mock implementation of v31.SettingsGetter.
//
// func TestSomethingThatUsesSettingsGetter(t *testing.T) {
//
// // make and configure a mocked v31.SettingsGetter
// mockedSettingsGetter := &SettingsGetterMock{
// SettingsFunc: func(namespace string) v31.SettingInterface {
// panic("mock out the Settings method")
// },
// }
//
// // use mockedSettingsGetter in code that requires v31.SettingsGetter
// // and then make assertions.
//
// }
type SettingsGetterMock struct {
// SettingsFunc mocks the Settings method.
SettingsFunc func(namespace string) v31.SettingInterface
// calls tracks calls to the methods.
calls struct {
// Settings holds details about calls to the Settings method.
Settings []struct {
// Namespace is the namespace argument value.
Namespace string
}
}
}
// Settings calls SettingsFunc.
func (mock *SettingsGetterMock) Settings(namespace string) v31.SettingInterface {
if mock.SettingsFunc == nil {
panic("SettingsGetterMock.SettingsFunc: method is nil but SettingsGetter.Settings was just called")
}
callInfo := struct {
Namespace string
}{
Namespace: namespace,
}
lockSettingsGetterMockSettings.Lock()
mock.calls.Settings = append(mock.calls.Settings, callInfo)
lockSettingsGetterMockSettings.Unlock()
return mock.SettingsFunc(namespace)
}
// SettingsCalls gets all the calls that were made to Settings.
// Check the length with:
// len(mockedSettingsGetter.SettingsCalls())
func (mock *SettingsGetterMock) SettingsCalls() []struct {
Namespace string
} {
var calls []struct {
Namespace string
}
lockSettingsGetterMockSettings.RLock()
calls = mock.calls.Settings
lockSettingsGetterMockSettings.RUnlock()
return calls
}
| rancher/rancher | pkg/generated/norman/management.cattle.io/v3/fakes/zz_generated_setting_mock.go | GO | apache-2.0 | 61,844 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/transcribe/TranscribeService_EXPORTS.h>
#include <aws/core/Region.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace TranscribeService
{
namespace TranscribeServiceEndpoint
{
AWS_TRANSCRIBESERVICE_API Aws::String ForRegion(const Aws::String& regionName, bool useDualStack = false);
} // namespace TranscribeServiceEndpoint
} // namespace TranscribeService
} // namespace Aws
| jt70471/aws-sdk-cpp | aws-cpp-sdk-transcribe/include/aws/transcribe/TranscribeServiceEndpoint.h | C | apache-2.0 | 553 |
# Contributing to Kismatic:
First, thank you for any and all contributions! We always love to hear from our community and encourage everyone to submit pull requests that will improve the project.
Before submitting any major changes, here are some suggested guidelines:
1. Join the our public [Slack][slack] community to ask questions about any specific features, problems you may have, support needed, use cases or general approaches to using Kismatic.
1. Check the [open issues][issues] and [pull requests][prs] for existing discussions.
1. Open an [issue][issues] first, to discuss a new feature or enhancement.
1. Write tests, and make sure the test suite passes locally and on CI.
1. Open a pull request, and reference the relevant issue(s).
1. After receiving feedback, [squash your commits][squash] and add a [great commit message][message].
1. Have fun!
[slack]: https://kismatic.slack.com
[issues]: https://github.com/apprenda/kismatic/issues
[prs]: https://github.com/apprenda/kismatic/pulls
[squash]: http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html
[message]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
| apprenda/kismatic | docs/development/CONTRIBUTING.md | Markdown | apache-2.0 | 1,170 |
<?php
return [
'interfaces' => [
'google.cloud.compute.v1.GlobalOperations' => [
'AggregatedList' => [
'pageStreaming' => [
'requestPageTokenGetMethod' => 'getPageToken',
'requestPageTokenSetMethod' => 'setPageToken',
'requestPageSizeGetMethod' => 'getMaxResults',
'requestPageSizeSetMethod' => 'setMaxResults',
'responsePageTokenGetMethod' => 'getNextPageToken',
'resourcesGetMethod' => 'getItems',
],
],
'List' => [
'pageStreaming' => [
'requestPageTokenGetMethod' => 'getPageToken',
'requestPageTokenSetMethod' => 'setPageToken',
'requestPageSizeGetMethod' => 'getMaxResults',
'requestPageSizeSetMethod' => 'setMaxResults',
'responsePageTokenGetMethod' => 'getNextPageToken',
'resourcesGetMethod' => 'getItems',
],
],
],
],
];
| googleapis/google-cloud-php-compute | src/V1/resources/global_operations_descriptor_config.php | PHP | apache-2.0 | 1,107 |
select * from Emp where id = /*%if id.intValue() == 0*/ id = /*id*/1 /*%end*/ | backpaper0/doma2 | src/test/resources/META-INF/org/seasar/doma/internal/apt/dao/MethodAccessSqlValidationDao/select.sql | SQL | apache-2.0 | 77 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.DataMigration.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Description about the errors happen while performing migration
/// validation
/// </summary>
public partial class SchemaComparisonValidationResultType
{
/// <summary>
/// Initializes a new instance of the
/// SchemaComparisonValidationResultType class.
/// </summary>
public SchemaComparisonValidationResultType()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// SchemaComparisonValidationResultType class.
/// </summary>
/// <param name="objectName">Name of the object that has the
/// difference</param>
/// <param name="objectType">Type of the object that has the
/// difference. e.g (Table/View/StoredProcedure). Possible values
/// include: 'StoredProcedures', 'Table', 'User', 'View',
/// 'Function'</param>
/// <param name="updateAction">Update action type with respect to
/// target. Possible values include: 'DeletedOnTarget',
/// 'ChangedOnTarget', 'AddedOnTarget'</param>
public SchemaComparisonValidationResultType(string objectName = default(string), ObjectType? objectType = default(ObjectType?), UpdateActionType? updateAction = default(UpdateActionType?))
{
ObjectName = objectName;
ObjectType = objectType;
UpdateAction = updateAction;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets name of the object that has the difference
/// </summary>
[JsonProperty(PropertyName = "objectName")]
public string ObjectName { get; set; }
/// <summary>
/// Gets or sets type of the object that has the difference. e.g
/// (Table/View/StoredProcedure). Possible values include:
/// 'StoredProcedures', 'Table', 'User', 'View', 'Function'
/// </summary>
[JsonProperty(PropertyName = "objectType")]
public ObjectType? ObjectType { get; set; }
/// <summary>
/// Gets or sets update action type with respect to target. Possible
/// values include: 'DeletedOnTarget', 'ChangedOnTarget',
/// 'AddedOnTarget'
/// </summary>
[JsonProperty(PropertyName = "updateAction")]
public UpdateActionType? UpdateAction { get; set; }
}
}
| SiddharthChatrolaMs/azure-sdk-for-net | src/SDKs/DataMigration/Management.DataMigration/Generated/Models/SchemaComparisonValidationResultType.cs | C# | apache-2.0 | 3,028 |
package io.dropwizard.logging;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import io.dropwizard.jackson.DiscoverableSubtypeResolver;
import io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory;
import io.dropwizard.logging.filter.NullLevelFilterFactory;
import io.dropwizard.logging.layout.DropwizardLayoutFactory;
import io.dropwizard.util.Size;
import io.dropwizard.validation.BaseValidator;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import io.dropwizard.validation.ConstraintViolations;
import javax.validation.Validator;
import static org.assertj.core.api.Assertions.assertThat;
public class FileAppenderFactoryTest {
static {
BootstrapLogging.bootstrap();
}
private final Validator validator = BaseValidator.newValidator();
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void isDiscoverable() throws Exception {
assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes())
.contains(FileAppenderFactory.class);
}
@Test
public void includesCallerData() {
FileAppenderFactory<ILoggingEvent> fileAppenderFactory = new FileAppenderFactory<>();
fileAppenderFactory.setArchive(false);
AsyncAppender asyncAppender = (AsyncAppender) fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(asyncAppender.isIncludeCallerData()).isFalse();
fileAppenderFactory.setIncludeCallerData(true);
asyncAppender = (AsyncAppender) fileAppenderFactory.build(new LoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(asyncAppender.isIncludeCallerData()).isTrue();
}
@Test
public void isRolling() throws Exception {
// the method we want to test is protected, so we need to override it so we can see it
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory<ILoggingEvent>() {
@Override
public FileAppender<ILoggingEvent> buildAppender(LoggerContext context) {
return super.buildAppender(context);
}
};
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d.log.gz").toString());
assertThat(fileAppenderFactory.buildAppender(new LoggerContext())).isInstanceOf(RollingFileAppender.class);
}
@Test
public void hasArchivedLogFilenamePattern() throws Exception{
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory();
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
ImmutableList<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("must have archivedLogFilenamePattern if archive is true");
fileAppenderFactory.setArchive(false);
errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
public void isValidForMaxFileSize() throws Exception{
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory();
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
fileAppenderFactory.setMaxFileSize(Size.kilobytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d.log.gz").toString());
ImmutableList<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("when specifying maxFileSize, archivedLogFilenamePattern must contain %i");
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d-%i.log.gz").toString());
errors = ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
public void hasMaxFileSizeValidation() throws Exception{
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory();
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%i.log.gz").toString());
ImmutableList<String> errors =
ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors)
.containsOnly("when archivedLogFilenamePattern contains %i, maxFileSize must be specified");
fileAppenderFactory.setMaxFileSize(Size.kilobytes(1));
errors = ConstraintViolations.format(validator.validate(fileAppenderFactory));
assertThat(errors).isEmpty();
}
@Test
public void hasMaxFileSize() throws Exception {
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory();
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setMaxFileSize(Size.kilobytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d-%i.log.gz").toString());
RollingFileAppender<ILoggingEvent> appender = (RollingFileAppender<ILoggingEvent>) fileAppenderFactory.buildAppender(new LoggerContext());
assertThat(appender.getTriggeringPolicy()).isInstanceOf(SizeAndTimeBasedFNATP.class);
assertThat(((SizeAndTimeBasedFNATP) appender.getTriggeringPolicy()).getMaxFileSize()).isEqualTo("1024");
}
@Test
public void hasMaxFileSizeFixedWindow() throws Exception {
FileAppenderFactory fileAppenderFactory = new FileAppenderFactory();
fileAppenderFactory.setCurrentLogFilename(folder.newFile("logfile.log").toString());
fileAppenderFactory.setArchive(true);
fileAppenderFactory.setMaxFileSize(Size.kilobytes(1));
fileAppenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%i.log.gz").toString());
RollingFileAppender<ILoggingEvent> appender = (RollingFileAppender<ILoggingEvent>) fileAppenderFactory.buildAppender(new LoggerContext());
assertThat(appender.getRollingPolicy()).isInstanceOf(FixedWindowRollingPolicy.class);
assertThat(appender.getTriggeringPolicy()).isInstanceOf(SizeBasedTriggeringPolicy.class);
assertThat(((SizeBasedTriggeringPolicy) appender.getTriggeringPolicy()).getMaxFileSize()).isEqualTo("1024");
}
@Test
public void appenderContextIsSet() throws Exception {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>();
appenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d.log.gz").toString());
final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(appender.getContext()).isEqualTo(root.getLoggerContext());
}
@Test
public void appenderNameIsSet() throws Exception {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final FileAppenderFactory<ILoggingEvent> appenderFactory = new FileAppenderFactory<>();
appenderFactory.setArchivedLogFilenamePattern(folder.newFile("example-%d.log.gz").toString());
final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory());
assertThat(appender.getName()).isEqualTo("async-file-appender");
}
}
| mattnelson/dropwizard | dropwizard-logging/src/test/java/io/dropwizard/logging/FileAppenderFactoryTest.java | Java | apache-2.0 | 8,647 |
# Adobe Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [email protected]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [https://contributor-covenant.org/version/1/4][version]
[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/ | khakiout/aem-project-archetype | CODE_OF_CONDUCT.md | Markdown | apache-2.0 | 3,225 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.12.3_4-1-3
description: JSON.stringify a indirectly circular object throws a error
---*/
var obj = {p1: {p2: {}}};
obj.p1.p2.prop = obj;
assert.throws(TypeError, function() {
JSON.stringify(obj);
});
| m0ppers/arangodb | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/JSON/stringify/15.12.3_4-1-3.js | JavaScript | apache-2.0 | 363 |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you 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 org.openqa.selenium.remote.internal;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WrappedWebElement;
import org.openqa.selenium.remote.Dialect;
import org.openqa.selenium.remote.RemoteWebElement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class WebElementToJsonConverterTest {
private static final WebElementToJsonConverter CONVERTER = new WebElementToJsonConverter();
@Test
public void returnsPrimitivesAsIs() {
assertThat(CONVERTER.apply(null)).isNull();
assertThat(CONVERTER.apply("abc")).isEqualTo("abc");
assertThat(CONVERTER.apply(Boolean.TRUE)).isEqualTo(Boolean.TRUE);
assertThat(CONVERTER.apply(123)).isEqualTo(123);
assertThat(CONVERTER.apply(Math.PI)).isEqualTo(Math.PI);
}
@Test
public void convertsRemoteWebElementToWireProtocolMap() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
Object value = CONVERTER.apply(element);
assertIsWebElementObject(value, "abc123");
}
@Test
public void unwrapsWrappedElements() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
Object value = CONVERTER.apply(wrapElement(element));
assertIsWebElementObject(value, "abc123");
}
@Test
public void unwrapsWrappedElements_multipleLevelsOfWrapping() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
WrappedWebElement wrapped = wrapElement(element);
wrapped = wrapElement(wrapped);
wrapped = wrapElement(wrapped);
wrapped = wrapElement(wrapped);
Object value = CONVERTER.apply(wrapped);
assertIsWebElementObject(value, "abc123");
}
@Test
public void convertsSimpleCollections() {
Object converted = CONVERTER.apply(asList(null, "abc", true, 123, Math.PI));
assertThat(converted).isInstanceOf(Collection.class);
List<?> list = new ArrayList<>((Collection<?>) converted);
assertContentsInOrder(list, null, "abc", true, 123, Math.PI);
}
@Test
public void convertsNestedCollections_simpleValues() {
List<?> innerList = asList(123, "abc");
List<Object> outerList = asList("apples", "oranges", innerList);
Object converted = CONVERTER.apply(outerList);
assertThat(converted).isInstanceOf(Collection.class);
List<?> list = ImmutableList.copyOf((Collection<?>) converted);
assertThat(list).hasSize(3);
assertThat(list.get(0)).isEqualTo("apples");
assertThat(list.get(1)).isEqualTo("oranges");
assertThat(list.get(2)).isInstanceOf(Collection.class);
list = ImmutableList.copyOf((Collection<?>) list.get(2));
assertContentsInOrder(list, 123, "abc");
}
@Test
public void requiresMapsToHaveStringKeys() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> CONVERTER.apply(ImmutableMap.of(new Object(), "bunny")));
}
@Test
public void requiresNestedMapsToHaveStringKeys() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> CONVERTER.apply(
ImmutableMap.of("one", ImmutableMap.of("two", ImmutableMap.of(3, "not good")))));
}
@Test
public void convertsASimpleMap() {
Object converted = CONVERTER.apply(ImmutableMap.of(
"one", 1,
"fruit", "apples",
"honest", true));
assertThat(converted).isInstanceOf(Map.class);
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) converted;
assertThat(map).hasSize(3);
assertThat(map.get("one")).isEqualTo(1);
assertThat(map.get("fruit")).isEqualTo("apples");
assertThat(map.get("honest")).isEqualTo(true);
}
@SuppressWarnings("unchecked")
@Test
public void convertsANestedMap() {
Object converted = CONVERTER.apply(ImmutableMap.of(
"one", 1,
"fruit", "apples",
"honest", true,
"nested", ImmutableMap.of("bugs", "bunny")));
assertThat(converted).isInstanceOf(Map.class);
Map<String, Object> map = (Map<String, Object>) converted;
assertThat(map).hasSize(4);
assertThat(map.get("one")).isEqualTo(1);
assertThat(map.get("fruit")).isEqualTo("apples");
assertThat(map.get("honest")).isEqualTo(true);
assertThat(map.get("nested")).isInstanceOf(Map.class);
map = (Map<String, Object>) map.get("nested");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("bugs")).isEqualTo("bunny");
}
@SuppressWarnings("unchecked")
@Test
public void convertsAListWithAWebElement() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
RemoteWebElement element2 = new RemoteWebElement();
element2.setId("anotherId");
Object value = CONVERTER.apply(asList(element, element2));
assertThat(value).isInstanceOf(Collection.class);
List<Object> list = new ArrayList<>((Collection<Object>) value);
assertThat(list).hasSize(2);
assertIsWebElementObject(list.get(0), "abc123");
assertIsWebElementObject(list.get(1), "anotherId");
}
@SuppressWarnings("unchecked")
@Test
public void convertsAMapWithAWebElement() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
Object value = CONVERTER.apply(ImmutableMap.of("one", element));
assertThat(value).isInstanceOf(Map.class);
Map<String, Object> map = (Map<String, Object>) value;
assertThat(map.size()).isEqualTo(1);
assertIsWebElementObject(map.get("one"), "abc123");
}
@Test
public void convertsAnArray() {
Object value = CONVERTER.apply(new Object[] {
"abc123", true, 123, Math.PI
});
assertThat(value).isInstanceOf(Collection.class);
assertContentsInOrder(new ArrayList<>((Collection<?>) value),
"abc123", true, 123, Math.PI);
}
@Test
public void convertsAnArrayWithAWebElement() {
RemoteWebElement element = new RemoteWebElement();
element.setId("abc123");
Object value = CONVERTER.apply(new Object[] { element });
assertContentsInOrder(new ArrayList<>((Collection<?>) value),
ImmutableMap.of(
Dialect.OSS.getEncodedElementKey(), "abc123",
Dialect.W3C.getEncodedElementKey(), "abc123"));
}
private static WrappedWebElement wrapElement(WebElement element) {
return new WrappedWebElement(element);
}
private static void assertIsWebElementObject(Object value, String expectedKey) {
assertThat(value).isInstanceOf(Map.class);
Map<?, ?> map = (Map<?, ?>) value;
assertThat(map).hasSize(2);
assertThat(map.containsKey(Dialect.OSS.getEncodedElementKey())).isTrue();
assertThat(map.get(Dialect.OSS.getEncodedElementKey())).isEqualTo(expectedKey);
assertThat(map.containsKey(Dialect.W3C.getEncodedElementKey())).isTrue();
assertThat(map.get(Dialect.W3C.getEncodedElementKey())).isEqualTo(expectedKey);
}
private static void assertContentsInOrder(List<?> list, Object... expectedContents) {
List<Object> expected = asList(expectedContents);
assertThat(list).isEqualTo(expected);
}
}
| chrisblock/selenium | java/client/test/org/openqa/selenium/remote/internal/WebElementToJsonConverterTest.java | Java | apache-2.0 | 8,155 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--*** This is a generated file. Do not edit. ***-->
<link rel="stylesheet" href="../skin/tigris.css" type="text/css">
<link rel="stylesheet" href="../skin/mysite.css" type="text/css">
<link rel="stylesheet" href="../skin/site.css" type="text/css">
<link media="print" rel="stylesheet" href="../skin/print.css" type="text/css">
<title>Chart record information</title>
</head>
<body bgcolor="white" class="composite">
<!--================= start Banner ==================-->
<div id="banner">
<table width="100%" cellpadding="8" cellspacing="0" summary="banner" border="0">
<tbody>
<tr>
<!--================= start Group Logo ==================-->
<td width="50%" align="left">
<div class="groupLogo">
<a href="http://poi.apache.org"><img border="0" class="logoImage" alt="Apache POI" src="../resources/images/group-logo.jpg"></a>
</div>
</td>
<!--================= end Group Logo ==================-->
<!--================= start Project Logo ==================--><td width="50%" align="right">
<div align="right" class="projectLogo">
<a href="http://poi.apache.org/"><img border="0" class="logoImage" alt="POI" src="../resources/images/project-logo.jpg"></a>
</div>
</td>
<!--================= end Project Logo ==================-->
</tr>
</tbody>
</table>
</div>
<!--================= end Banner ==================-->
<!--================= start Main ==================-->
<table width="100%" cellpadding="0" cellspacing="0" border="0" summary="nav" id="breadcrumbs">
<tbody>
<!--================= start Status ==================-->
<tr class="status">
<td>
<!--================= start BreadCrumb ==================--><a href="http://www.apache.org/">Apache</a> | <a href="http://poi.apache.org/">POI</a><a href=""></a>
<!--================= end BreadCrumb ==================--></td><td id="tabs">
<!--================= start Tabs ==================-->
<div class="tab">
<span class="selectedTab"><a class="base-selected" href="../index.html">Home</a></span> | <script language="Javascript" type="text/javascript">
function printit() {
if (window.print) {
window.print() ;
} else {
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH="0" HEIGHT="0" CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";
}
}
</script><script language="Javascript" type="text/javascript">
var NS = (navigator.appName == "Netscape");
var VERSION = parseInt(navigator.appVersion);
if (VERSION > 3) {
document.write(' <a title="PRINT this page OUT" href="javascript:printit()">PRINT</a>');
}
</script>
</div>
<!--================= end Tabs ==================-->
</td>
</tr>
</tbody>
</table>
<!--================= end Status ==================-->
<table id="main" width="100%" cellpadding="8" cellspacing="0" summary="" border="0">
<tbody>
<tr valign="top">
<!--================= start Menu ==================-->
<td id="leftcol">
<div id="navcolumn">
<div class="menuBar">
<div class="menu">
<span class="menuLabel">Apache POI</span>
<div class="menuItem">
<a href="../index.html">Top</a>
</div>
</div>
<div class="menu">
<span class="menuLabel">HSSF+XSSF</span>
<div class="menuItem">
<a href="index.html">Overview</a>
</div>
<div class="menuItem">
<a href="quick-guide.html">Quick Guide</a>
</div>
<div class="menuItem">
<a href="how-to.html">HOWTO</a>
</div>
<div class="menuItem">
<a href="converting.html">HSSF to SS Converting</a>
</div>
<div class="menuItem">
<a href="formula.html">Formula Support</a>
</div>
<div class="menuItem">
<a href="eval.html">Formula Evaluation</a>
</div>
<div class="menuItem">
<a href="eval-devguide.html">Eval Dev Guide</a>
</div>
<div class="menuItem">
<a href="examples.html">Examples</a>
</div>
<div class="menuItem">
<a href="use-case.html">Use Case</a>
</div>
<div class="menuItem">
<a href="diagrams.html">Pictorial Docs</a>
</div>
<div class="menuItem">
<a href="limitations.html">Limitations</a>
</div>
<div class="menuItem">
<a href="user-defined-functions.html">User Defined Functions</a>
</div>
<div class="menuItem">
<a href="excelant.html">ExcelAnt Tests</a>
</div>
</div>
<div class="menu">
<span class="menuLabel">Contributer's Guide</span>
<div class="menuItem">
<a href="hacking-hssf.html">Hacking HSSF</a>
</div>
<div class="menuItem">
<a href="record-generator.html">Record Generator</a>
</div>
<div class="menuItem">
<span class="menuSelected">Charts</span>
</div>
</div>
</div>
</div>
<form target="_blank" action="http://www.google.com/search" method="get">
<table summary="search" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><img height="1" width="1" alt="" src="../skin/images/spacer.gif" class="spacer"></td><td nowrap="nowrap">
Search Apache POI<br>
<input value="poi.apache.org" name="sitesearch" type="hidden"><input size="10" name="q" id="query" type="text"><img height="1" width="5" alt="" src="../skin/images/spacer.gif" class="spacer"><input name="Search" value="GO" type="submit"></td><td><img height="1" width="1" alt="" src="../skin/images/spacer.gif" class="spacer"></td>
</tr>
<tr>
<td colspan="3"><img height="7" width="1" alt="" src="../skin/images/spacer.gif" class="spacer"></td>
</tr>
<tr>
<td class="bottom-left-thick"></td><td bgcolor="#a5b6c6"><img height="1" width="1" alt="" src="../skin/images/spacer.gif" class="spacer"></td><td class="bottom-right-thick"></td>
</tr>
</table>
</form>
</td>
<!--================= end Menu ==================-->
<!--================= start Content ==================--><td>
<div id="bodycol">
<div class="app">
<div align="center">
<h1>Chart record information</h1>
</div>
<div class="h3">
<a name="Introduction"></a>
<div class="h3">
<h3>Introduction</h3>
</div>
<p>
This document is intended as a work in progress for describing
our current understanding of how the chart records are are
written to produce a valid chart.
</p>
<a name="Bar+chart"></a>
<div class="h3">
<h3>Bar chart</h3>
</div>
<p>
The following records detail the records written for a
'simple' bar chart.
</p>
<pre class="code">
============================================
rectype = 0xec, recsize = 0xc8
-BEGIN DUMP---------------------------------
00000000 0F 00 02 F0 C0 00 00 00 10 00 08 F0 08 00 00 00 ................
00000010 02 00 00 00 02 04 00 00 0F 00 03 F0 A8 00 00 00 ................
00000020 0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 ....(...........
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000040 02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 ................
00000050 0F 00 04 F0 70 00 00 00 92 0C 0A F0 08 00 00 00 ....p...........
00000060 02 04 00 00 00 0A 00 00 93 00 0B F0 36 00 00 00 ............6...
00000070 7F 00 04 01 04 01 BF 00 08 00 08 00 81 01 4E 00 ..............N.
00000080 00 08 83 01 4D 00 00 08 BF 01 10 00 11 00 C0 01 ....M...........
00000090 4D 00 00 08 FF 01 08 00 08 00 3F 02 00 00 02 00 M.........?.....
000000A0 BF 03 00 00 08 00 00 00 10 F0 12 00 00 00 00 00 ................
000000B0 04 00 C0 02 0A 00 F4 00 0E 00 66 01 20 00 E9 00 ..........f. ...
000000C0 00 00 11 F0 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0xec, size =200
[UNKNOWN RECORD:ec]
.id = ec
[/UNKNOWN RECORD]
============================================
rectype = 0x5d, recsize = 0x1a
-BEGIN DUMP---------------------------------
00000000 15 00 12 00 05 00 02 00 11 60 00 00 00 00 B8 03 .........`......
00000010 87 03 00 00 00 00 00 00 00 00 ..........
-END DUMP-----------------------------------
recordid = 0x5d, size =26
[UNKNOWN RECORD:5d]
.id = 5d
[/UNKNOWN RECORD]
============================================
rectype = 0x809, recsize = 0x10
-BEGIN DUMP---------------------------------
00000000 00 06 20 00 FE 1C CD 07 C9 40 00 00 06 01 00 00 .. ......@......
-END DUMP-----------------------------------
recordid = 0x809, size =16
[BOF RECORD]
.version = 600
.type = 20
.build = 1cfe
.buildyear = 1997
.history = 40c9
.requiredversion = 106
[/BOF RECORD]
============================================
rectype = 0x14, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x14, size =0
[HEADER]
.length = 0
.header = null
[/HEADER]
============================================
rectype = 0x15, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x15, size =0
[FOOTER]
.footerlen = 0
.footer = null
[/FOOTER]
============================================
rectype = 0x83, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x83, size =2
[HCENTER]
.hcenter = false
[/HCENTER]
============================================
rectype = 0x84, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x84, size =2
[VCENTER]
.vcenter = false
[/VCENTER]
============================================
rectype = 0xa1, recsize = 0x22
-BEGIN DUMP---------------------------------
00000000 00 00 12 00 01 00 01 00 01 00 04 00 00 00 B8 03 ................
00000010 00 00 00 00 00 00 E0 3F 00 00 00 00 00 00 E0 3F .......?.......?
00000020 0F 00 ..
-END DUMP-----------------------------------
recordid = 0xa1, size =34
[PRINTSETUP]
.papersize = 0
.scale = 18
.pagestart = 1
.fitwidth = 1
.fitheight = 1
.options = 4
.ltor = false
.landscape = false
.valid = true
.mono = false
.draft = false
.notes = false
.noOrientat = false
.usepage = false
.hresolution = 0
.vresolution = 952
.headermargin = 0.5
.footermargin = 0.5
.copies = 15
[/PRINTSETUP]
<!-- Comment to avoid forrest bug -->
============================================
rectype = 0x33, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 03 00 ..
-END DUMP-----------------------------------
recordid = 0x33, size =2
[UNKNOWN RECORD:33]
.id = 33
[/UNKNOWN RECORD]
============================================
rectype = 0x1060, recsize = 0xa
-BEGIN DUMP---------------------------------
00000000 A0 23 08 16 C8 00 00 00 05 00 .#........
-END DUMP-----------------------------------
recordid = 0x1060, size =10
[FBI]
.xBasis = 0x23A0 (9120 )
.yBasis = 0x1608 (5640 )
.heightBasis = 0x00C8 (200 )
.scale = 0x0000 (0 )
.indexToFontTable = 0x0005 (5 )
[/FBI]
============================================
rectype = 0x1060, recsize = 0xa
-BEGIN DUMP---------------------------------
00000000 A0 23 08 16 C8 00 01 00 06 00 .#........
-END DUMP-----------------------------------
recordid = 0x1060, size =10
[FBI]
.xBasis = 0x23A0 (9120 )
.yBasis = 0x1608 (5640 )
.heightBasis = 0x00C8 (200 )
.scale = 0x0001 (1 )
.indexToFontTable = 0x0006 (6 )
[/FBI]
============================================
rectype = 0x12, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x12, size =2
[PROTECT]
.rowheight = 0
[/PROTECT]
============================================
Offset 0xf22 (3874)
rectype = 0x1001, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x1001, size =2
[UNITS]
.units = 0x0000 (0 )
[/UNITS]
============================================
Offset 0xf28 (3880)
rectype = 0x1002, recsize = 0x10
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 00 00 58 66 D0 01 40 66 22 01 ........Xf..@f".
-END DUMP-----------------------------------
recordid = 0x1002, size =16
[CHART]
.x = 0x00000000 (0 )
.y = 0x00000000 (0 )
.width = 0x01D06658 (30434904 )
.height = 0x01226640 (19031616 )
[/CHART]
============================================
Offset 0xf3c (3900)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0xf40 (3904)
rectype = 0xa0, recsize = 0x4
-BEGIN DUMP---------------------------------
00000000 01 00 01 00 ....
-END DUMP-----------------------------------
recordid = 0xa0, size =4
[SCL]
.numerator = 0x0001 (1 )
.denominator = 0x0001 (1 )
[/SCL]
<!-- Comment to avoid forrest bug -->
============================================
Offset 0xf48 (3912)
rectype = 0x1064, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 00 01 00 00 00 01 00 ........
-END DUMP-----------------------------------
recordid = 0x1064, size =8
[PLOTGROWTH]
.horizontalScale = 0x00010000 (65536 )
.verticalScale = 0x00010000 (65536 )
[/PLOTGROWTH]
============================================
Offset 0xf54 (3924)
rectype = 0x1032, recsize = 0x4
-BEGIN DUMP---------------------------------
00000000 00 00 02 00 ....
-END DUMP-----------------------------------
recordid = 0x1032, size =4
[FRAME]
.borderType = 0x0000 (0 )
.options = 0x0002 (2 )
.autoSize = false
.autoPosition = true
[/FRAME]
============================================
Offset 0xf5c (3932)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0xf60 (3936)
rectype = 0x1007, recsize = 0xc
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 FF FF 09 00 4D 00 ..........M.
-END DUMP-----------------------------------
recordid = 0x1007, size =12
[LINEFORMAT]
.lineColor = 0x00000000 (0 )
.linePattern = 0x0000 (0 )
.weight = 0xFFFF (-1 )
.format = 0x0009 (9 )
.auto = true
.drawTicks = false
.unknown = false
.colourPaletteIndex = 0x004D (77 )
[/LINEFORMAT]
============================================
Offset 0xf70 (3952)
rectype = 0x100a, recsize = 0x10
-BEGIN DUMP---------------------------------
00000000 FF FF FF 00 00 00 00 00 01 00 01 00 4E 00 4D 00 ............N.M.
-END DUMP-----------------------------------
recordid = 0x100a, size =16
[AREAFORMAT]
.foregroundColor = 0x00FFFFFF (16777215 )
.backgroundColor = 0x00000000 (0 )
.pattern = 0x0001 (1 )
.formatFlags = 0x0001 (1 )
.automatic = true
.invert = false
.forecolorIndex = 0x004E (78 )
.backcolorIndex = 0x004D (77 )
[/AREAFORMAT]
============================================
Offset 0xf84 (3972)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0xf88 (3976)
rectype = 0x1003, recsize = 0xc
-BEGIN DUMP---------------------------------
00000000 01 00 01 00 20 00 1F 00 01 00 00 00 .... .......
-END DUMP-----------------------------------
recordid = 0x1003, size =12
[SERIES]
.categoryDataType = 0x0001 (1 )
.valuesDataType = 0x0001 (1 )
.numCategories = 0x0020 (32 )
.numValues = 0x001F (31 )
.bubbleSeriesType = 0x0001 (1 )
.numBubbleValues = 0x0000 (0 )
[/SERIES]
============================================
Offset 0xf98 (3992)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
<!-- Comment to avoid forrest bug -->
============================================
Offset 0xf9c (3996)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x00 (0 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1ee3914 )
[/AI]
============================================
Offset 0xfa8 (4008)
rectype = 0x1051, recsize = 0x13
-BEGIN DUMP---------------------------------
00000000 01 02 00 00 00 00 0B 00 3B 00 00 00 00 1E 00 01 ........;.......
00000010 00 01 00 ...
-END DUMP-----------------------------------
recordid = 0x1051, size =19
[AI]
.linkType = 0x01 (1 )
.referenceType = 0x02 (2 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@e5855a )
[/AI]
============================================
Offset 0xfbf (4031)
rectype = 0x1051, recsize = 0x13
-BEGIN DUMP---------------------------------
00000000 02 02 00 00 69 01 0B 00 3B 00 00 00 00 1F 00 00 ....i...;.......
00000010 00 00 00 ...
-END DUMP-----------------------------------
recordid = 0x1051, size =19
[AI]
.linkType = 0x02 (2 )
.referenceType = 0x02 (2 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0169 (361 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@95fd19 )
[/AI]
============================================
Offset 0xfd6 (4054)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 03 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x03 (3 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@11b9fb1 )
[/AI]
============================================
Offset 0xfe2 (4066)
rectype = 0x1006, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 FF FF 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1006, size =8
[DATAFORMAT]
.pointNumber = 0xFFFF (-1 )
.seriesIndex = 0x0000 (0 )
.seriesNumber = 0x0000 (0 )
.formatFlags = 0x0000 (0 )
.useExcel4Colors = false
[/DATAFORMAT]
============================================
Offset 0xfee (4078)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0xff2 (4082)
rectype = 0x105f, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x105f, size =2
[UNKNOWN RECORD]
.id = 105f
[/UNKNOWN RECORD]
============================================
Offset 0xff8 (4088)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0xffc (4092)
rectype = 0x1045, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 00 00 ..
-END DUMP-----------------------------------
recordid = 0x1045, size =2
[SeriesToChartGroup]
.chartGroupIndex = 0x0000 (0 )
[/SeriesToChartGroup]
============================================
Offset 0x1002 (4098)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x1006 (4102)
rectype = 0x1044, recsize = 0x4
-BEGIN DUMP---------------------------------
00000000 0A 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x1044, size =4
[SHTPROPS]
.flags = 0x000A (10 )
.chartTypeManuallyFormatted = false
.plotVisibleOnly = true
.doNotSizeWithWindow = false
.defaultPlotDimensions = true
.autoPlotArea = false
.empty = 0x00 (0 )
[/SHTPROPS]
============================================
Offset 0x100e (4110)
rectype = 0x1024, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 02 00 ..
-END DUMP-----------------------------------
recordid = 0x1024, size =2
[DEFAULTTEXT]
.categoryDataType = 0x0002 (2 )
[/DEFAULTTEXT]
============================================
Offset 0x1014 (4116)
rectype = 0x1025, recsize = 0x20
-BEGIN DUMP---------------------------------
00000000 02 02 01 00 00 00 00 00 DB FF FF FF C4 FF FF FF ................
00000010 00 00 00 00 00 00 00 00 B1 00 4D 00 50 2B 00 00 ..........M.P+..
-END DUMP-----------------------------------
recordid = 0x1025, size =32
[TEXT]
.horizontalAlignment = 0x02 (2 )
.verticalAlignment = 0x02 (2 )
.displayMode = 0x0001 (1 )
.rgbColor = 0x00000000 (0 )
.x = 0xFFFFFFDB (-37 )
.y = 0xFFFFFFC4 (-60 )
.width = 0x00000000 (0 )
.height = 0x00000000 (0 )
.options1 = 0x00B1 (177 )
.autoColor = true
.showKey = false
.showValue = false
.vertical = false
.autoGeneratedText = true
.generated = true
.autoLabelDeleted = false
.autoBackground = true
.rotation = 0
.showCategoryLabelAsPercentage = false
.showValueAsPercentage = false
.showBubbleSizes = false
.showLabel = false
.indexOfColorValue = 0x004D (77 )
.options2 = 0x2B50 (11088 )
.dataLabelPlacement = 0
.textRotation = 0x0000 (0 )
[/TEXT]
============================================
Offset 0x1038 (4152)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
<!-- Comment to avoid forrest bug -->
============================================
Offset 0x103c (4156)
rectype = 0x104f, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 02 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x104f, size =20
[UNKNOWN RECORD]
.id = 104f
[/UNKNOWN RECORD]
============================================
Offset 0x1054 (4180)
rectype = 0x1026, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 05 00 ..
-END DUMP-----------------------------------
recordid = 0x1026, size =2
[FONTX]
.fontIndex = 0x0005 (5 )
[/FONTX]
============================================
Offset 0x105a (4186)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x00 (0 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@913fe2 )
[/AI]
============================================
Offset 0x1066 (4198)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x106a (4202)
rectype = 0x1024, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 03 00 ..
-END DUMP-----------------------------------
recordid = 0x1024, size =2
[DEFAULTTEXT]
.categoryDataType = 0x0003 (3 )
[/DEFAULTTEXT]
============================================
Offset 0x1070 (4208)
rectype = 0x1025, recsize = 0x20
-BEGIN DUMP---------------------------------
00000000 02 02 01 00 00 00 00 00 DB FF FF FF C4 FF FF FF ................
00000010 00 00 00 00 00 00 00 00 B1 00 4D 00 50 2B 00 00 ..........M.P+..
-END DUMP-----------------------------------
recordid = 0x1025, size =32
[TEXT]
.horizontalAlignment = 0x02 (2 )
.verticalAlignment = 0x02 (2 )
.displayMode = 0x0001 (1 )
.rgbColor = 0x00000000 (0 )
.x = 0xFFFFFFDB (-37 )
.y = 0xFFFFFFC4 (-60 )
.width = 0x00000000 (0 )
.height = 0x00000000 (0 )
.options1 = 0x00B1 (177 )
.autoColor = true
.showKey = false
.showValue = false
.vertical = false
.autoGeneratedText = true
.generated = true
.autoLabelDeleted = false
.autoBackground = true
.rotation = 0
.showCategoryLabelAsPercentage = false
.showValueAsPercentage = false
.showBubbleSizes = false
.showLabel = false
.indexOfColorValue = 0x004D (77 )
.options2 = 0x2B50 (11088 )
.dataLabelPlacement = 0
.textRotation = 0x0000 (0 )
[/TEXT]
============================================
Offset 0x1094 (4244)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x1098 (4248)
rectype = 0x104f, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 02 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x104f, size =20
[UNKNOWN RECORD]
.id = 104f
[/UNKNOWN RECORD]
============================================
Offset 0x10b0 (4272)
rectype = 0x1026, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 06 00 ..
-END DUMP-----------------------------------
recordid = 0x1026, size =2
[FONTX]
.fontIndex = 0x0006 (6 )
[/FONTX]
============================================
Offset 0x10b6 (4278)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x00 (0 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1f934ad )
[/AI]
============================================
Offset 0x10c2 (4290)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x10c6 (4294)
rectype = 0x1046, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 01 00 ..
-END DUMP-----------------------------------
recordid = 0x1046, size =2
[AXISUSED]
.numAxis = 0x0001 (1 )
[/AXISUSED]
============================================
Offset 0x10cc (4300)
rectype = 0x1041, recsize = 0x12
-BEGIN DUMP---------------------------------
00000000 00 00 DF 01 00 00 DD 00 00 00 B3 0B 00 00 56 0B ..............V.
00000010 00 00 ..
-END DUMP-----------------------------------
recordid = 0x1041, size =18
[AXISPARENT]
.axisType = 0x0000 (0 )
.x = 0x000001DF (479 )
.y = 0x000000DD (221 )
.width = 0x00000BB3 (2995 )
.height = 0x00000B56 (2902 )
[/AXISPARENT]
============================================
Offset 0x10e2 (4322)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x10e6 (4326)
rectype = 0x104f, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 02 00 02 00 3A 00 00 00 5E 00 00 00 58 0D 00 00 ....:...^...X...
00000010 E5 0E 00 00 ....
-END DUMP-----------------------------------
recordid = 0x104f, size =20
[UNKNOWN RECORD]
.id = 104f
[/UNKNOWN RECORD]
============================================
Offset 0x10fe (4350)
rectype = 0x101d, recsize = 0x12
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 ..
-END DUMP-----------------------------------
recordid = 0x101d, size =18
[AXIS]
.axisType = 0x0000 (0 )
.reserved1 = 0x00000000 (0 )
.reserved2 = 0x00000000 (0 )
.reserved3 = 0x00000000 (0 )
.reserved4 = 0x00000000 (0 )
[/AXIS]
============================================
Offset 0x1114 (4372)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x1118 (4376)
rectype = 0x1020, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 01 00 01 00 01 00 01 00 ........
-END DUMP-----------------------------------
recordid = 0x1020, size =8
[CATSERRANGE]
.crossingPoint = 0x0001 (1 )
.labelFrequency = 0x0001 (1 )
.tickMarkFrequency = 0x0001 (1 )
.options = 0x0001 (1 )
.valueAxisCrossing = true
.crossesFarRight = false
.reversed = false
[/CATSERRANGE]
============================================
Offset 0x1124 (4388)
rectype = 0x1062, recsize = 0x12
-BEGIN DUMP---------------------------------
00000000 1C 90 39 90 02 00 00 00 01 00 00 00 00 00 1C 90 ..9.............
00000010 FF 00 ..
-END DUMP-----------------------------------
recordid = 0x1062, size =18
[AXCEXT]
.minimumCategory = 0x901C (-28644 )
.maximumCategory = 0x9039 (-28615 )
.majorUnitValue = 0x0002 (2 )
.majorUnit = 0x0000 (0 )
.minorUnitValue = 0x0001 (1 )
.minorUnit = 0x0000 (0 )
.baseUnit = 0x0000 (0 )
.crossingPoint = 0x901C (-28644 )
.options = 0x00FF (255 )
.defaultMinimum = true
.defaultMaximum = true
.defaultMajor = true
.defaultMinorUnit = true
.isDate = true
.defaultBase = true
.defaultCross = true
.defaultDateSettings = true
[/AXCEXT]
============================================
Offset 0x113a (4410)
rectype = 0x101e, recsize = 0x1e
-BEGIN DUMP---------------------------------
00000000 02 00 03 01 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 00 00 00 00 23 00 4D 00 2D 00 ........#.M.-.
-END DUMP-----------------------------------
recordid = 0x101e, size =30
[TICK]
.majorTickType = 0x02 (2 )
.minorTickType = 0x00 (0 )
.labelPosition = 0x03 (3 )
.background = 0x01 (1 )
.labelColorRgb = 0x00000000 (0 )
.zero1 = 0x0000 (0 )
.zero2 = 0x0000 (0 )
.options = 0x0023 (35 )
.autoTextColor = true
.autoTextBackground = true
.rotation = 0
.autorotate = true
.tickColor = 0x004D (77 )
.zero3 = 0x002D (45 )
[/TICK]
============================================
Offset 0x115c (4444)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x1160 (4448)
rectype = 0x101d, recsize = 0x12
-BEGIN DUMP---------------------------------
00000000 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 ..
-END DUMP-----------------------------------
recordid = 0x101d, size =18
[AXIS]
.axisType = 0x0001 (1 )
.reserved1 = 0x00000000 (0 )
.reserved2 = 0x00000000 (0 )
.reserved3 = 0x00000000 (0 )
.reserved4 = 0x00000000 (0 )
[/AXIS]
<!-- Comment to avoid forrest bug -->
============================================
Offset 0x1176 (4470)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x117a (4474)
rectype = 0x101f, recsize = 0x2a
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000020 00 00 00 00 00 00 00 00 1F 01 ..........
-END DUMP-----------------------------------
recordid = 0x101f, size =42
[VALUERANGE]
.minimumAxisValue = (0.0 )
.maximumAxisValue = (0.0 )
.majorIncrement = (0.0 )
.minorIncrement = (0.0 )
.categoryAxisCross = (0.0 )
.options = 0x011F (287 )
.automaticMinimum = true
.automaticMaximum = true
.automaticMajor = true
.automaticMinor = true
.automaticCategoryCrossing = true
.logarithmicScale = false
.valuesInReverse = false
.crossCategoryAxisAtMaximum = false
.reserved = true
[/VALUERANGE]
============================================
Offset 0x11a8 (4520)
rectype = 0x101e, recsize = 0x1e
-BEGIN DUMP---------------------------------
00000000 02 00 03 01 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 00 00 00 00 23 00 4D 00 00 00 ........#.M...
-END DUMP-----------------------------------
recordid = 0x101e, size =30
[TICK]
.majorTickType = 0x02 (2 )
.minorTickType = 0x00 (0 )
.labelPosition = 0x03 (3 )
.background = 0x01 (1 )
.labelColorRgb = 0x00000000 (0 )
.zero1 = 0x0000 (0 )
.zero2 = 0x0000 (0 )
.options = 0x0023 (35 )
.autoTextColor = true
.autoTextBackground = true
.rotation = 0
.autorotate = true
.tickColor = 0x004D (77 )
.zero3 = 0x0000 (0 )
[/TICK]
============================================
Offset 0x11ca (4554)
rectype = 0x1021, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 01 00 ..
-END DUMP-----------------------------------
recordid = 0x1021, size =2
[AXISLINEFORMAT]
.axisType = 0x0001 (1 )
[/AXISLINEFORMAT]
============================================
Offset 0x11d0 (4560)
rectype = 0x1007, recsize = 0xc
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 FF FF 09 00 4D 00 ..........M.
-END DUMP-----------------------------------
recordid = 0x1007, size =12
[LINEFORMAT]
.lineColor = 0x00000000 (0 )
.linePattern = 0x0000 (0 )
.weight = 0xFFFF (-1 )
.format = 0x0009 (9 )
.auto = true
.drawTicks = false
.unknown = false
.colourPaletteIndex = 0x004D (77 )
[/LINEFORMAT]
============================================
Offset 0x11e0 (4576)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x11e4 (4580)
rectype = 0x1035, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1035, size =0
[PLOTAREA]
[/PLOTAREA]
============================================
Offset 0x11e8 (4584)
rectype = 0x1032, recsize = 0x4
-BEGIN DUMP---------------------------------
00000000 00 00 03 00 ....
-END DUMP-----------------------------------
recordid = 0x1032, size =4
[FRAME]
.borderType = 0x0000 (0 )
.options = 0x0003 (3 )
.autoSize = true
.autoPosition = true
[/FRAME]
============================================
Offset 0x11f0 (4592)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x11f4 (4596)
rectype = 0x1007, recsize = 0xc
-BEGIN DUMP---------------------------------
00000000 80 80 80 00 00 00 00 00 00 00 17 00 ............
-END DUMP-----------------------------------
recordid = 0x1007, size =12
[LINEFORMAT]
.lineColor = 0x00808080 (8421504 )
.linePattern = 0x0000 (0 )
.weight = 0x0000 (0 )
.format = 0x0000 (0 )
.auto = false
.drawTicks = false
.unknown = false
.colourPaletteIndex = 0x0017 (23 )
[/LINEFORMAT]
============================================
Offset 0x1204 (4612)
rectype = 0x100a, recsize = 0x10
-BEGIN DUMP---------------------------------
00000000 C0 C0 C0 00 00 00 00 00 01 00 00 00 16 00 4F 00 ..............O.
-END DUMP-----------------------------------
recordid = 0x100a, size =16
[AREAFORMAT]
.foregroundColor = 0x00C0C0C0 (12632256 )
.backgroundColor = 0x00000000 (0 )
.pattern = 0x0001 (1 )
.formatFlags = 0x0000 (0 )
.automatic = false
.invert = false
.forecolorIndex = 0x0016 (22 )
.backcolorIndex = 0x004F (79 )
[/AREAFORMAT]
============================================
Offset 0x1218 (4632)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x121c (4636)
rectype = 0x1014, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x1014, size =20
[CHARTFORMAT]
.xPosition = 0
.yPosition = 0
.width = 0
.height = 0
.grBit = 0
[/CHARTFORMAT]
============================================
Offset 0x1234 (4660)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x1238 (4664)
rectype = 0x1017, recsize = 0x6
-BEGIN DUMP---------------------------------
00000000 00 00 96 00 00 00 ......
-END DUMP-----------------------------------
recordid = 0x1017, size =6
[BAR]
.barSpace = 0x0000 (0 )
.categorySpace = 0x0096 (150 )
.formatFlags = 0x0000 (0 )
.horizontal = false
.stacked = false
.displayAsPercentage = false
.shadow = false
[/BAR]
============================================
Offset 0x1242 (4674)
rectype = 0x1022, recsize = 0xa
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 00 00 00 00 0F 00 ..........
-END DUMP-----------------------------------
recordid = 0x1022, size =10
[UNKNOWN RECORD]
.id = 1022
[/UNKNOWN RECORD]
============================================
Offset 0x1250 (4688)
rectype = 0x1015, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 D6 0D 00 00 1E 06 00 00 B5 01 00 00 D5 00 00 00 ................
00000010 03 01 1F 00 ....
-END DUMP-----------------------------------
recordid = 0x1015, size =20
[LEGEND]
.xAxisUpperLeft = 0x00000DD6 (3542 )
.yAxisUpperLeft = 0x0000061E (1566 )
.xSize = 0x000001B5 (437 )
.ySize = 0x000000D5 (213 )
.type = 0x03 (3 )
.spacing = 0x01 (1 )
.options = 0x001F (31 )
.autoPosition = true
.autoSeries = true
.autoXPositioning = true
.autoYPositioning = true
.vertical = true
.dataTable = false
[/LEGEND]
============================================
Offset 0x1268 (4712)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x126c (4716)
rectype = 0x104f, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 05 00 02 00 D6 0D 00 00 1E 06 00 00 00 00 00 00 ................
00000010 00 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x104f, size =20
[UNKNOWN RECORD]
.id = 104f
[/UNKNOWN RECORD]
============================================
Offset 0x1284 (4740)
rectype = 0x1025, recsize = 0x20
-BEGIN DUMP---------------------------------
00000000 02 02 01 00 00 00 00 00 DB FF FF FF C4 FF FF FF ................
00000010 00 00 00 00 00 00 00 00 B1 00 4D 00 70 37 00 00 ..........M.p7..
-END DUMP-----------------------------------
recordid = 0x1025, size =32
[TEXT]
.horizontalAlignment = 0x02 (2 )
.verticalAlignment = 0x02 (2 )
.displayMode = 0x0001 (1 )
.rgbColor = 0x00000000 (0 )
.x = 0xFFFFFFDB (-37 )
.y = 0xFFFFFFC4 (-60 )
.width = 0x00000000 (0 )
.height = 0x00000000 (0 )
.options1 = 0x00B1 (177 )
.autoColor = true
.showKey = false
.showValue = false
.vertical = false
.autoGeneratedText = true
.generated = true
.autoLabelDeleted = false
.autoBackground = true
.rotation = 0
.showCategoryLabelAsPercentage = false
.showValueAsPercentage = false
.showBubbleSizes = false
.showLabel = false
.indexOfColorValue = 0x004D (77 )
.options2 = 0x3770 (14192 )
.dataLabelPlacement = 0
.textRotation = 0x0000 (0 )
[/TEXT]
============================================
Offset 0x12a8 (4776)
rectype = 0x1033, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1033, size =0
[BEGIN]
[/BEGIN]
============================================
Offset 0x12ac (4780)
rectype = 0x104f, recsize = 0x14
-BEGIN DUMP---------------------------------
00000000 02 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000010 00 00 00 00 ....
-END DUMP-----------------------------------
recordid = 0x104f, size =20
[UNKNOWN RECORD]
.id = 104f
[/UNKNOWN RECORD]
============================================
Offset 0x12c4 (4804)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x00 (0 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1d05c81 )
[/AI]
============================================
Offset 0x12d0 (4816)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
<!-- Comment to avoid forrest bug -->
============================================
Offset 0x12d4 (4820)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x12d8 (4824)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x12dc (4828)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
Offset 0x12e0 (4832)
rectype = 0x1034, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0x1034, size =0
[END]
[/END]
============================================
rectype = 0x200, recsize = 0xe
-BEGIN DUMP---------------------------------
00000000 00 00 00 00 1F 00 00 00 00 00 01 00 00 00 ..............
-END DUMP-----------------------------------
recordid = 0x200, size =14
[DIMENSIONS]
.firstrow = 0
.lastrow = 1f
.firstcol = 0
.lastcol = 1
.zero = 0
[/DIMENSIONS]
============================================
rectype = 0x1065, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 02 00 ..
-END DUMP-----------------------------------
recordid = 0x1065, size =2
[SINDEX]
.index = 0x0002 (2 )
[/SINDEX]
============================================
rectype = 0x1065, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 01 00 ..
-END DUMP-----------------------------------
recordid = 0x1065, size =2
[SINDEX]
.index = 0x0001 (1 )
[/SINDEX]
============================================
rectype = 0x1065, recsize = 0x2
-BEGIN DUMP---------------------------------
00000000 03 00 ..
-END DUMP-----------------------------------
recordid = 0x1065, size =2
[SINDEX]
.index = 0x0003 (3 )
[/SINDEX]
============================================
rectype = 0xa, recsize = 0x0
-BEGIN DUMP---------------------------------
**NO RECORD DATA**
-END DUMP-----------------------------------
recordid = 0xa, size =0
[EOF]
[/EOF]
</pre>
<p>
The next section breaks those records down into an easier
to read format:
</p>
<pre class="code">
[UNKNOWN RECORD:ec]
[UNKNOWN RECORD:5d]
[BOF RECORD]
[HEADER]
[FOOTER]
[HCENTER]
[VCENTER]
[PRINTSETUP]
[UNKNOWN RECORD:33]
[FBI]
[FBI]
[PROTECT]
[UNITS]
[CHART]
[BEGIN]
[SCL] // zoom magnification
[PLOTGROWTH] // font scaling
[FRAME] // border around text
[BEGIN] // default line and area format
[LINEFORMAT]
[AREAFORMAT]
[END]
[SERIES] // start of series
[BEGIN]
[AI] // LINK_TYPE_TITLE_OR_TEXT
[AI] // LINK_TYPE_VALUES
[AI] // LINK_TYPE_CATEGORIES
[AI] // ??
[DATAFORMAT] // Formatting applies to series?
[BEGIN] // ??
[UNKNOWN RECORD]
[END]
[SeriesToChartGroup] // Used to support > 1 chart?
[END]
[SHTPROPS] // Some defaults for how chart is displayed.
[DEFAULTTEXT] // Describes the characteristics of the next
// record
[TEXT] // Details of the text that follows in the
// next section
[BEGIN]
[UNKNOWN RECORD] // POS record... looks like I missed this one.
// docs seem to indicate it's better to use
// defaults...
[FONTX] // index to font record.
[AI] // link to text? seems to be linking to nothing
[END]
[DEFAULTTEXT] // contains a category type of 3 which is not
// documented (sigh).
[TEXT] // defines position, color etc for text on chart.
[BEGIN]
[UNKNOWN RECORD] // Another pos record
[FONTX] // font
[AI] // reference type is DIRECT (not sure what this
// means)
[END]
[AXISUSED] // number of axis on the chart.
[AXISPARENT] // axis size and location
[BEGIN] // beginning of axis details
[UNKNOWN RECORD] // Another pos record.
[AXIS] // Category axis
[BEGIN]
[CATSERRANGE] // defines tick marks and other stuff
[AXCEXT] // unit information
[TICK] // tick formating characteristics
[END]
[AXIS] // Value axis
[BEGIN]
[VALUERANGE] // defines tick marks and other stuff
[TICK] // tick formating characteristics
[AXISLINEFORMAT] // major grid line axis format
[LINEFORMAT] // what do the lines look like?
[END]
[PLOTAREA] // marks that the frame following belongs
// to the frame.
[FRAME] // border
[BEGIN]
[LINEFORMAT] // border line
[AREAFORMAT] // border area
[END]
[CHARTFORMAT] // marks a chart group
[BEGIN]
[BAR] // indicates a bar chart
[UNKNOWN RECORD] // apparently this record is ignoreable
[LEGEND] // positioning for the legend
[BEGIN]
[UNKNOWN RECORD] // another position record.
[TEXT] // details of the text that follows
// in the next section
[BEGIN]
[UNKNOWN RECORD] // yet another pos record
[AI] // another link (of type direct)
[END]
[END]
[END]
[END]
[END]
[DIMENSIONS]
[SINDEX]
[SINDEX]
[SINDEX]
[EOF]
</pre>
<p>
Just a quick note on some of the unknown records:
</p>
<ul>
<li>EC: MSODRAWING - A Microsoft drawing record. (Need to
track down where this is documented).</li>
<li>5D: OBJ: Description of a drawing object. (This is going to
be a PITA to implement).</li>
<li>33: Not documented. :-(</li>
<li>105f: Not documented. :-(</li>
<li>104f: POS: Position record (should be able to safely leave this out).</li>
<li>1022: CHARTFORMATLINK: Can be left out.</li>
</ul>
<p>
It is currently suspected that many of those records could be
left out when generating a bar chart from scratch. The way
we will be proceeding with this is to write code that generates
most of these records and then start removing them to see
how this effects the chart in excel.
</p>
<a name="Inserting+the+Chart+into+the+Workbook"></a>
<div class="h3">
<h3>Inserting the Chart into the Workbook</h3>
</div>
<ul>
<li>
Unknown record (sid=00eb) is inserted before the SST
record.
</li>
</ul>
<pre class="code">
============================================
rectype = 0xeb, recsize = 0x5a
-BEGIN DUMP---------------------------------
00000000 0F 00 00 F0 52 00 00 00 00 00 06 F0 18 00 00 00 ....R...........
00000010 01 08 00 00 02 00 00 00 02 00 00 00 01 00 00 00 ................
00000020 01 00 00 00 03 00 00 00 33 00 0B F0 12 00 00 00 ........3.......
00000030 BF 00 08 00 08 00 81 01 09 00 00 08 C0 01 40 00 ..............@.
00000040 00 08 40 00 1E F1 10 00 00 00 0D 00 00 08 0C 00 ..@.............
00000050 00 08 17 00 00 08 F7 00 00 10 ..........
-END DUMP-----------------------------------
recordid = 0xeb, size =90
[UNKNOWN RECORD:eb]
.id = eb
[/UNKNOWN RECORD]
============================================
</pre>
<ul>
<li>
Any extra font records are inserted as needed
</li>
<li>
Chart records inserted after DBCell records.
</li>
</ul>
<div id="authors" align="right">by Glen Stampoultzis</div>
</div>
</div>
</div>
</td>
<!--================= end Content ==================-->
</tr>
</tbody>
</table>
<!--================= end Main ==================-->
<!--================= start Footer ==================-->
<div id="footer">
<table summary="footer" cellspacing="0" cellpadding="4" width="100%" border="0">
<tbody>
<tr>
<!--================= start Copyright ==================-->
<td colspan="2">
<div align="center">
<div class="copyright">
Copyright © 2002-2014 The Apache Software Foundation. All rights reserved.<br>
Apache POI, POI, Apache, the Apache feather logo, and the Apache
POI project logo are trademarks of The Apache Software Foundation.
</div>
</div>
</td>
<!--================= end Copyright ==================-->
</tr>
<tr>
<td align="left">
<!--================= start Host ==================-->
<!--================= end Host ==================--></td><td align="right">
<!--================= start Credits ==================-->
<div align="right">
<div class="credit"></div>
</div>
<!--================= end Credits ==================-->
</td>
</tr>
</tbody>
</table>
</div>
<!--================= end Footer ==================-->
</body>
</html>
| RyoSaeba69/Bio-info | mylib/poi-3.11/docs/spreadsheet/chart.html | HTML | apache-2.0 | 63,700 |
import matplotlib.pyplot as plt
from numpy import *
from time import sleep
def loadDataSet(fileName):
dataMat = []; labelMat = []
fr = open(fileName)
for line in fr.readlines():
lineArr = line.strip().split('\t')
dataMat.append([float(lineArr[0]), float(lineArr[1])])
labelMat.append(float(lineArr[2]))
return dataMat,labelMat
def selectJrand(i,m):
j=i #we want to select any J not equal to i
while (j==i):
j = int(random.uniform(0,m))
return j
def clipAlpha(aj,H,L):
if aj > H:
aj = H
if L > aj:
aj = L
return aj
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
b = 0; m,n = shape(dataMatrix)
alphas = mat(zeros((m,1)))
iter = 0
while (iter < maxIter):
alphaPairsChanged = 0
for i in range(m):
fXi = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[i,:].T)) + b
Ei = fXi - float(labelMat[i])#if checks if an example violates KKT conditions
if ((labelMat[i]*Ei < -toler) and (alphas[i] < C)) or ((labelMat[i]*Ei > toler) and (alphas[i] > 0)):
j = selectJrand(i,m)
fXj = float(multiply(alphas,labelMat).T*(dataMatrix*dataMatrix[j,:].T)) + b
Ej = fXj - float(labelMat[j])
alphaIold = alphas[i].copy(); alphaJold = alphas[j].copy();
if (labelMat[i] != labelMat[j]):
L = max(0, alphas[j] - alphas[i])
H = min(C, C + alphas[j] - alphas[i])
else:
L = max(0, alphas[j] + alphas[i] - C)
H = min(C, alphas[j] + alphas[i])
# if L==H: print "L==H"; continue
eta = 2.0 * dataMatrix[i,:]*dataMatrix[j,:].T - dataMatrix[i,:]*dataMatrix[i,:].T - dataMatrix[j,:]*dataMatrix[j,:].T
if eta >= 0: print "eta>=0"; continue
alphas[j] -= labelMat[j]*(Ei - Ej)/eta
alphas[j] = clipAlpha(alphas[j],H,L)
# if (abs(alphas[j] - alphaJold) < 0.00001): print "j not moving enough"; continue
alphas[i] += labelMat[j]*labelMat[i]*(alphaJold - alphas[j])#update i by the same amount as j
#the update is in the oppostie direction
b1 = b - Ei- labelMat[i]*(alphas[i]-alphaIold)*dataMatrix[i,:]*dataMatrix[i,:].T - labelMat[j]*(alphas[j]-alphaJold)*dataMatrix[i,:]*dataMatrix[j,:].T
b2 = b - Ej- labelMat[i]*(alphas[i]-alphaIold)*dataMatrix[i,:]*dataMatrix[j,:].T - labelMat[j]*(alphas[j]-alphaJold)*dataMatrix[j,:]*dataMatrix[j,:].T
if (0 < alphas[i]) and (C > alphas[i]): b = b1
elif (0 < alphas[j]) and (C > alphas[j]): b = b2
else: b = (b1 + b2)/2.0
alphaPairsChanged += 1
# print "iter: %d i:%d, pairs changed %d" % (iter,i,alphaPairsChanged)
if (alphaPairsChanged == 0): iter += 1
else: iter = 0
# print "iteration number: %d" % iter
return b,alphas
def matplot(dataMat,lableMat):
xcord1 = []; ycord1 = []
xcord2 = []; ycord2 = []
xcord3 = []; ycord3 = []
for i in range(100):
if lableMat[i]==1:
xcord1.append(dataMat[i][0])
ycord1.append(dataMat[i][1])
else:
xcord2.append(dataMat[i][0])
ycord2.append(dataMat[i][1])
b,alphas=smoSimple(dataMat,labelMat,0.6,0.001,40)
for j in range(100):
if alphas[j]>0:
xcord3.append(dataMat[j][0])
ycord3.append(dataMat[j][1])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
ax.scatter(xcord2, ycord2, s=30, c='green')
ax.scatter(xcord3, ycord3, s=80, c='blue')
ax.plot()
plt.xlabel('X1'); plt.ylabel('X2');
plt.show()
if __name__=='__main__':
dataMat,labelMat=loadDataSet('/Users/hakuri/Desktop/testSet.txt')
# b,alphas=smoSimple(dataMat,labelMat,0.6,0.001,40)
# print b,alphas[alphas>0]
matplot(dataMat,labelMat) | X-Brain/MachineLearning | SMO/src/SMO.py | Python | apache-2.0 | 4,227 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.cassandra.db;
import java.io.IOError;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.cassandra.config.*;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
/**
* It represents a Keyspace.
*/
public class Table
{
public static final String SYSTEM_TABLE = "system";
private static final Logger logger = LoggerFactory.getLogger(Table.class);
/**
* accesses to CFS.memtable should acquire this for thread safety.
* Table.maybeSwitchMemtable should aquire the writeLock; see that method for the full explanation.
*
* (Enabling fairness in the RRWL is observed to decrease throughput, so we leave it off.)
*/
static final ReentrantReadWriteLock switchLock = new ReentrantReadWriteLock();
// It is possible to call Table.open without a running daemon, so it makes sense to ensure
// proper directories here as well as in CassandraDaemon.
static
{
if (!StorageService.instance.isClientMode())
{
try
{
DatabaseDescriptor.createAllDirectories();
}
catch (IOException ex)
{
throw new IOError(ex);
}
}
}
/* Table name. */
public final String name;
/* ColumnFamilyStore per column family */
private final Map<Integer, ColumnFamilyStore> columnFamilyStores = new ConcurrentHashMap<Integer, ColumnFamilyStore>();
private final Object[] indexLocks;
private volatile AbstractReplicationStrategy replicationStrategy;
public static Table open(String table)
{
return open(table, Schema.instance);
}
public static Table open(String table, Schema schema)
{
Table tableInstance = schema.getTableInstance(table);
if (tableInstance == null)
{
// instantiate the Table. we could use putIfAbsent but it's important to making sure it is only done once
// per keyspace, so we synchronize and re-check before doing it.
synchronized (Table.class)
{
tableInstance = schema.getTableInstance(table);
if (tableInstance == null)
{
// open and store the table
tableInstance = new Table(table);
schema.storeTableInstance(tableInstance);
// table has to be constructed and in the cache before cacheRow can be called
for (ColumnFamilyStore cfs : tableInstance.getColumnFamilyStores())
cfs.initRowCache();
}
}
}
return tableInstance;
}
public static Table clear(String table) throws IOException
{
return clear(table, Schema.instance);
}
public static Table clear(String table, Schema schema) throws IOException
{
synchronized (Table.class)
{
Table t = schema.removeTableInstance(table);
if (t != null)
{
for (ColumnFamilyStore cfs : t.getColumnFamilyStores())
t.unloadCf(cfs);
}
return t;
}
}
public Collection<ColumnFamilyStore> getColumnFamilyStores()
{
return Collections.unmodifiableCollection(columnFamilyStores.values());
}
public ColumnFamilyStore getColumnFamilyStore(String cfName)
{
Integer id = Schema.instance.getId(name, cfName);
if (id == null)
throw new IllegalArgumentException(String.format("Unknown table/cf pair (%s.%s)", name, cfName));
return getColumnFamilyStore(id);
}
public ColumnFamilyStore getColumnFamilyStore(Integer id)
{
ColumnFamilyStore cfs = columnFamilyStores.get(id);
if (cfs == null)
throw new IllegalArgumentException("Unknown CF " + id);
return cfs;
}
/**
* Do a cleanup of keys that do not belong locally.
*/
public void forceCleanup(NodeId.OneShotRenewer renewer) throws IOException, ExecutionException, InterruptedException
{
if (name.equals(SYSTEM_TABLE))
throw new UnsupportedOperationException("Cleanup of the system table is neither necessary nor wise");
// Sort the column families in order of SSTable size, so cleanup of smaller CFs
// can free up space for larger ones
List<ColumnFamilyStore> sortedColumnFamilies = new ArrayList<ColumnFamilyStore>(columnFamilyStores.values());
Collections.sort(sortedColumnFamilies, new Comparator<ColumnFamilyStore>()
{
// Compare first on size and, if equal, sort by name (arbitrary & deterministic).
@Override
public int compare(ColumnFamilyStore cf1, ColumnFamilyStore cf2)
{
long diff = (cf1.getTotalDiskSpaceUsed() - cf2.getTotalDiskSpaceUsed());
if (diff > 0)
return 1;
if (diff < 0)
return -1;
return cf1.columnFamily.compareTo(cf2.columnFamily);
}
});
// Cleanup in sorted order to free up space for the larger ones
for (ColumnFamilyStore cfs : sortedColumnFamilies)
cfs.forceCleanup(renewer);
}
/**
* Take a snapshot of the entire set of column families with a given timestamp
*
* @param snapshotName the tag associated with the name of the snapshot. This value may not be null
*/
public void snapshot(String snapshotName)
{
assert snapshotName != null;
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
cfStore.snapshot(snapshotName);
}
/**
* @param clientSuppliedName may be null.
* @return
*/
public static String getTimestampedSnapshotName(String clientSuppliedName)
{
String snapshotName = Long.toString(System.currentTimeMillis());
if (clientSuppliedName != null && !clientSuppliedName.equals(""))
{
snapshotName = snapshotName + "-" + clientSuppliedName;
}
return snapshotName;
}
/**
* Check whether snapshots already exists for a given name.
*
* @param snapshotName the user supplied snapshot name
* @return true if the snapshot exists
*/
public boolean snapshotExists(String snapshotName)
{
assert snapshotName != null;
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
{
if (cfStore.snapshotExists(snapshotName))
return true;
}
return false;
}
/**
* Clear all the snapshots for a given table.
*
* @param snapshotName the user supplied snapshot name. It empty or null,
* all the snapshots will be cleaned
*/
public void clearSnapshot(String snapshotName) throws IOException
{
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
{
cfStore.clearSnapshot(snapshotName);
}
}
/**
* @return A list of open SSTableReaders
*/
public List<SSTableReader> getAllSSTables()
{
List<SSTableReader> list = new ArrayList<SSTableReader>();
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
list.addAll(cfStore.getSSTables());
return list;
}
private Table(String table)
{
name = table;
KSMetaData ksm = Schema.instance.getKSMetaData(table);
assert ksm != null : "Unknown keyspace " + table;
try
{
createReplicationStrategy(ksm);
}
catch (ConfigurationException e)
{
throw new RuntimeException(e);
}
indexLocks = new Object[DatabaseDescriptor.getConcurrentWriters() * 128];
for (int i = 0; i < indexLocks.length; i++)
indexLocks[i] = new Object();
for (CFMetaData cfm : new ArrayList<CFMetaData>(Schema.instance.getTableDefinition(table).cfMetaData().values()))
{
logger.debug("Initializing {}.{}", name, cfm.cfName);
initCf(cfm.cfId, cfm.cfName);
}
}
public void createReplicationStrategy(KSMetaData ksm) throws ConfigurationException
{
if (replicationStrategy != null)
StorageService.instance.getTokenMetadata().unregister(replicationStrategy);
replicationStrategy = AbstractReplicationStrategy.createReplicationStrategy(ksm.name,
ksm.strategyClass,
StorageService.instance.getTokenMetadata(),
DatabaseDescriptor.getEndpointSnitch(),
ksm.strategyOptions);
}
// best invoked on the compaction mananger.
public void dropCf(Integer cfId) throws IOException
{
assert columnFamilyStores.containsKey(cfId);
ColumnFamilyStore cfs = columnFamilyStores.remove(cfId);
if (cfs == null)
return;
unloadCf(cfs);
}
// disassociate a cfs from this table instance.
private void unloadCf(ColumnFamilyStore cfs) throws IOException
{
try
{
cfs.forceBlockingFlush();
}
catch (ExecutionException e)
{
throw new IOException(e);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
cfs.invalidate();
}
/** adds a cf to internal structures, ends up creating disk files). */
public void initCf(Integer cfId, String cfName)
{
assert !columnFamilyStores.containsKey(cfId) : String.format("tried to init %s as %s, but already used by %s",
cfName, cfId, columnFamilyStores.get(cfId));
columnFamilyStores.put(cfId, ColumnFamilyStore.createColumnFamilyStore(this, cfName));
}
public Row getRow(QueryFilter filter) throws IOException
{
ColumnFamilyStore cfStore = getColumnFamilyStore(filter.getColumnFamilyName());
ColumnFamily columnFamily = cfStore.getColumnFamily(filter, ArrayBackedSortedColumns.factory());
return new Row(filter.key, columnFamily);
}
public void apply(RowMutation mutation, boolean writeCommitLog) throws IOException
{
apply(mutation, writeCommitLog, true);
}
/**
* This method adds the row to the Commit Log associated with this table.
* Once this happens the data associated with the individual column families
* is also written to the column family store's memtable.
*/
public void apply(RowMutation mutation, boolean writeCommitLog, boolean updateIndexes) throws IOException
{
if (logger.isDebugEnabled())
logger.debug("applying mutation of row {}", ByteBufferUtil.bytesToHex(mutation.key()));
// write the mutation to the commitlog and memtables
switchLock.readLock().lock();
try
{
if (writeCommitLog)
CommitLog.instance.add(mutation);
//We consider the operation applied now
//WL TODO Perhaps we should move this into ColumnFamilyStore.apply and do it individually for all CFs?
//Determine if this is part of a transaction, if it isn't, update AppliedOps, if it is, that's done in the Coordinator/Cohort
boolean inTransaction;
if (mutation.getColumnFamilies().size() == 0 || mutation.getColumnFamilies().iterator().next().columns.size() == 0) {
inTransaction = false;
} else {
IColumn firstColumn = mutation.getColumnFamilies().iterator().next().columns.iterator().next();
if (firstColumn instanceof SuperColumn) {
if (firstColumn.getSubColumns().size() == 0) {
inTransaction = false;
} else {
inTransaction = firstColumn.getSubColumns().iterator().next().transactionCoordinatorKey() != null;
}
} else {
inTransaction = firstColumn.transactionCoordinatorKey() != null;
}
}
if (!inTransaction) {
AppliedOperations.addAppliedOp(mutation.key(), mutation.extractTimestamp());
}
//Set the earliest_valid_time for all columns in this update
//if the update originates from this node, it's earliest valid time == timestamp
//otherwise it's the current logical time
long earliestValidTime;
if (ShortNodeId.getLocalDC() == VersionUtil.extractDatacenter(mutation.extractTimestamp())) {
earliestValidTime = mutation.extractTimestamp();
} else {
earliestValidTime = LamportClock.getVersion();
}
for (ColumnFamily cf : mutation.getColumnFamilies()) {
for (IColumn column : cf.columns) {
if (column instanceof Column) {
column.setEarliestValidTime(earliestValidTime);
} else {
assert column instanceof SuperColumn;
for (IColumn subcolumn : column.getSubColumns()) {
assert subcolumn instanceof Column;
subcolumn.setEarliestValidTime(earliestValidTime);
}
}
}
}
DecoratedKey<?> key = StorageService.getPartitioner().decorateKey(mutation.key());
for (ColumnFamily cf : mutation.getColumnFamilies())
{
ColumnFamilyStore cfs = columnFamilyStores.get(cf.id());
if (cfs == null)
{
logger.error("Attempting to mutate non-existant column family " + cf.id());
continue;
}
SortedSet<ByteBuffer> mutatedIndexedColumns = null;
if (updateIndexes)
{
for (ByteBuffer column : cfs.indexManager.getIndexedColumns())
{
if (cf.getColumnNames().contains(column) || cf.isMarkedForDelete())
{
if (mutatedIndexedColumns == null)
mutatedIndexedColumns = new TreeSet<ByteBuffer>();
mutatedIndexedColumns.add(column);
if (logger.isDebugEnabled())
{
// can't actually use validator to print value here, because we overload value
// for deletion timestamp as well (which may not be a well-formed value for the column type)
ByteBuffer value = cf.getColumn(column) == null ? null : cf.getColumn(column).value(); // may be null on row-level deletion
logger.debug(String.format("mutating indexed column %s value %s",
cf.getComparator().getString(column),
value == null ? "null" : ByteBufferUtil.bytesToHex(value)));
}
}
}
}
// Sharding the lock is insufficient to avoid contention when there is a "hot" row, e.g., for
// hint writes when a node is down (keyed by target IP). So it is worth special-casing the
// no-index case to avoid the synchronization.
if (mutatedIndexedColumns == null)
{
cfs.apply(key, cf);
continue;
}
// else mutatedIndexedColumns != null
synchronized (indexLockFor(mutation.key()))
{
// with the raw data CF, we can just apply every update in any order and let
// read-time resolution throw out obsolete versions, thus avoiding read-before-write.
// but for indexed data we need to make sure that we're not creating index entries
// for obsolete writes.
ColumnFamily oldIndexedColumns = readCurrentIndexedColumns(key, cfs, mutatedIndexedColumns);
logger.debug("Pre-mutation index row is {}", oldIndexedColumns);
ignoreObsoleteMutations(cf, mutatedIndexedColumns, oldIndexedColumns);
cfs.apply(key, cf);
// ignore full index memtables -- we flush those when the "master" one is full
cfs.indexManager.applyIndexUpdates(mutation.key(), cf, mutatedIndexedColumns, oldIndexedColumns);
}
}
}
finally
{
switchLock.readLock().unlock();
}
}
private static void ignoreObsoleteMutations(ColumnFamily cf, SortedSet<ByteBuffer> mutatedIndexedColumns, ColumnFamily oldIndexedColumns)
{
// DO NOT modify the cf object here, it can race w/ the CL write (see https://issues.apache.org/jira/browse/CASSANDRA-2604)
if (oldIndexedColumns == null)
return;
for (Iterator<ByteBuffer> iter = mutatedIndexedColumns.iterator(); iter.hasNext(); )
{
ByteBuffer name = iter.next();
IColumn newColumn = cf.getColumn(name); // null == row delete or it wouldn't be marked Mutated
if (newColumn != null && cf.isMarkedForDelete())
{
// row is marked for delete, but column was also updated. if column is timestamped less than
// the row tombstone, treat it as if it didn't exist. Otherwise we don't care about row
// tombstone for the purpose of the index update and we can proceed as usual.
if (newColumn.timestamp() <= cf.getMarkedForDeleteAt())
{
// don't remove from the cf object; that can race w/ CommitLog write. Leaving it is harmless.
newColumn = null;
}
}
IColumn oldColumn = oldIndexedColumns.getColumn(name);
// deletions are irrelevant to the index unless we're changing state from live -> deleted, i.e.,
// just updating w/ a newer tombstone doesn't matter
boolean bothDeleted = (newColumn == null || newColumn.isMarkedForDelete())
&& (oldColumn == null || oldColumn.isMarkedForDelete());
// obsolete means either the row or the column timestamp we're applying is older than existing data
boolean obsoleteRowTombstone = newColumn == null && oldColumn != null && cf.getMarkedForDeleteAt() < oldColumn.timestamp();
boolean obsoleteColumn = newColumn != null && (newColumn.timestamp() <= oldIndexedColumns.getMarkedForDeleteAt()
|| (oldColumn != null && oldColumn.reconcile(newColumn) == oldColumn));
if (bothDeleted || obsoleteRowTombstone || obsoleteColumn)
{
if (logger.isDebugEnabled())
logger.debug("skipping index update for obsolete mutation of " + cf.getComparator().getString(name));
iter.remove();
oldIndexedColumns.remove(name);
}
}
}
private static ColumnFamily readCurrentIndexedColumns(DecoratedKey<?> key, ColumnFamilyStore cfs, SortedSet<ByteBuffer> mutatedIndexedColumns)
{
QueryFilter filter = QueryFilter.getNamesFilter(key, new QueryPath(cfs.getColumnFamilyName()), mutatedIndexedColumns);
return cfs.getColumnFamily(filter);
}
public AbstractReplicationStrategy getReplicationStrategy()
{
return replicationStrategy;
}
public static void indexRow(DecoratedKey<?> key, ColumnFamilyStore cfs, SortedSet<ByteBuffer> indexedColumns)
{
if (logger.isDebugEnabled())
logger.debug("Indexing row {} ", cfs.metadata.getKeyValidator().getString(key.key));
switchLock.readLock().lock();
try
{
synchronized (cfs.table.indexLockFor(key.key))
{
ColumnFamily cf = readCurrentIndexedColumns(key, cfs, indexedColumns);
if (cf != null)
try
{
cfs.indexManager.applyIndexUpdates(key.key, cf, cf.getColumnNames(), null);
}
catch (IOException e)
{
throw new IOError(e);
}
}
}
finally
{
switchLock.readLock().unlock();
}
}
private Object indexLockFor(ByteBuffer key)
{
return indexLocks[Math.abs(key.hashCode() % indexLocks.length)];
}
public List<Future<?>> flush() throws IOException
{
List<Future<?>> futures = new ArrayList<Future<?>>();
for (Integer cfId : columnFamilyStores.keySet())
{
Future<?> future = columnFamilyStores.get(cfId).forceFlush();
if (future != null)
futures.add(future);
}
return futures;
}
public static Iterable<Table> all()
{
Function<String, Table> transformer = new Function<String, Table>()
{
@Override
public Table apply(String tableName)
{
return Table.open(tableName);
}
};
return Iterables.transform(Schema.instance.getTables(), transformer);
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(name='" + name + "')";
}
}
| wlloyd/eiger | src/java/org/apache/cassandra/db/Table.java | Java | apache-2.0 | 23,606 |
import React, { Component } from "react";
import {
Container,
Header,
Left,
Button,
Body,
Title,
Icon,
Right,
Content,
ActionSheet,
Text
} from "native-base";
var BUTTONS = ["Option 0", "Option 1", "Option 2", "Delete", "Cancel"];
var DESTRUCTIVE_INDEX = 3;
var CANCEL_INDEX = 4;
export default class ActionSheetNB extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("DrawerOpen")}
>
<Icon name="ios-menu" />
</Button>
</Left>
<Body>
<Title>ActionSheet</Title>
</Body>
<Right />
</Header>
<Content padder>
<Button
onPress={() =>
ActionSheet.show(
{
options: BUTTONS,
cancelButtonIndex: CANCEL_INDEX,
destructiveButtonIndex: DESTRUCTIVE_INDEX,
title: "Options"
},
buttonIndex => {
this.setState({ clicked: BUTTONS[buttonIndex] });
}
)}
>
<Text>Actionsheet</Text>
</Button>
</Content>
</Container>
);
}
}
| auto-flourish/ios | js/components/actionsheet/index.ios.js | JavaScript | apache-2.0 | 1,406 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/sso-oidc/SSOOIDC_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SSOOIDC
{
namespace Model
{
/**
* <p>Indicates that a request contains an invalid grant. This can occur if a
* client makes a <a>CreateToken</a> request with an invalid grant
* type.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/sso-oidc-2019-06-10/InvalidGrantException">AWS
* API Reference</a></p>
*/
class AWS_SSOOIDC_API InvalidGrantException
{
public:
InvalidGrantException();
InvalidGrantException(Aws::Utils::Json::JsonView jsonValue);
InvalidGrantException& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
inline const Aws::String& GetError() const{ return m_error; }
inline bool ErrorHasBeenSet() const { return m_errorHasBeenSet; }
inline void SetError(const Aws::String& value) { m_errorHasBeenSet = true; m_error = value; }
inline void SetError(Aws::String&& value) { m_errorHasBeenSet = true; m_error = std::move(value); }
inline void SetError(const char* value) { m_errorHasBeenSet = true; m_error.assign(value); }
inline InvalidGrantException& WithError(const Aws::String& value) { SetError(value); return *this;}
inline InvalidGrantException& WithError(Aws::String&& value) { SetError(std::move(value)); return *this;}
inline InvalidGrantException& WithError(const char* value) { SetError(value); return *this;}
inline const Aws::String& GetError_description() const{ return m_error_description; }
inline bool Error_descriptionHasBeenSet() const { return m_error_descriptionHasBeenSet; }
inline void SetError_description(const Aws::String& value) { m_error_descriptionHasBeenSet = true; m_error_description = value; }
inline void SetError_description(Aws::String&& value) { m_error_descriptionHasBeenSet = true; m_error_description = std::move(value); }
inline void SetError_description(const char* value) { m_error_descriptionHasBeenSet = true; m_error_description.assign(value); }
inline InvalidGrantException& WithError_description(const Aws::String& value) { SetError_description(value); return *this;}
inline InvalidGrantException& WithError_description(Aws::String&& value) { SetError_description(std::move(value)); return *this;}
inline InvalidGrantException& WithError_description(const char* value) { SetError_description(value); return *this;}
private:
Aws::String m_error;
bool m_errorHasBeenSet;
Aws::String m_error_description;
bool m_error_descriptionHasBeenSet;
};
} // namespace Model
} // namespace SSOOIDC
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-sso-oidc/include/aws/sso-oidc/model/InvalidGrantException.h | C | apache-2.0 | 3,050 |
/*
* Copyright 2006-2016 the original author or authors.
*
* 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 com.consol.citrus.ssh.client;
import com.consol.citrus.endpoint.AbstractEndpointBuilder;
import com.consol.citrus.message.MessageCorrelator;
import com.consol.citrus.ssh.message.SshMessageConverter;
/**
* @author Christoph Deppisch
* @since 2.5
*/
public class SshClientBuilder extends AbstractEndpointBuilder<SshClient> {
/** Endpoint target */
private SshClient endpoint = new SshClient();
@Override
protected SshClient getEndpoint() {
return endpoint;
}
/**
* Sets the host property.
* @param host
* @return
*/
public SshClientBuilder host(String host) {
endpoint.getEndpointConfiguration().setHost(host);
return this;
}
/**
* Sets the port property.
* @param port
* @return
*/
public SshClientBuilder port(int port) {
endpoint.getEndpointConfiguration().setPort(port);
return this;
}
/**
* Sets the user property.
* @param user
* @return
*/
public SshClientBuilder user(String user) {
endpoint.getEndpointConfiguration().setUser(user);
return this;
}
/**
* Sets the client password.
* @param password
* @return
*/
public SshClientBuilder password(String password) {
endpoint.getEndpointConfiguration().setPassword(password);
return this;
}
/**
* Sets the privateKeyPath property.
* @param privateKeyPath
* @return
*/
public SshClientBuilder privateKeyPath(String privateKeyPath) {
endpoint.getEndpointConfiguration().setPrivateKeyPath(privateKeyPath);
return this;
}
/**
* Sets the privateKeyPassword property.
* @param privateKeyPassword
* @return
*/
public SshClientBuilder privateKeyPassword(String privateKeyPassword) {
endpoint.getEndpointConfiguration().setPrivateKeyPassword(privateKeyPassword);
return this;
}
/**
* Sets the strictHostChecking property.
* @param strictHostChecking
* @return
*/
public SshClientBuilder strictHostChecking(boolean strictHostChecking) {
endpoint.getEndpointConfiguration().setStrictHostChecking(strictHostChecking);
return this;
}
/**
* Sets the knownHosts property.
* @param knownHosts
* @return
*/
public SshClientBuilder knownHosts(String knownHosts) {
endpoint.getEndpointConfiguration().setKnownHosts(knownHosts);
return this;
}
/**
* Sets the commandTimeout property.
* @param commandTimeout
* @return
*/
public SshClientBuilder commandTimeout(long commandTimeout) {
endpoint.getEndpointConfiguration().setCommandTimeout(commandTimeout);
return this;
}
/**
* Sets the connectionTimeout property.
* @param connectionTimeout
* @return
*/
public SshClientBuilder connectionTimeout(int connectionTimeout) {
endpoint.getEndpointConfiguration().setConnectionTimeout(connectionTimeout);
return this;
}
/**
* Sets the message converter.
* @param messageConverter
* @return
*/
public SshClientBuilder messageConverter(SshMessageConverter messageConverter) {
endpoint.getEndpointConfiguration().setMessageConverter(messageConverter);
return this;
}
/**
* Sets the message correlator.
* @param correlator
* @return
*/
public SshClientBuilder correlator(MessageCorrelator correlator) {
endpoint.getEndpointConfiguration().setCorrelator(correlator);
return this;
}
/**
* Sets the polling interval.
* @param pollingInterval
* @return
*/
public SshClientBuilder pollingInterval(int pollingInterval) {
endpoint.getEndpointConfiguration().setPollingInterval(pollingInterval);
return this;
}
/**
* Sets the default timeout.
* @param timeout
* @return
*/
public SshClientBuilder timeout(long timeout) {
endpoint.getEndpointConfiguration().setTimeout(timeout);
return this;
}
}
| hmmlopez/citrus | modules/citrus-ssh/src/main/java/com/consol/citrus/ssh/client/SshClientBuilder.java | Java | apache-2.0 | 4,757 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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 org.keycloak.testsuite.arquillian;
import org.jboss.arquillian.container.spi.client.deployment.DeploymentDescription;
import org.jboss.arquillian.container.spi.client.deployment.TargetDescription;
import org.jboss.arquillian.container.test.impl.client.deployment.AnnotationDeploymentScenarioGenerator;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.logging.Logger;
import java.util.List;
import static org.keycloak.testsuite.arquillian.AppServerTestEnricher.getAppServerQualifier;
/**
* Changes target container for all Arquillian deployments based on value of
* @AppServerContainer.
*
* @author tkyjovsk
*/
public class DeploymentTargetModifier extends AnnotationDeploymentScenarioGenerator {
// Will be replaced in runtime by real auth-server-container
public static final String AUTH_SERVER_CURRENT = "auth-server-current";
protected final Logger log = Logger.getLogger(this.getClass());
@Override
public List<DeploymentDescription> generate(TestClass testClass) {
List<DeploymentDescription> deployments = super.generate(testClass);
checkAuthServerTestDeployment(deployments, testClass);
String appServerQualifier = getAppServerQualifier(
testClass.getJavaClass());
if (appServerQualifier != null && !appServerQualifier.isEmpty()) {
for (DeploymentDescription deployment : deployments) {
if (deployment.getTarget() == null || !deployment.getTarget().getName().startsWith(appServerQualifier)) {
log.debug("Setting target container for " + deployment.getName() + ": " + appServerQualifier);
deployment.setTarget(new TargetDescription(appServerQualifier));
}
}
}
return deployments;
}
private void checkAuthServerTestDeployment(List<DeploymentDescription> descriptions, TestClass testClass) {
for (DeploymentDescription deployment : descriptions) {
if (deployment.getTarget() != null) {
String containerQualifier = deployment.getTarget().getName();
if (AUTH_SERVER_CURRENT.equals(containerQualifier)) {
String authServerQualifier = AuthServerTestEnricher.AUTH_SERVER_CONTAINER;
log.infof("Setting target container for deployment %s.%s: %s", testClass.getName(), deployment.getName(), authServerQualifier);
deployment.setTarget(new TargetDescription(authServerQualifier));
}
}
}
}
}
| almighty/keycloak | testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/DeploymentTargetModifier.java | Java | apache-2.0 | 3,243 |
#!/bin/bash
# Copyright 2016 The Kubernetes Authors All rights reserved.
#
# 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.
K8S_ORG_ROOT=${GOPATH}/src/k8s.io
MINIKUBE_ROOT=${K8S_ORG_ROOT}/minikube
KUBE_ROOT=${K8S_ORG_ROOT}/kubernetes
KUBE_VERSION=$(python ${MINIKUBE_ROOT}/hack/get_k8s_version.py --k8s-version-only 2>&1)
source ${MINIKUBE_ROOT}/hack/godeps/utils.sh
godep::ensure_godep_version v79
# We can't 'go get kubernetes' so this hack is here
mkdir -p ${K8S_ORG_ROOT}
if [ ! -d "${KUBE_ROOT}" ]; then
pushd ${K8S_ORG_ROOT} >/dev/null
git clone https://github.com/kubernetes/kubernetes.git
popd >/dev/null
fi
pushd ${KUBE_ROOT} >/dev/null
git checkout ${KUBE_VERSION}
./hack/godep-restore.sh
popd >/dev/null
godep::sync_staging
pushd ${MINIKUBE_ROOT} >/dev/null
godep restore ./...
popd >/dev/null
| abbytiz/minikube | hack/godeps/godep-restore.sh | Shell | apache-2.0 | 1,324 |
package org.tigris.scarab.om;
/* ================================================================
* Copyright (c) 2000-2002 CollabNet. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement: "This product includes
* software developed by Collab.Net <http://www.Collab.Net/>."
* Alternately, this acknowlegement may appear in the software itself, if
* and wherever such third-party acknowlegements normally appear.
*
* 4. The hosted project names must not be used to endorse or promote
* products derived from this software without prior written
* permission. For written permission, please contact [email protected].
*
* 5. Products derived from this software may not use the "Tigris" or
* "Scarab" names nor may "Tigris" or "Scarab" appear in their names without
* prior written permission of Collab.Net.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of Collab.Net.
*/
import java.util.Date;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import org.apache.torque.TorqueException;
import org.apache.torque.util.Criteria;
import org.apache.torque.om.NumberKey;
import org.apache.fulcrum.template.TemplateContext;
import org.apache.fulcrum.template.DefaultTemplateContext;
import org.apache.fulcrum.template.TemplateEmail;
import org.apache.turbine.Turbine;
import org.apache.torque.om.Persistent;
import org.tigris.scarab.util.ScarabException;
import org.tigris.scarab.util.Email;
import org.tigris.scarab.services.cache.ScarabCache;
/**
* The skeleton for this class was autogenerated by Torque on:
*
* [Wed Feb 28 16:36:26 PST 2001]
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*/
public class Transaction
extends BaseTransaction
implements Persistent
{
private static final String GET_ACTIVITY_LIST =
"getActivityList";
/**
* The Attachment associated with this Transaction
// FIXME: (JSS) is this needed?
*/
private Attachment aAttachment = null;
/**
* Populates a new transaction object.
*/
public void create(NumberKey typeId, ScarabUser user, Attachment attachment)
throws Exception
{
if (attachment != null && attachment.getAttachmentId() == null)
{
String mesg =
"Attachment must be saved before starting transaction";
throw new ScarabException(mesg);
}
setTypeId(typeId);
setCreatedBy(user.getUserId());
setCreatedDate(new Date());
if (attachment != null)
{
setAttachment(attachment);
}
save();
}
/**
* Returns a list of Activity objects associated with this Transaction.
*/
public List getActivityList() throws Exception
{
List result = null;
Object obj = ScarabCache.get(this, GET_ACTIVITY_LIST);
if ( obj == null )
{
Criteria crit = new Criteria()
.add(ActivityPeer.TRANSACTION_ID, getTransactionId());
result = ActivityPeer.doSelect(crit);
ScarabCache.put(result, this, GET_ACTIVITY_LIST);
}
else
{
result = (List)obj;
}
return result;
}
/**
Sends email to the users associated with the issue.
That is associated with this transaction.
If no subject and template specified, assume modify issue action.
throws Exception
*/
public boolean sendEmail( TemplateContext context, Issue issue,
String subject, String template )
throws Exception
{
if ( context == null )
{
context = new DefaultTemplateContext();
}
// add data to context
context.put("issue", issue);
// FIXME: (JSS) is this needed?
context.put("attachment", aAttachment);
context.put("activityList", getActivityList());
String fromUser = "scarab.email.modifyissue";
if (subject == null)
{
subject = "[" + issue.getModule().getRealName().toUpperCase() +
"] Issue #" + issue.getUniqueId() + " modified";
}
if (template == null)
{
template = Turbine.getConfiguration().
getString("scarab.email.modifyissue.template");
}
// Get users for "to" field of email
List toUsers = new LinkedList();
// Then add users who are assigned to "email-to" attributes
List users = issue.getUsersToEmail(AttributePeer.EMAIL_TO);
Iterator iter = users.iterator();
while ( iter.hasNext() )
{
toUsers.add(iter.next());
}
// add users to cc field of email
List ccUsers = null;
users = issue.getUsersToEmail(AttributePeer.CC_TO);
if (users != null)
{
ccUsers = new LinkedList();
iter = users.iterator();
while ( iter.hasNext() )
{
ccUsers.add(iter.next());
}
}
return Email.sendEmail( context, issue.getModule(), fromUser, toUsers,
ccUsers, subject, template);
}
/**
If no subject and template have been specified,
Pass null arguments to the email method to specify
Using default values for modify issue.
@throws Exception
*/
public boolean sendEmail(TemplateContext context, Issue issue)
throws Exception
{
return sendEmail(context, issue, null, null);
}
public boolean sendEmail(Issue issue)
throws Exception
{
return sendEmail(null, issue, null, null);
}
/**
Convenience method for emails that require no extra context info.
@throws Exception
*/
public boolean sendEmail(Issue issue, String subject, String template)
throws Exception
{
return sendEmail(null, issue, subject, template);
}
}
| SpoonLabs/gumtree-spoon-ast-diff | src/test/resources/examples/t_227130/left_Transaction_1.37.java | Java | apache-2.0 | 7,708 |
package resources
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// GroupsClient is the provides operations for working with resources and resource groups.
type GroupsClient struct {
BaseClient
}
// NewGroupsClient creates an instance of the GroupsClient client.
func NewGroupsClient(subscriptionID string) GroupsClient {
return NewGroupsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewGroupsClientWithBaseURI creates an instance of the GroupsClient client.
func NewGroupsClientWithBaseURI(baseURI string, subscriptionID string) GroupsClient {
return GroupsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CheckExistence checks whether a resource group exists.
// Parameters:
// resourceGroupName - the name of the resource group to check. The name is case insensitive.
func (client GroupsClient) CheckExistence(ctx context.Context, resourceGroupName string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "CheckExistence", err.Error())
}
req, err := client.CheckExistencePreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", nil, "Failure preparing request")
return
}
resp, err := client.CheckExistenceSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", resp, "Failure sending request")
return
}
result, err = client.CheckExistenceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CheckExistence", resp, "Failure responding to request")
}
return
}
// CheckExistencePreparer prepares the CheckExistence request.
func (client GroupsClient) CheckExistencePreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsHead(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CheckExistenceSender sends the CheckExistence request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) CheckExistenceSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CheckExistenceResponder handles the response to the CheckExistence request. The method always
// closes the http.Response Body.
func (client GroupsClient) CheckExistenceResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound),
autorest.ByClosing())
result.Response = resp
return
}
// CreateOrUpdate creates or updates a resource group.
// Parameters:
// resourceGroupName - the name of the resource group to create or update.
// parameters - parameters supplied to the create or update a resource group.
func (client GroupsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, parameters Group) (result Group, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "CreateOrUpdate", resp, "Failure responding to request")
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client GroupsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, parameters Group) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client GroupsClient) CreateOrUpdateResponder(resp *http.Response) (result Group, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete when you delete a resource group, all of its resources are also deleted. Deleting a resource group deletes
// all of its template deployments and currently stored operations.
// Parameters:
// resourceGroupName - the name of the resource group to delete. The name is case insensitive.
func (client GroupsClient) Delete(ctx context.Context, resourceGroupName string) (result GroupsDeleteFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client GroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) DeleteSender(req *http.Request) (future GroupsDeleteFuture, err error) {
var resp *http.Response
resp, err = autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client GroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByClosing())
result.Response = resp
return
}
// ExportTemplate captures the specified resource group as a template.
// Parameters:
// resourceGroupName - the name of the resource group to export as a template.
// parameters - parameters for exporting the template.
func (client GroupsClient) ExportTemplate(ctx context.Context, resourceGroupName string, parameters ExportTemplateRequest) (result GroupExportResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "ExportTemplate", err.Error())
}
req, err := client.ExportTemplatePreparer(ctx, resourceGroupName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "ExportTemplate", nil, "Failure preparing request")
return
}
resp, err := client.ExportTemplateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "ExportTemplate", resp, "Failure sending request")
return
}
result, err = client.ExportTemplateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "ExportTemplate", resp, "Failure responding to request")
}
return
}
// ExportTemplatePreparer prepares the ExportTemplate request.
func (client GroupsClient) ExportTemplatePreparer(ctx context.Context, resourceGroupName string, parameters ExportTemplateRequest) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/exportTemplate", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ExportTemplateSender sends the ExportTemplate request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) ExportTemplateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ExportTemplateResponder handles the response to the ExportTemplate request. The method always
// closes the http.Response Body.
func (client GroupsClient) ExportTemplateResponder(resp *http.Response) (result GroupExportResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Get gets a resource group.
// Parameters:
// resourceGroupName - the name of the resource group to get. The name is case insensitive.
func (client GroupsClient) Get(ctx context.Context, resourceGroupName string) (result Group, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client GroupsClient) GetPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client GroupsClient) GetResponder(resp *http.Response) (result Group, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List gets all the resource groups for a subscription.
// Parameters:
// filter - the filter to apply on the operation.
// top - the number of results to return. If null is passed, returns all resource groups.
func (client GroupsClient) List(ctx context.Context, filter string, top *int32) (result GroupListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx, filter, top)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.glr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure sending request")
return
}
result.glr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client GroupsClient) ListPreparer(ctx context.Context, filter string, top *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
if top != nil {
queryParameters["$top"] = autorest.Encode("query", *top)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client GroupsClient) ListResponder(resp *http.Response) (result GroupListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client GroupsClient) listNextResults(lastResults GroupListResult) (result GroupListResult, err error) {
req, err := lastResults.groupListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "resources.GroupsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client GroupsClient) ListComplete(ctx context.Context, filter string, top *int32) (result GroupListResultIterator, err error) {
result.page, err = client.List(ctx, filter, top)
return
}
// Update resource groups can be updated through a simple PATCH operation to a group address. The format of the request
// is the same as that for creating a resource group. If a field is unspecified, the current value is retained.
// Parameters:
// resourceGroupName - the name of the resource group to update. The name is case insensitive.
// parameters - parameters supplied to update a resource group.
func (client GroupsClient) Update(ctx context.Context, resourceGroupName string, parameters GroupPatchable) (result Group, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("resources.GroupsClient", "Update", err.Error())
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "resources.GroupsClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client GroupsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, parameters GroupPatchable) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-05-10"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client GroupsClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client GroupsClient) UpdateResponder(resp *http.Response) (result Group, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| linzhaoming/origin | vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources/groups.go | GO | apache-2.0 | 24,281 |
/**
* Copyright 2010 Newcastle University
* <p>
* http://research.ncl.ac.uk/smart/
* <p>
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 org.apache.oltu.oauth2.client.demo.controller;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.demo.Utils;
import org.apache.oltu.oauth2.client.demo.model.OAuthParams;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ResourceController {
private Logger logger = LoggerFactory.getLogger(ResourceController.class);
@RequestMapping("/get_resource")
public ModelAndView authorize(@ModelAttribute("oauthParams") OAuthParams oauthParams,
HttpServletRequest req) {
logger.debug("start processing /get_resource request");
try {
OAuthClientRequest request = getoAuthClientRequest(oauthParams);
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse resourceResponse = client.resource(request, oauthParams.getRequestMethod(), OAuthResourceResponse.class);
if (resourceResponse.getResponseCode() == 200) {
oauthParams.setResource(resourceResponse.getBody());
} else {
oauthParams.setErrorMessage(
"Could not access resource: " + resourceResponse.getResponseCode() + " " + resourceResponse.getBody());
}
} catch (OAuthSystemException e) {
logger.error("Failed to process get_resource request", e);
oauthParams.setErrorMessage(e.getMessage());
} catch (OAuthProblemException e) {
logger.error("Invalid get_resource request", e);
oauthParams.setErrorMessage(e.getMessage());
}
return new ModelAndView("resource");
}
private OAuthClientRequest getoAuthClientRequest(OAuthParams oauthParams) throws OAuthSystemException {
OAuthClientRequest request = null;
OAuthBearerClientRequest oAuthBearerClientRequest =
new OAuthBearerClientRequest(oauthParams.getResourceUrl())
.setAccessToken(oauthParams.getAccessToken());
String requestType = oauthParams.getRequestType();
if (Utils.REQUEST_TYPE_QUERY.equals(requestType)) {
request = oAuthBearerClientRequest.buildQueryMessage();
} else if (Utils.REQUEST_TYPE_HEADER.equals(requestType)) {
request = oAuthBearerClientRequest.buildHeaderMessage();
} else if (Utils.REQUEST_TYPE_BODY.equals(requestType)) {
request = oAuthBearerClientRequest.buildBodyMessage();
}
return request;
}
}
| englishtown/oltu | demos/client-demo/src/main/java/org/apache/oltu/oauth2/client/demo/controller/ResourceController.java | Java | apache-2.0 | 4,130 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""This file simply creates the AUTHOR file based on parser content."""
from __future__ import print_function
import fnmatch
import os
def ProcessFile(file_path):
"""Process a single file to match for an author tag."""
# TODO: Change to do a "proper" import of modules and
# check the __author__ attribute of it.
# Current approach does not work if the author tag is a list
# instead of a single attribute (current files as of writing do
# not have that behavior, but that might change in the future).
ret = ''
with open(file_path, 'rb') as fh:
for line in fh:
if '__author__' in line:
_, _, ret = line[:-1].partition(' = ')
return ret[1:-1]
if __name__ == '__main__':
header = """# Names should be added to this file with this pattern:
#
# For individuals:
# Name (email address)
#
# For organizations:
# Organization (fnmatch pattern)
#
# See python fnmatch module documentation for more information.
Google Inc. (*@google.com)
Kristinn Gudjonsson ([email protected])
Joachim Metz ([email protected])
Eric Mak ([email protected])
Elizabeth Schweinsberg ([email protected])
Keith Wall ([email protected])
"""
authors = []
with open('AUTHORS', 'wb') as out_file:
out_file.write(header)
for path, folders, files in os.walk('.'):
if path in ('utils', 'build', 'dist'):
continue
for filematch in fnmatch.filter(files, '*.py'):
author = ProcessFile(os.path.join(path, filematch))
if not author:
continue
if isinstance(author, (list, tuple)):
for author_name in author:
if author_name not in authors:
authors.append(author)
else:
if author not in authors:
authors.append(author)
out_file.write('\n'.join(authors))
out_file.write('\n')
print(u'Added {0:d} authors from files.'.format(len(authors)))
| ostree/plaso | utils/create_authors.py | Python | apache-2.0 | 1,946 |
package io.github.droidkaigi.confsched.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.like.LikeButton;
import com.like.OnLikeListener;
import org.parceler.Parcels;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import io.github.droidkaigi.confsched.MainApplication;
import io.github.droidkaigi.confsched.R;
import io.github.droidkaigi.confsched.activity.ActivityNavigator;
import io.github.droidkaigi.confsched.dao.SessionDao;
import io.github.droidkaigi.confsched.databinding.FragmentSessionsTabBinding;
import io.github.droidkaigi.confsched.databinding.ItemSessionBinding;
import io.github.droidkaigi.confsched.model.Session;
import io.github.droidkaigi.confsched.util.AlarmUtil;
import io.github.droidkaigi.confsched.widget.ArrayRecyclerAdapter;
import io.github.droidkaigi.confsched.widget.BindingHolder;
import io.github.droidkaigi.confsched.widget.itemdecoration.SpaceItemDecoration;
public class SessionsTabFragment extends Fragment {
protected static final String ARG_SESSIONS = "sessions";
private static final int REQ_DETAIL = 1;
@Inject
SessionDao dao;
@Inject
ActivityNavigator activityNavigator;
private SessionsAdapter adapter;
private FragmentSessionsTabBinding binding;
private List<Session> sessions;
private SessionsFragment.OnChangeSessionListener onChangeSessionListener = sessions -> {/* no op */};
@NonNull
public static SessionsTabFragment newInstance(List<Session> sessions) {
SessionsTabFragment fragment = new SessionsTabFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SESSIONS, Parcels.wrap(sessions));
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessions = Parcels.unwrap(getArguments().getParcelable(ARG_SESSIONS));
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
MainApplication.getComponent(this).inject(this);
if (context instanceof SessionsFragment.OnChangeSessionListener) {
onChangeSessionListener = (SessionsFragment.OnChangeSessionListener) context;
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentSessionsTabBinding.inflate(inflater, container, false);
bindData();
return binding.getRoot();
}
private void bindData() {
adapter = createAdapter();
binding.recyclerView.setAdapter(adapter);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
int spacing = getResources().getDimensionPixelSize(R.dimen.spacing_xsmall);
binding.recyclerView.addItemDecoration(new SpaceItemDecoration(spacing));
adapter.addAll(sessions);
}
protected SessionsAdapter createAdapter() {
return new SessionsAdapter(getContext());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_DETAIL:
if (resultCode == Activity.RESULT_OK) {
Session session = Parcels.unwrap(data.getParcelableExtra(Session.class.getSimpleName()));
if (session != null) {
adapter.refresh(session);
onChangeSessionListener.onChangeSession(Collections.singletonList(session));
}
}
break;
}
}
public void scrollUpToTop() {
binding.recyclerView.smoothScrollToPosition(0);
}
protected class SessionsAdapter extends ArrayRecyclerAdapter<Session, BindingHolder<ItemSessionBinding>> {
public SessionsAdapter(@NonNull Context context) {
super(context);
}
protected void refresh(@NonNull Session session) {
// TODO It may be heavy logic...
for (int i = 0, count = adapter.getItemCount(); i < count; i++) {
Session s = adapter.getItem(i);
if (session.equals(s)) {
s.checked = session.checked;
adapter.notifyItemChanged(i);
}
}
}
@Override
public BindingHolder<ItemSessionBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
return new BindingHolder<>(getContext(), parent, R.layout.item_session);
}
@Override
public void onBindViewHolder(BindingHolder<ItemSessionBinding> holder, int position) {
Session session = getItem(position);
ItemSessionBinding binding = holder.binding;
binding.setSession(session);
if (position > 0 && position < getItemCount()) {
Session prevSession = getItem(position - 1);
if (prevSession.stime.getTime() == session.stime.getTime()) {
binding.txtStime.setVisibility(View.INVISIBLE);
} else {
binding.txtStime.setVisibility(View.VISIBLE);
}
} else {
binding.txtStime.setVisibility(View.VISIBLE);
}
binding.txtConflict.setVisibility(View.GONE);
binding.btnStar.setOnLikeListener(new OnLikeListener() {
@Override
public void liked(LikeButton likeButton) {
session.checked = true;
onLikeChanged(session, position);
}
@Override
public void unLiked(LikeButton likeButton) {
session.checked = false;
onLikeChanged(session, position);
}
});
binding.cardView.setOnClickListener(v ->
activityNavigator.showSessionDetail(SessionsTabFragment.this, session, REQ_DETAIL));
}
protected void onLikeChanged(@NonNull Session session, int position) {
dao.updateChecked(session);
AlarmUtil.handleSessionAlarm(getContext(), session);
onChangeSessionListener.onChangeSession(Collections.singletonList(session));
}
}
}
| sys1yagi/droidkaigi2016 | app/src/main/java/io/github/droidkaigi/confsched/fragment/SessionsTabFragment.java | Java | apache-2.0 | 6,769 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.smartdata.server.rest;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartdata.model.RuleState;
import org.smartdata.server.SmartEngine;
import org.smartdata.server.rest.message.JsonResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Rules APIs.
*/
@Path("/rules")
@Produces("application/json")
public class RuleRestApi {
private SmartEngine smartEngine;
private static final Logger logger =
LoggerFactory.getLogger(RuleRestApi.class);
public RuleRestApi(SmartEngine smartEngine) {
this.smartEngine = smartEngine;
}
@POST
@Path("/add")
public Response addRule(@FormParam("ruleText") String ruleText) {
String rule;
long t;
try {
logger.info("Adding rule: " + ruleText);
t = smartEngine.getRuleManager().submitRule(ruleText, RuleState.DISABLED);
} catch (Exception e) {
logger.error("Exception in RuleRestApi while adding rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
return new JsonResponse(Response.Status.CREATED, t).build();
}
@POST
@Path("/{ruleId}/delete")
public Response deleteRule(@PathParam("ruleId") String ruleId) {
try {
Long longNumber = Long.parseLong(ruleId);
smartEngine.getRuleManager().deleteRule(longNumber, false);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while deleting rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/{ruleId}/start")
public Response start(@PathParam("ruleId") String ruleId) {
logger.info("Start rule{}", ruleId);
Long intNumber = Long.parseLong(ruleId);
try {
smartEngine.getRuleManager().activateRule(intNumber);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while starting rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@POST
@Path("/{ruleId}/stop")
public Response stop(@PathParam("ruleId") String ruleId) {
logger.info("Stop rule{}", ruleId);
Long intNumber = Long.parseLong(ruleId);
try {
smartEngine.getRuleManager().disableRule(intNumber, true);
return new JsonResponse<>(Response.Status.OK).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while stopping rule ", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/info")
public Response info(@PathParam("ruleId") String ruleId) {
Long intNumber = Long.parseLong(ruleId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().getRuleInfo(intNumber)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting rule info", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/cmdlets/{pageIndex}/{numPerPage}/{orderBy}/{isDesc}")
public Response cmdlets(@PathParam("ruleId") String ruleId,
@PathParam("pageIndex") String pageIndex,
@PathParam("numPerPage") String numPerPage,
@PathParam("orderBy") String orderBy,
@PathParam("isDesc") String isDesc) {
Long longNumber = Long.parseLong(ruleId);
if (logger.isDebugEnabled()) {
logger.debug("ruleId={}, pageIndex={}, numPerPage={}, orderBy={}, " +
"isDesc={}", longNumber, pageIndex, numPerPage, orderBy, isDesc);
}
try {
List<String> orderByList = Arrays.asList(orderBy.split(","));
List<String> isDescStringList = Arrays.asList(isDesc.split(","));
List<Boolean> isDescList = new ArrayList<>();
for (int i = 0; i < isDescStringList.size(); i++) {
isDescList.add(Boolean.parseBoolean(isDescStringList.get(i)));
}
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().listCmdletsInfo(longNumber,
Integer.parseInt(pageIndex),
Integer.parseInt(numPerPage), orderByList, isDescList)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/{ruleId}/cmdlets")
public Response cmdlets(@PathParam("ruleId") String ruleId) {
Long intNumber = Long.parseLong(ruleId);
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getCmdletManager().listCmdletsInfo(intNumber, null)).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while getting cmdlets", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list")
public Response ruleList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/move")
public Response ruleMoveList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesMoveInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing Move rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
@GET
@Path("/list/sync")
public Response ruleSyncList() {
try {
return new JsonResponse<>(Response.Status.OK,
smartEngine.getRuleManager().listRulesSyncInfo()).build();
} catch (Exception e) {
logger.error("Exception in RuleRestApi while listing Sync rules", e);
return new JsonResponse<>(Response.Status.INTERNAL_SERVER_ERROR,
e.getMessage(), ExceptionUtils.getStackTrace(e)).build();
}
}
}
| duzhen1996/SSM | smart-zeppelin/zeppelin-server/src/main/java/org/smartdata/server/rest/RuleRestApi.java | Java | apache-2.0 | 7,718 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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 com.intellij.openapi.wm.impl.status;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.TaskInfo;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.openapi.ui.popup.IconButton;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.InplaceButton;
import com.intellij.ui.components.panels.NonOpaquePanel;
import com.intellij.ui.components.panels.Wrapper;
import com.intellij.util.containers.JBIterable;
import com.intellij.util.ui.GraphicsUtil;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class InlineProgressIndicator extends ProgressIndicatorBase implements Disposable {
protected final TextPanel myText = new TextPanel();
private final TextPanel myText2 = new TextPanel();
private final JBIterable<ProgressButton> myEastButtons;
protected JProgressBar myProgress;
private JPanel myComponent;
private final boolean myCompact;
private TaskInfo myInfo;
private final TextPanel myProcessName = new TextPanel();
private boolean myDisposed;
public InlineProgressIndicator(boolean compact, @NotNull TaskInfo processInfo) {
myCompact = compact;
myInfo = processInfo;
myProgress = new JProgressBar(SwingConstants.HORIZONTAL);
UIUtil.applyStyle(UIUtil.ComponentStyle.MINI, myProgress);
myComponent = new MyComponent(compact, myProcessName);
myEastButtons = createEastButtons();
if (myCompact) {
myComponent.setLayout(new BorderLayout(2, 0));
createCompactTextAndProgress();
myComponent.add(createButtonPanel(myEastButtons.map(b -> b.button)), BorderLayout.EAST);
myComponent.setToolTipText(processInfo.getTitle() + ". " + IdeBundle.message("progress.text.clickToViewProgressWindow"));
}
else {
myComponent.setLayout(new BorderLayout());
myProcessName.setText(processInfo.getTitle());
myComponent.add(myProcessName, BorderLayout.NORTH);
myProcessName.setForeground(UIUtil.getPanelBackground().brighter().brighter());
myProcessName.setBorder(JBUI.Borders.empty(2));
final NonOpaquePanel content = new NonOpaquePanel(new BorderLayout());
content.setBorder(JBUI.Borders.empty(2, 2, 2, myInfo.isCancellable() ? 2 : 4));
myComponent.add(content, BorderLayout.CENTER);
content.add(createButtonPanel(myEastButtons.map(b -> withBorder(b.button))), BorderLayout.EAST);
content.add(myText, BorderLayout.NORTH);
content.add(myProgress, BorderLayout.CENTER);
content.add(myText2, BorderLayout.SOUTH);
myComponent.setBorder(JBUI.Borders.empty(2));
}
UIUtil.uiTraverser(myComponent).forEach(o -> ((JComponent)o).setOpaque(false));
if (!myCompact) {
myProcessName.recomputeSize();
myText.recomputeSize();
myText2.recomputeSize();
}
}
protected void createCompactTextAndProgress() {
JPanel textAndProgress = new NonOpaquePanel(new BorderLayout());
textAndProgress.add(myText, BorderLayout.CENTER);
final NonOpaquePanel progressWrapper = new NonOpaquePanel(new BorderLayout());
progressWrapper.setBorder(JBUI.Borders.empty(0, 4));
progressWrapper.add(myProgress, BorderLayout.CENTER);
textAndProgress.add(progressWrapper, BorderLayout.EAST);
myComponent.add(textAndProgress, BorderLayout.CENTER);
}
static JPanel createButtonPanel(Iterable<JComponent> components) {
JPanel iconsPanel = new NonOpaquePanel(new GridBagLayout());
GridBag gb = new GridBag().setDefaultFill(GridBagConstraints.BOTH);
for (JComponent component : components) {
iconsPanel.add(component, gb.next());
}
return iconsPanel;
}
private static Wrapper withBorder(InplaceButton button) {
Wrapper wrapper = new Wrapper(button);
wrapper.setBorder(JBUI.Borders.empty(0, 3, 0, 2));
return wrapper;
}
protected JBIterable<ProgressButton> createEastButtons() {
return JBIterable.of(createCancelButton());
}
private ProgressButton createCancelButton() {
InplaceButton cancelButton = new InplaceButton(
new IconButton(myInfo.getCancelTooltipText(),
myCompact ? AllIcons.Process.StopSmall : AllIcons.Process.Stop,
myCompact ? AllIcons.Process.StopSmallHovered : AllIcons.Process.StopHovered),
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
cancelRequest();
}
}).setFillBg(false);
cancelButton.setVisible(myInfo.isCancellable());
return new ProgressButton(cancelButton, () -> cancelButton.setPainting(!isStopping()));
}
protected void cancelRequest() {
cancel();
}
protected void updateProgress() {
queueProgressUpdate();
}
protected void updateAndRepaint() {
if (isDisposed()) return;
updateProgressNow();
myComponent.repaint();
}
public void updateProgressNow() {
if (isPaintingIndeterminate()) {
myProgress.setIndeterminate(true);
}
else {
myProgress.setIndeterminate(false);
myProgress.setMinimum(0);
myProgress.setMaximum(100);
}
if (getFraction() > 0) {
myProgress.setValue((int)(getFraction() * 99 + 1));
}
myText.setText(getText() != null ? getText() : "");
myText2.setText(getText2() != null ? getText2() : "");
if (myCompact && StringUtil.isEmpty(myText.getText())) {
myText.setText(myInfo.getTitle());
}
if (isStopping()) {
if (myCompact) {
myText.setText("Stopping - " + myText.getText());
} else {
myProcessName.setText("Stopping - " + myInfo.getTitle());
}
myText.setEnabled(false);
myText2.setEnabled(false);
myProgress.setEnabled(false);
} else {
myText.setEnabled(true);
myText2.setEnabled(true);
myProgress.setEnabled(true);
}
myEastButtons.forEach(b -> b.updateAction.run());
}
protected boolean isPaintingIndeterminate() {
return isIndeterminate() || getFraction() == 0;
}
private boolean isStopping() {
return wasStarted() && (isCanceled() || !isRunning()) && !isFinished();
}
protected boolean isFinished() {
return false;
}
protected void queueProgressUpdate() {
updateAndRepaint();
}
protected void queueRunningUpdate(@NotNull Runnable update) {
update.run();
}
@Override
protected void onProgressChange() {
updateProgress();
}
public JComponent getComponent() {
return myComponent;
}
public boolean isCompact() {
return myCompact;
}
public TaskInfo getInfo() {
return myInfo;
}
private class MyComponent extends JPanel {
private final boolean myCompact;
private final JComponent myProcessName;
private MyComponent(final boolean compact, final JComponent processName) {
myCompact = compact;
myProcessName = processName;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (UIUtil.isCloseClick(e) && getBounds().contains(e.getX(), e.getY())) {
cancelRequest();
}
}
});
}
@Override
protected void paintComponent(final Graphics g) {
if (myCompact) {
super.paintComponent(g);
return;
}
final GraphicsConfig c = GraphicsUtil.setupAAPainting(g);
UISettings.setupAntialiasing(g);
int arc = 8;
Color bg = getBackground();
final Rectangle bounds = myProcessName.getBounds();
final Rectangle label = SwingUtilities.convertRectangle(myProcessName.getParent(), bounds, this);
g.setColor(UIUtil.getPanelBackground());
g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, arc, arc);
if (!UIUtil.isUnderDarcula()) {
bg = ColorUtil.toAlpha(bg.darker().darker(), 230);
g.setColor(bg);
g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, arc, arc);
g.setColor(UIUtil.getPanelBackground());
g.fillRoundRect(0, getHeight() / 2, getWidth() - 1, getHeight() / 2, arc, arc);
g.fillRect(0, (int)label.getMaxY() + 1, getWidth() - 1, getHeight() / 2);
} else {
bg = bg.brighter();
g.setColor(bg);
g.drawLine(0, (int)label.getMaxY() + 1, getWidth() - 1, (int)label.getMaxY() + 1);
}
g.setColor(bg);
g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, arc, arc);
c.restore();
}
}
@Override
public void dispose() {
if (myDisposed) return;
myDisposed = true;
myComponent.removeAll();
myComponent = null;
if (myProgress != null) {
UIUtil.disposeProgress(myProgress);
}
myProgress = null;
myInfo = null;
}
private boolean isDisposed() {
return myDisposed;
}
}
class ProgressButton {
final InplaceButton button;
final Runnable updateAction;
ProgressButton(InplaceButton button, Runnable updateAction) {
this.button = button;
this.updateAction = updateAction;
}
} | goodwinnk/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java | Java | apache-2.0 | 10,047 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.component.jcr;
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class JcrAuthLoginTest extends JcrAuthTestBase {
@Test
public void testCreateNodeWithAuthentication() throws Exception {
Exchange exchange = createExchangeWithBody("<message>hello!</message>");
Exchange out = template.send("direct:a", exchange);
assertNotNull(out);
String uuid = out.getMessage().getBody(String.class);
assertNotNull("Out body was null; expected JCR node UUID", uuid);
Session session = getRepository().login(
new SimpleCredentials("admin", "admin".toCharArray()));
try {
Node node = session.getNodeByIdentifier(uuid);
assertNotNull(node);
assertEquals(BASE_REPO_PATH + "/node", node.getPath());
} finally {
if (session != null && session.isLive()) {
session.logout();
}
}
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// START SNIPPET: jcr
from("direct:a").setHeader(JcrConstants.JCR_NODE_NAME,
constant("node")).setHeader("my.contents.property",
body()).to(
"jcr://test:quatloos@repository" + BASE_REPO_PATH);
// END SNIPPET: jcr
}
};
}
}
| ullgren/camel | components/camel-jcr/src/test/java/org/apache/camel/component/jcr/JcrAuthLoginTest.java | Java | apache-2.0 | 2,471 |
/*
Copyright 2011-2016 Google Inc. All Rights Reserved.
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 com.google.security.zynamics.reil.translators.arm;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;
import java.util.List;
public class ARMUmullTranslator extends ARMBaseTranslator {
@Override
protected void translateCore(final ITranslationEnvironment environment,
final IInstruction instruction, final List<ReilInstruction> instructions) {
final IOperandTreeNode registerOperand1 =
instruction.getOperands().get(0).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand2 =
instruction.getOperands().get(1).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand3 =
instruction.getOperands().get(2).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand4 =
instruction.getOperands().get(3).getRootNode().getChildren().get(0);
final String sourceRegister1 = (registerOperand1.getValue());
final String sourceRegister2 = (registerOperand2.getValue());
final String sourceRegister3 = (registerOperand3.getValue());
final String sourceRegister4 = (registerOperand4.getValue());
final OperandSize bt = OperandSize.BYTE;
final OperandSize wd = OperandSize.WORD;
final OperandSize dw = OperandSize.DWORD;
final OperandSize qw = OperandSize.QWORD;
long baseOffset = (instruction.getAddress().toLong() * 0x100) + instructions.size();
final String tmpVar1 = environment.getNextVariableString();
instructions.add(ReilHelpers.createMul(baseOffset++, dw, sourceRegister3, dw, sourceRegister4,
qw, tmpVar1));
instructions.add(ReilHelpers.createAnd(baseOffset++, qw, tmpVar1, dw,
String.valueOf(0xFFFFFFFFL), dw, sourceRegister1));
instructions.add(ReilHelpers.createBsh(baseOffset++, qw, tmpVar1, wd, String.valueOf(-32L), dw,
sourceRegister2));
if (instruction.getMnemonic().endsWith("S") && (instruction.getMnemonic().length() != 7)) {
final String isZero1 = environment.getNextVariableString();
final String isZero2 = environment.getNextVariableString();
instructions.add(ReilHelpers.createBsh(baseOffset++, dw, sourceRegister2, wd,
String.valueOf(-31L), bt, "N"));
instructions.add(ReilHelpers.createBisz(baseOffset++, dw, sourceRegister1, bt, isZero1));
instructions.add(ReilHelpers.createBisz(baseOffset++, dw, sourceRegister2, bt, isZero2));
instructions.add(ReilHelpers.createAnd(baseOffset++, bt, isZero1, bt, isZero2, bt, "Z"));
}
}
/**
* UMULL{<cond>}{S} <RdLo>, <RdHi>, <Rm>, <Rs>
*
* Operation:
*
* if ConditionPassed(cond) then RdHi = (Rm * Rs)[63:32] // Unsigned multiplication RdLo = (Rm *
* Rs)[31:0] if S == 1 then N Flag = RdHi[31] Z Flag = if (RdHi == 0) and (RdLo == 0) then 1 else
* 0 C Flag = unaffected // See "C and V flags" note V Flag = unaffected // See "C and V flags"
* note
*/
@Override
public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
final List<ReilInstruction> instructions) throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "UMULL");
translateAll(environment, instruction, "UMULL", instructions);
}
}
| chubbymaggie/binnavi | src/main/java/com/google/security/zynamics/reil/translators/arm/ARMUmullTranslator.java | Java | apache-2.0 | 4,339 |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// join_test.cpp
//
// Identification: test/executor/join_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include "common/harness.h"
#include "executor/testing_executor_util.h"
#include "executor/testing_join_util.h"
#include "common/internal_types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/executor_context.h"
#include "executor/hash_executor.h"
#include "executor/hash_join_executor.h"
#include "executor/index_scan_executor.h"
#include "executor/merge_join_executor.h"
#include "executor/nested_loop_join_executor.h"
#include "executor/seq_scan_executor.h"
#include "expression/abstract_expression.h"
#include "expression/expression_util.h"
#include "expression/tuple_value_expression.h"
#include "planner/hash_join_plan.h"
#include "planner/hash_plan.h"
#include "planner/index_scan_plan.h"
#include "planner/merge_join_plan.h"
#include "planner/nested_loop_join_plan.h"
#include "planner/seq_scan_plan.h"
#include "storage/data_table.h"
#include "storage/tile.h"
#include "concurrency/transaction_manager_factory.h"
#include "executor/mock_executor.h"
using ::testing::NotNull;
using ::testing::Return;
using ::testing::InSequence;
namespace peloton {
namespace test {
class JoinTests : public PelotonTest {};
std::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() {
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
auto left = expression::ExpressionUtil::TupleValueFactory(
type::TypeId::INTEGER, 0, 1);
auto right = expression::ExpressionUtil::TupleValueFactory(
type::TypeId::INTEGER, 1, 1);
bool reversed = false;
join_clauses.emplace_back(left, right, reversed);
return join_clauses;
}
std::shared_ptr<const peloton::catalog::Schema> CreateJoinSchema() {
return std::shared_ptr<const peloton::catalog::Schema>(
new catalog::Schema({TestingExecutorUtil::GetColumnInfo(1),
TestingExecutorUtil::GetColumnInfo(1),
TestingExecutorUtil::GetColumnInfo(0),
TestingExecutorUtil::GetColumnInfo(0)}));
}
// PlanNodeType::NESTLOOP is picked out as a separated test
std::vector<PlanNodeType> join_algorithms = {PlanNodeType::MERGEJOIN,
PlanNodeType::HASHJOIN};
std::vector<JoinType> join_types = {JoinType::INNER, JoinType::LEFT,
JoinType::RIGHT, JoinType::OUTER};
void ExecuteJoinTest(PlanNodeType join_algorithm, JoinType join_type,
oid_t join_test_type);
void ExecuteNestedLoopJoinTest(JoinType join_type, bool IndexScan = false);
void PopulateTable(storage::DataTable *table, int num_rows, bool random,
concurrency::TransactionContext *current_txn);
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile);
void ValidateJoinLogicalTile(executor::LogicalTile *logical_tile);
void ValidateNestedLoopJoinLogicalTile(executor::LogicalTile *logical_tile);
void ExpectEmptyTileResult(MockExecutor *table_scan_executor);
void ExpectMoreThanOneTileResults(
MockExecutor *table_scan_executor,
std::vector<std::unique_ptr<executor::LogicalTile>>
&table_logical_tile_ptrs);
void ExpectNormalTileResults(size_t table_tile_group_count,
MockExecutor *table_scan_executor,
std::vector<std::unique_ptr<executor::LogicalTile>>
&table_logical_tile_ptrs);
enum JOIN_TEST_TYPE {
BASIC_TEST = 0,
BOTH_TABLES_EMPTY = 1,
COMPLICATED_TEST = 2,
SPEED_TEST = 3,
LEFT_TABLE_EMPTY = 4,
RIGHT_TABLE_EMPTY = 5,
};
TEST_F(JoinTests, BasicTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
ExecuteJoinTest(join_algorithm, JoinType::INNER, BASIC_TEST);
}
}
TEST_F(JoinTests, EmptyTablesTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
ExecuteJoinTest(join_algorithm, JoinType::INNER, BOTH_TABLES_EMPTY);
}
}
TEST_F(JoinTests, JoinTypesTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
// Go over all join types
for (auto join_type : join_types) {
LOG_TRACE("JOIN TYPE :: %s", JoinTypeToString(join_type).c_str());
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type, BASIC_TEST);
}
}
}
TEST_F(JoinTests, ComplicatedTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
// Go over all join types
for (auto join_type : join_types) {
LOG_TRACE("JOIN TYPE :: %s", JoinTypeToString(join_type).c_str());
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type, COMPLICATED_TEST);
}
}
}
TEST_F(JoinTests, LeftTableEmptyTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
// Go over all join types
for (auto join_type : join_types) {
LOG_TRACE("JOIN TYPE :: %s", JoinTypeToString(join_type).c_str());
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type, LEFT_TABLE_EMPTY);
}
}
}
TEST_F(JoinTests, RightTableEmptyTest) {
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
// Go over all join types
for (auto join_type : join_types) {
LOG_TRACE("JOIN TYPE :: %s", JoinTypeToString(join_type).c_str());
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type, RIGHT_TABLE_EMPTY);
}
}
}
TEST_F(JoinTests, JoinPredicateTest) {
oid_t join_test_types = 1;
// Go over all join test types
for (oid_t join_test_type = 0; join_test_type < join_test_types;
join_test_type++) {
LOG_TRACE("JOIN TEST_F ------------------------ :: %u", join_test_type);
// Go over all join algorithms
for (auto join_algorithm : join_algorithms) {
LOG_TRACE("JOIN ALGORITHM :: %s",
PlanNodeTypeToString(join_algorithm).c_str());
// Go over all join types
for (auto join_type : join_types) {
LOG_TRACE("JOIN TYPE :: %s", JoinTypeToString(join_type).c_str());
// Execute the join test
ExecuteJoinTest(join_algorithm, join_type, join_test_type);
}
}
}
}
TEST_F(JoinTests, SpeedTest) {
ExecuteJoinTest(PlanNodeType::HASHJOIN, JoinType::OUTER, SPEED_TEST);
ExecuteJoinTest(PlanNodeType::MERGEJOIN, JoinType::OUTER, SPEED_TEST);
ExecuteNestedLoopJoinTest(JoinType::OUTER, true);
ExecuteNestedLoopJoinTest(JoinType::OUTER, false);
}
TEST_F(JoinTests, BasicNestedLoopTest) {
LOG_TRACE("PlanNodeType::NESTLOOP");
ExecuteNestedLoopJoinTest(JoinType::INNER, true);
ExecuteNestedLoopJoinTest(JoinType::INNER, false);
}
void PopulateTable(storage::DataTable *table, int num_rows, bool random,
concurrency::TransactionContext *current_txn) {
// Random values
if (random) std::srand(std::time(nullptr));
const catalog::Schema *schema = table->GetSchema();
// Ensure that the tile group is as expected.
PELOTON_ASSERT(schema->GetColumnCount() == 4);
// Insert tuples into tile_group.
const bool allocate = true;
auto testing_pool = TestingHarness::GetInstance().GetTestingPool();
for (int rowid = 0; rowid < num_rows; rowid++) {
storage::Tuple tuple(schema, allocate);
// First column is unique in this case
tuple.SetValue(0, type::ValueFactory::GetIntegerValue(50 * rowid).Copy(),
testing_pool);
// In case of random, make sure this column has duplicated values
tuple.SetValue(
1, type::ValueFactory::GetIntegerValue(50 * rowid * 2 + 1).Copy(),
testing_pool);
tuple.SetValue(2, type::ValueFactory::GetDecimalValue(1.5).Copy(),
testing_pool);
// In case of random, make sure this column has duplicated values
auto string_value =
type::ValueFactory::GetVarcharValue(std::to_string(123));
tuple.SetValue(3, string_value, testing_pool);
ItemPointer *index_entry_ptr = nullptr;
ItemPointer tuple_slot_id =
table->InsertTuple(&tuple, current_txn, &index_entry_ptr);
PELOTON_ASSERT(tuple_slot_id.block != INVALID_OID);
PELOTON_ASSERT(tuple_slot_id.offset != INVALID_OID);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
txn_manager.PerformInsert(current_txn, tuple_slot_id, index_entry_ptr);
}
}
void ExecuteNestedLoopJoinTest(JoinType join_type, bool IndexScan) {
//===--------------------------------------------------------------------===//
// Create Table
//===--------------------------------------------------------------------===//
// Create a table and wrap it in logical tile
size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
size_t left_table_tile_group_count = 3;
size_t right_table_tile_group_count = 2;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
// Left table has 3 tile groups (15 tuples)
std::unique_ptr<storage::DataTable> left_table(
TestingExecutorUtil::CreateTable(tile_group_size));
TestingExecutorUtil::PopulateTable(
left_table.get(), tile_group_size * left_table_tile_group_count, false,
false, false, txn);
// Right table has 2 tile groups (10 tuples)
std::unique_ptr<storage::DataTable> right_table(
TestingExecutorUtil::CreateTable(tile_group_size));
PopulateTable(right_table.get(),
tile_group_size * right_table_tile_group_count, false, txn);
txn_manager.CommitTransaction(txn);
LOG_INFO("%s\n", left_table->GetInfo().c_str());
LOG_INFO("%s\n", right_table->GetInfo().c_str());
//===--------------------------------------------------------------------===//
// Begin nested loop
//===--------------------------------------------------------------------===//
txn = txn_manager.BeginTransaction();
std::unique_ptr<executor::ExecutorContext> context(
new executor::ExecutorContext(txn));
//===--------------------------------------------------------------------===//
// Create executors
//===--------------------------------------------------------------------===//
// executor::IndexScanExecutor left_table_scan_executor,
// right_table_scan_executor;
// LEFT ATTR 0 == 100
auto index = left_table->GetIndex(0);
std::vector<oid_t> key_column_ids;
std::vector<ExpressionType> expr_types;
std::vector<type::Value> values;
std::vector<expression::AbstractExpression *> runtime_keys;
key_column_ids.push_back(0);
expr_types.push_back(ExpressionType::COMPARE_EQUAL);
values.push_back(type::ValueFactory::GetIntegerValue(50).Copy());
expression::AbstractExpression *predicate_scan = nullptr;
std::vector<oid_t> column_ids({0, 1, 3}); // COL_A, B, D
std::unique_ptr<executor::AbstractExecutor> left_table_scan_executor;
std::unique_ptr<planner::AbstractPlan> left_table_node;
if (IndexScan) {
LOG_INFO("Construct Left Index Scan Node");
// Create index scan desc
planner::IndexScanPlan::IndexScanDesc index_scan_desc(
index->GetOid(), key_column_ids, expr_types, values, runtime_keys);
// Create plan node.
left_table_node.reset(new planner::IndexScanPlan(
left_table.get(), predicate_scan, column_ids, index_scan_desc));
// executor
left_table_scan_executor.reset(
new executor::IndexScanExecutor(left_table_node.get(), context.get()));
} else {
LOG_INFO("Construct Left Seq Scan Node");
// Create sequential scan plan node
left_table_node.reset(
new planner::SeqScanPlan(left_table.get(), predicate_scan, column_ids));
// Executor
left_table_scan_executor.reset(
new executor::SeqScanExecutor(left_table_node.get(), context.get()));
}
// Right ATTR 0 =
auto index_right = right_table->GetIndex(0);
std::vector<oid_t> key_column_ids_right;
std::vector<ExpressionType> expr_types_right;
std::vector<type::Value> values_right;
std::vector<expression::AbstractExpression *> runtime_keys_right;
key_column_ids_right.push_back(0);
expr_types_right.push_back(ExpressionType::COMPARE_EQUAL);
// values_right.push_back(type::ValueFactory::GetIntegerValue(100).Copy());
values_right.push_back(type::ValueFactory::GetParameterOffsetValue(0).Copy());
expression::AbstractExpression *predicate_scan_right = nullptr;
std::vector<oid_t> column_ids_right({0, 1});
std::unique_ptr<executor::AbstractExecutor> right_table_scan_executor;
std::unique_ptr<planner::AbstractPlan> right_table_node;
if (IndexScan) {
LOG_INFO("Construct Right Index Scan Node");
// Create index scan desc
planner::IndexScanPlan::IndexScanDesc index_scan_desc_right(
index_right->GetOid(), key_column_ids_right, expr_types_right,
values_right, runtime_keys_right);
// Create plan node.
right_table_node.reset(
new planner::IndexScanPlan(right_table.get(), predicate_scan_right,
column_ids_right, index_scan_desc_right));
// executor
right_table_scan_executor.reset(
new executor::IndexScanExecutor(right_table_node.get(), context.get()));
} else {
LOG_INFO("Construct Right Seq Scan Node");
// Create sequential scan plan node
right_table_node.reset(new planner::SeqScanPlan(
right_table.get(), predicate_scan_right, column_ids_right));
// Executor
right_table_scan_executor.reset(
new executor::SeqScanExecutor(right_table_node.get(), context.get()));
}
//===--------------------------------------------------------------------===//
// Setup join plan nodes and executors and run them
//===--------------------------------------------------------------------===//
oid_t result_tuple_count = 0;
oid_t tuples_with_null = 0;
auto projection = TestingJoinUtil::CreateProjection();
// setup the projection schema
auto schema = CreateJoinSchema();
// Construct predicate
expression::TupleValueExpression *left_table_attr_1 =
new expression::TupleValueExpression(type::TypeId::INTEGER, 0, 0);
expression::TupleValueExpression *right_table_attr_1 =
new expression::TupleValueExpression(type::TypeId::INTEGER, 1, 0);
std::unique_ptr<const expression::AbstractExpression> predicate(
new expression::ComparisonExpression(ExpressionType::COMPARE_EQUAL,
left_table_attr_1,
right_table_attr_1));
// LEFT.A = RIGHT.A
std::vector<oid_t> join_column_ids_left = {0}; // A in the result
std::vector<oid_t> join_column_ids_right = {0}; // A in the table
// Create nested loop join plan node.
planner::NestedLoopJoinPlan nested_loop_join_node(
join_type, std::move(predicate), std::move(projection), schema,
join_column_ids_left, join_column_ids_right);
// Run the nested loop join executor
executor::NestedLoopJoinExecutor nested_loop_join_executor(
&nested_loop_join_node, context.get());
// Construct the executor tree
nested_loop_join_executor.AddChild(left_table_scan_executor.get());
nested_loop_join_executor.AddChild(right_table_scan_executor.get());
// Run the nested loop join executor
EXPECT_TRUE(nested_loop_join_executor.Init());
while (nested_loop_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
nested_loop_join_executor.GetOutput());
if (result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());
ValidateNestedLoopJoinLogicalTile(result_logical_tile.get());
LOG_INFO("result tile info: %s", result_logical_tile->GetInfo().c_str());
LOG_INFO("result_tuple_count: %u", result_tuple_count);
LOG_INFO("tuples_with_null: %u", tuples_with_null);
} else {
LOG_INFO("Nothing find out");
}
}
txn_manager.CommitTransaction(txn);
}
void ExecuteJoinTest(PlanNodeType join_algorithm, JoinType join_type,
oid_t join_test_type) {
//===--------------------------------------------------------------------===//
// Mock table scan executors
//===--------------------------------------------------------------------===//
MockExecutor left_table_scan_executor, right_table_scan_executor;
// Create a table and wrap it in logical tile
size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
size_t left_table_tile_group_count = 3;
size_t right_table_tile_group_count = 2;
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
// Left table has 3 tile groups (15 tuples)
std::unique_ptr<storage::DataTable> left_table(
TestingExecutorUtil::CreateTable(tile_group_size));
TestingExecutorUtil::PopulateTable(
left_table.get(), tile_group_size * left_table_tile_group_count, false,
false, false, txn);
// Right table has 2 tile groups (10 tuples)
std::unique_ptr<storage::DataTable> right_table(
TestingExecutorUtil::CreateTable(tile_group_size));
TestingExecutorUtil::PopulateTable(
right_table.get(), tile_group_size * right_table_tile_group_count, false,
false, false, txn);
txn_manager.CommitTransaction(txn);
LOG_TRACE("%s", left_table->GetInfo().c_str());
LOG_TRACE("%s", right_table->GetInfo().c_str());
if (join_test_type == COMPLICATED_TEST) {
// Modify some values in left and right tables for complicated test
auto left_source_tile = left_table->GetTileGroup(2)->GetTile(0);
auto right_dest_tile = right_table->GetTileGroup(1)->GetTile(0);
auto right_source_tile = left_table->GetTileGroup(0)->GetTile(0);
auto source_tile_tuple_count = left_source_tile->GetAllocatedTupleCount();
auto source_tile_column_count = left_source_tile->GetColumnCount();
// LEFT - 3 rd tile --> RIGHT - 2 nd tile
for (oid_t tuple_itr = 3; tuple_itr < source_tile_tuple_count;
tuple_itr++) {
for (oid_t col_itr = 0; col_itr < source_tile_column_count; col_itr++) {
type::Value val = (left_source_tile->GetValue(tuple_itr, col_itr));
right_dest_tile->SetValue(val, tuple_itr, col_itr);
}
}
// RIGHT - 1 st tile --> RIGHT - 2 nd tile
// RIGHT - 2 nd tile --> RIGHT - 2 nd tile
for (oid_t col_itr = 0; col_itr < source_tile_column_count; col_itr++) {
type::Value val1 = (right_source_tile->GetValue(4, col_itr));
right_dest_tile->SetValue(val1, 0, col_itr);
type::Value val2 = (right_dest_tile->GetValue(3, col_itr));
right_dest_tile->SetValue(val2, 2, col_itr);
}
}
std::vector<std::unique_ptr<executor::LogicalTile>>
left_table_logical_tile_ptrs;
std::vector<std::unique_ptr<executor::LogicalTile>>
right_table_logical_tile_ptrs;
// Wrap the input tables with logical tiles
for (size_t left_table_tile_group_itr = 0;
left_table_tile_group_itr < left_table_tile_group_count;
left_table_tile_group_itr++) {
std::unique_ptr<executor::LogicalTile> left_table_logical_tile(
executor::LogicalTileFactory::WrapTileGroup(
left_table->GetTileGroup(left_table_tile_group_itr)));
left_table_logical_tile_ptrs.push_back(std::move(left_table_logical_tile));
}
for (size_t right_table_tile_group_itr = 0;
right_table_tile_group_itr < right_table_tile_group_count;
right_table_tile_group_itr++) {
std::unique_ptr<executor::LogicalTile> right_table_logical_tile(
executor::LogicalTileFactory::WrapTileGroup(
right_table->GetTileGroup(right_table_tile_group_itr)));
right_table_logical_tile_ptrs.push_back(
std::move(right_table_logical_tile));
}
// Left scan executor returns logical tiles from the left table
EXPECT_CALL(left_table_scan_executor, DInit()).WillOnce(Return(true));
//===--------------------------------------------------------------------===//
// Setup left table
//===--------------------------------------------------------------------===//
if (join_test_type == BASIC_TEST || join_test_type == COMPLICATED_TEST ||
join_test_type == SPEED_TEST) {
ExpectNormalTileResults(left_table_tile_group_count,
&left_table_scan_executor,
left_table_logical_tile_ptrs);
} else if (join_test_type == BOTH_TABLES_EMPTY) {
ExpectEmptyTileResult(&left_table_scan_executor);
} else if (join_test_type == LEFT_TABLE_EMPTY) {
ExpectEmptyTileResult(&left_table_scan_executor);
} else if (join_test_type == RIGHT_TABLE_EMPTY) {
if (join_type == JoinType::INNER || join_type == JoinType::RIGHT) {
ExpectMoreThanOneTileResults(&left_table_scan_executor,
left_table_logical_tile_ptrs);
} else {
ExpectNormalTileResults(left_table_tile_group_count,
&left_table_scan_executor,
left_table_logical_tile_ptrs);
}
}
// Right scan executor returns logical tiles from the right table
// EXPECT_CALL(right_table_scan_executor, DInit()).WillOnce(Return(true));
EXPECT_CALL(right_table_scan_executor, DInit()).WillRepeatedly(Return(true));
//===--------------------------------------------------------------------===//
// Setup right table
//===--------------------------------------------------------------------===//
if (join_test_type == BASIC_TEST || join_test_type == COMPLICATED_TEST ||
join_test_type == SPEED_TEST) {
ExpectNormalTileResults(right_table_tile_group_count,
&right_table_scan_executor,
right_table_logical_tile_ptrs);
} else if (join_test_type == BOTH_TABLES_EMPTY) {
ExpectEmptyTileResult(&right_table_scan_executor);
} else if (join_test_type == LEFT_TABLE_EMPTY) {
if (join_type == JoinType::INNER || join_type == JoinType::LEFT) {
// For hash join, we always build the hash table from right child
if (join_algorithm == PlanNodeType::HASHJOIN) {
ExpectNormalTileResults(right_table_tile_group_count,
&right_table_scan_executor,
right_table_logical_tile_ptrs);
} else {
ExpectMoreThanOneTileResults(&right_table_scan_executor,
right_table_logical_tile_ptrs);
}
} else if (join_type == JoinType::OUTER || join_type == JoinType::RIGHT) {
ExpectNormalTileResults(right_table_tile_group_count,
&right_table_scan_executor,
right_table_logical_tile_ptrs);
}
} else if (join_test_type == RIGHT_TABLE_EMPTY) {
ExpectEmptyTileResult(&right_table_scan_executor);
}
//===--------------------------------------------------------------------===//
// Setup join plan nodes and executors and run them
//===--------------------------------------------------------------------===//
oid_t result_tuple_count = 0;
oid_t tuples_with_null = 0;
auto projection = TestingJoinUtil::CreateProjection();
// setup the projection schema
auto schema = CreateJoinSchema();
// Construct predicate
std::unique_ptr<const expression::AbstractExpression> predicate(
TestingJoinUtil::CreateJoinPredicate());
// Differ based on join algorithm
switch (join_algorithm) {
case PlanNodeType::NESTLOOP: {
// Create nested loop join plan node.
std::vector<oid_t> left_join_cols = {1};
std::vector<oid_t> right_join_cols = {1};
planner::NestedLoopJoinPlan nested_loop_join_node(
join_type, std::move(predicate), std::move(projection), schema,
left_join_cols, right_join_cols);
// Run the nested loop join executor
executor::NestedLoopJoinExecutor nested_loop_join_executor(
&nested_loop_join_node, nullptr);
// Construct the executor tree
nested_loop_join_executor.AddChild(&left_table_scan_executor);
nested_loop_join_executor.AddChild(&right_table_scan_executor);
// Run the nested loop join executor
EXPECT_TRUE(nested_loop_join_executor.Init());
while (nested_loop_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
nested_loop_join_executor.GetOutput());
if (result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null +=
CountTuplesWithNullFields(result_logical_tile.get());
ValidateJoinLogicalTile(result_logical_tile.get());
LOG_TRACE("result tile info: %s",
result_logical_tile->GetInfo().c_str());
}
}
} break;
case PlanNodeType::MERGEJOIN: {
// Create join clauses
std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;
join_clauses = CreateJoinClauses();
// Create merge join plan node
planner::MergeJoinPlan merge_join_node(join_type, std::move(predicate),
std::move(projection), schema,
join_clauses);
// Construct the merge join executor
executor::MergeJoinExecutor merge_join_executor(&merge_join_node,
nullptr);
// Construct the executor tree
merge_join_executor.AddChild(&left_table_scan_executor);
merge_join_executor.AddChild(&right_table_scan_executor);
// Run the merge join executor
EXPECT_TRUE(merge_join_executor.Init());
while (merge_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
merge_join_executor.GetOutput());
if (result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null +=
CountTuplesWithNullFields(result_logical_tile.get());
ValidateJoinLogicalTile(result_logical_tile.get());
LOG_TRACE("%s", result_logical_tile->GetInfo().c_str());
}
}
} break;
case PlanNodeType::HASHJOIN: {
// Create hash plan node
expression::AbstractExpression *right_table_attr_1 =
new expression::TupleValueExpression(type::TypeId::INTEGER, 1, 1);
std::vector<std::unique_ptr<const expression::AbstractExpression>>
hash_keys;
hash_keys.emplace_back(right_table_attr_1);
std::vector<std::unique_ptr<const expression::AbstractExpression>>
left_hash_keys;
left_hash_keys.emplace_back(
std::unique_ptr<expression::AbstractExpression>{
new expression::TupleValueExpression(type::TypeId::INTEGER, 0,
1)});
std::vector<std::unique_ptr<const expression::AbstractExpression>>
right_hash_keys;
right_hash_keys.emplace_back(
std::unique_ptr<expression::AbstractExpression>{
new expression::TupleValueExpression(type::TypeId::INTEGER, 1,
1)});
// Create hash plan node
planner::HashPlan hash_plan_node(hash_keys);
// Construct the hash executor
executor::HashExecutor hash_executor(&hash_plan_node, nullptr);
// Create hash join plan node.
planner::HashJoinPlan hash_join_plan_node(
join_type, std::move(predicate), std::move(projection), schema,
left_hash_keys, right_hash_keys, false);
// Construct the hash join executor
executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node,
nullptr);
// Construct the executor tree
hash_join_executor.AddChild(&left_table_scan_executor);
hash_join_executor.AddChild(&hash_executor);
hash_executor.AddChild(&right_table_scan_executor);
// Run the hash_join_executor
EXPECT_TRUE(hash_join_executor.Init());
while (hash_join_executor.Execute() == true) {
std::unique_ptr<executor::LogicalTile> result_logical_tile(
hash_join_executor.GetOutput());
if (result_logical_tile != nullptr) {
result_tuple_count += result_logical_tile->GetTupleCount();
tuples_with_null +=
CountTuplesWithNullFields(result_logical_tile.get());
ValidateJoinLogicalTile(result_logical_tile.get());
LOG_TRACE("%s", result_logical_tile->GetInfo().c_str());
}
}
} break;
default:
throw Exception("Unsupported join algorithm : " +
PlanNodeTypeToString(join_algorithm));
break;
}
//===--------------------------------------------------------------------===//
// Execute test
//===--------------------------------------------------------------------===//
if (join_test_type == BASIC_TEST) {
// Check output
switch (join_type) {
case JoinType::INNER:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::LEFT:
EXPECT_EQ(result_tuple_count, 15);
EXPECT_EQ(tuples_with_null, 5);
break;
case JoinType::RIGHT:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::OUTER:
EXPECT_EQ(result_tuple_count, 15);
EXPECT_EQ(tuples_with_null, 5);
break;
default:
throw Exception("Unsupported join type : " +
JoinTypeToString(join_type));
break;
}
} else if (join_test_type == BOTH_TABLES_EMPTY) {
// Check output
switch (join_type) {
case JoinType::INNER:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::LEFT:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::RIGHT:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::OUTER:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
default:
throw Exception("Unsupported join type : " +
JoinTypeToString(join_type));
break;
}
} else if (join_test_type == COMPLICATED_TEST) {
// Check output
switch (join_type) {
case JoinType::INNER:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::LEFT:
EXPECT_EQ(result_tuple_count, 17);
EXPECT_EQ(tuples_with_null, 7);
break;
case JoinType::RIGHT:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::OUTER:
EXPECT_EQ(result_tuple_count, 17);
EXPECT_EQ(tuples_with_null, 7);
break;
default:
throw Exception("Unsupported join type : " +
JoinTypeToString(join_type));
break;
}
} else if (join_test_type == LEFT_TABLE_EMPTY) {
// Check output
switch (join_type) {
case JoinType::INNER:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::LEFT:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::RIGHT:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 10);
break;
case JoinType::OUTER:
EXPECT_EQ(result_tuple_count, 10);
EXPECT_EQ(tuples_with_null, 10);
break;
default:
throw Exception("Unsupported join type : " +
JoinTypeToString(join_type));
break;
}
} else if (join_test_type == RIGHT_TABLE_EMPTY) {
// Check output
switch (join_type) {
case JoinType::INNER:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::LEFT:
EXPECT_EQ(result_tuple_count, 15);
EXPECT_EQ(tuples_with_null, 15);
break;
case JoinType::RIGHT:
EXPECT_EQ(result_tuple_count, 0);
EXPECT_EQ(tuples_with_null, 0);
break;
case JoinType::OUTER:
EXPECT_EQ(result_tuple_count, 15);
EXPECT_EQ(tuples_with_null, 15);
break;
default:
throw Exception("Unsupported join type : " +
JoinTypeToString(join_type));
break;
}
}
}
oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile) {
PELOTON_ASSERT(logical_tile);
// Get column count
auto column_count = logical_tile->GetColumnCount();
oid_t tuples_with_null = 0;
// Go over the tile
for (auto logical_tile_itr : *logical_tile) {
const ContainerTuple<executor::LogicalTile> join_tuple(logical_tile,
logical_tile_itr);
// Go over all the fields and check for null values
for (oid_t col_itr = 0; col_itr < column_count; col_itr++) {
type::Value val = (join_tuple.GetValue(col_itr));
if (val.IsNull()) {
tuples_with_null++;
break;
}
}
}
return tuples_with_null;
}
void ValidateJoinLogicalTile(executor::LogicalTile *logical_tile) {
PELOTON_ASSERT(logical_tile);
// Get column count
auto column_count = logical_tile->GetColumnCount();
// Check # of columns
EXPECT_EQ(column_count, 4);
// Check the attribute values
// Go over the tile
for (auto logical_tile_itr : *logical_tile) {
const ContainerTuple<executor::LogicalTile> join_tuple(logical_tile,
logical_tile_itr);
// Check the join fields
type::Value left_tuple_join_attribute_val = (join_tuple.GetValue(0));
type::Value right_tuple_join_attribute_val = (join_tuple.GetValue(1));
type::Value cmp = type::ValueFactory::GetBooleanValue(
(left_tuple_join_attribute_val.CompareEquals(
right_tuple_join_attribute_val)));
EXPECT_TRUE(cmp.IsNull() || cmp.IsTrue());
}
}
void ValidateNestedLoopJoinLogicalTile(executor::LogicalTile *logical_tile) {
PELOTON_ASSERT(logical_tile);
// Get column count
auto column_count = logical_tile->GetColumnCount();
// Check # of columns
EXPECT_EQ(column_count, 4);
// Check the attribute values
// Go over the tile
for (auto logical_tile_itr : *logical_tile) {
const ContainerTuple<executor::LogicalTile> join_tuple(logical_tile,
logical_tile_itr);
// Check the join fields
type::Value left_tuple_join_attribute_val = (join_tuple.GetValue(2));
type::Value right_tuple_join_attribute_val = (join_tuple.GetValue(3));
type::Value cmp = type::ValueFactory::GetBooleanValue(
(left_tuple_join_attribute_val.CompareEquals(
right_tuple_join_attribute_val)));
EXPECT_TRUE(cmp.IsNull() || cmp.IsTrue());
}
}
void ExpectEmptyTileResult(MockExecutor *table_scan_executor) {
// Expect zero result tiles from the child
EXPECT_CALL(*table_scan_executor, DExecute()).WillOnce(Return(false));
}
void ExpectMoreThanOneTileResults(
MockExecutor *table_scan_executor,
std::vector<std::unique_ptr<executor::LogicalTile>>
&table_logical_tile_ptrs) {
// Expect more than one result tiles from the child, but only get one of them
EXPECT_CALL(*table_scan_executor, DExecute()).WillOnce(Return(true));
EXPECT_CALL(*table_scan_executor, GetOutput())
.WillOnce(Return(table_logical_tile_ptrs[0].release()));
}
void ExpectNormalTileResults(size_t table_tile_group_count,
MockExecutor *table_scan_executor,
std::vector<std::unique_ptr<executor::LogicalTile>>
&table_logical_tile_ptrs) {
// Return true for the first table_tile_group_count times
// Then return false after that
{
testing::Sequence execute_sequence;
for (size_t table_tile_group_itr = 0;
table_tile_group_itr < table_tile_group_count + 1;
table_tile_group_itr++) {
// Return true for the first table_tile_group_count times
if (table_tile_group_itr < table_tile_group_count) {
EXPECT_CALL(*table_scan_executor, DExecute())
.InSequence(execute_sequence)
.WillOnce(Return(true));
} else // Return false after that
{
EXPECT_CALL(*table_scan_executor, DExecute())
.InSequence(execute_sequence)
.WillOnce(Return(false));
}
}
}
// Return the appropriate logical tiles for the first table_tile_group_count
// times
{
testing::Sequence get_output_sequence;
for (size_t table_tile_group_itr = 0;
table_tile_group_itr < table_tile_group_count;
table_tile_group_itr++) {
EXPECT_CALL(*table_scan_executor, GetOutput())
.InSequence(get_output_sequence)
.WillOnce(
Return(table_logical_tile_ptrs[table_tile_group_itr].release()));
}
}
}
} // namespace test
} // namespace peloton
| malin1993ml/peloton | test/executor/join_test.cpp | C++ | apache-2.0 | 38,200 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/cognito-identity/CognitoIdentity_EXPORTS.h>
#include <aws/cognito-identity/CognitoIdentityRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace CognitoIdentity
{
namespace Model
{
/**
*/
class AWS_COGNITOIDENTITY_API ListTagsForResourceRequest : public CognitoIdentityRequest
{
public:
ListTagsForResourceRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ListTagsForResource"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline const Aws::String& GetResourceArn() const{ return m_resourceArn; }
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; }
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline ListTagsForResourceRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline ListTagsForResourceRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the identity pool that the tags are
* assigned to.</p>
*/
inline ListTagsForResourceRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;}
private:
Aws::String m_resourceArn;
bool m_resourceArnHasBeenSet;
};
} // namespace Model
} // namespace CognitoIdentity
} // namespace Aws
| awslabs/aws-sdk-cpp | aws-cpp-sdk-cognito-identity/include/aws/cognito-identity/model/ListTagsForResourceRequest.h | C | apache-2.0 | 3,118 |
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.io;
/**
* Reads text from a character-input stream, buffering characters so as to
* provide for the efficient reading of characters, arrays, and lines.
*
* <p> The buffer size may be specified, or the default size may be used. The
* default is large enough for most purposes.
*
* <p> In general, each read request made of a Reader causes a corresponding
* read request to be made of the underlying character or byte stream. It is
* therefore advisable to wrap a BufferedReader around any Reader whose read()
* operations may be costly, such as FileReaders and InputStreamReaders. For
* example,
*
* <pre>
* BufferedReader in
* = new BufferedReader(new FileReader("foo.in"));
* </pre>
*
* will buffer the input from the specified file. Without buffering, each
* invocation of read() or readLine() could cause bytes to be read from the
* file, converted into characters, and then returned, which can be very
* inefficient.
*
* <p> Programs that use DataInputStreams for textual input can be localized by
* replacing each DataInputStream with an appropriate BufferedReader.
*
* @see FileReader
* @see InputStreamReader
* @see java.nio.file.Files#newBufferedReader
*
* @author Mark Reinhold
* @since JDK1.1
*/
public class BufferedReader extends Reader {
private Reader in;
private char cb[];
private int nChars, nextChar;
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
/** If the next character is a line feed, skip it */
private boolean skipLF = false;
/** The skipLF flag when the mark was set */
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
/**
* Creates a buffering character-input stream that uses an input buffer of
* the specified size.
*
* @param in A Reader
* @param sz Input-buffer size
*
* @exception IllegalArgumentException If sz is <= 0
*/
public BufferedReader(Reader in, int sz) {
super(in);
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in A Reader
*/
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
/** Checks to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
if (in == null)
throw new IOException("Stream closed");
}
/**
* Fills the input buffer, taking the mark into account if it is valid.
*/
private void fill() throws IOException {
int dst;
if (markedChar <= UNMARKED) {
/* No mark */
dst = 0;
} else {
/* Marked */
int delta = nextChar - markedChar;
if (delta >= readAheadLimit) {
/* Gone past read-ahead limit: Invalidate mark */
markedChar = INVALIDATED;
readAheadLimit = 0;
dst = 0;
} else {
if (readAheadLimit <= cb.length) {
/* Shuffle in the current buffer */
System.arraycopy(cb, markedChar, cb, 0, delta);
markedChar = 0;
dst = delta;
} else {
/* Reallocate buffer to accommodate read-ahead limit */
char ncb[] = new char[readAheadLimit];
System.arraycopy(cb, markedChar, ncb, 0, delta);
cb = ncb;
markedChar = 0;
dst = delta;
}
nextChar = nChars = delta;
}
}
int n;
do {
n = in.read(cb, dst, cb.length - dst);
} while (n == 0);
if (n > 0) {
nChars = dst + n;
nextChar = dst;
}
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range
* 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
* end of the stream has been reached
* @exception IOException If an I/O error occurs
*/
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
for (;;) {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return -1;
}
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
continue;
}
}
return cb[nextChar++];
}
}
}
/**
* Reads characters into a portion of an array, reading from the underlying
* stream if necessary.
*/
private int read1(char[] cbuf, int off, int len) throws IOException {
if (nextChar >= nChars) {
/* If the requested length is at least as large as the buffer, and
if there is no mark/reset activity, and if line feeds are not
being skipped, do not bother to copy the characters into the
local buffer. In this way buffered streams will cascade
harmlessly. */
if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if (nextChar >= nChars) return -1;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
if (nextChar >= nChars)
fill();
if (nextChar >= nChars)
return -1;
}
}
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
}
/**
* Reads characters into a portion of an array.
*
* <p> This method implements the general contract of the corresponding
* <code>{@link Reader#read(char[], int, int) read}</code> method of the
* <code>{@link Reader}</code> class. As an additional convenience, it
* attempts to read as many characters as possible by repeatedly invoking
* the <code>read</code> method of the underlying stream. This iterated
* <code>read</code> continues until one of the following conditions becomes
* true: <ul>
*
* <li> The specified number of characters have been read,
*
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file, or
*
* <li> The <code>ready</code> method of the underlying stream
* returns <code>false</code>, indicating that further input requests
* would block.
*
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of characters
* actually read.
*
* <p> Subclasses of this class are encouraged, but not required, to
* attempt to read as many characters as possible in the same fashion.
*
* <p> Ordinarily this method takes characters from this stream's character
* buffer, filling it from the underlying stream as necessary. If,
* however, the buffer is empty, the mark is not valid, and the requested
* length is at least as large as the buffer, then this method will read
* characters directly from the underlying stream into the given array.
* Thus redundant <code>BufferedReader</code>s will not copy data
* unnecessarily.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
*
* @return The number of characters read, or -1 if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*/
public int read(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
int n = read1(cbuf, off, len);
if (n <= 0) return n;
while ((n < len) && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if (n1 <= 0) break;
n += n1;
}
return n;
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @param ignoreLF If true, the next '\n' will be skipped
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
*
* @see java.io.LineNumberReader#readLine()
*
* @exception IOException If an I/O error occurs
*/
String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;
synchronized (lock) {
ensureOpen();
boolean omitLF = ignoreLF || skipLF;
bufferLoop:
for (;;) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
if (omitLF && (cb[nextChar] == '\n'))
nextChar++;
skipLF = false;
omitLF = false;
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n') || (c == '\r')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if (c == '\r') {
skipLF = true;
}
return str;
}
if (s == null)
s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*
* @see java.nio.file.Files#readAllLines
*/
public String readLine() throws IOException {
return readLine(false);
}
/**
* Skips characters.
*
* @param n The number of characters to skip
*
* @return The number of characters actually skipped
*
* @exception IllegalArgumentException If <code>n</code> is negative.
* @exception IOException If an I/O error occurs
*/
public long skip(long n) throws IOException {
if (n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
synchronized (lock) {
ensureOpen();
long r = n;
while (r > 0) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) /* EOF */
break;
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
}
}
long d = nChars - nextChar;
if (r <= d) {
nextChar += r;
r = 0;
break;
}
else {
r -= d;
nextChar = nChars;
}
}
return n - r;
}
}
/**
* Tells whether this stream is ready to be read. A buffered character
* stream is ready if the buffer is not empty, or if the underlying
* character stream is ready.
*
* @exception IOException If an I/O error occurs
*/
public boolean ready() throws IOException {
synchronized (lock) {
ensureOpen();
/*
* If newline needs to be skipped and the next char to be read
* is a newline character, then just skip it right away.
*/
if (skipLF) {
/* Note that in.ready() will return true if and only if the next
* read on the stream will not block.
*/
if (nextChar >= nChars && in.ready()) {
fill();
}
if (nextChar < nChars) {
if (cb[nextChar] == '\n')
nextChar++;
skipLF = false;
}
}
return (nextChar < nChars) || in.ready();
}
}
/**
* Tells whether this stream supports the mark() operation, which it does.
*/
public boolean markSupported() {
return true;
}
/**
* Marks the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. An attempt
* to reset the stream after reading characters
* up to this limit or beyond may fail.
* A limit value larger than the size of the input
* buffer will cause a new buffer to be allocated
* whose size is no smaller than limit.
* Therefore large values should be used with care.
*
* @exception IllegalArgumentException If readAheadLimit is < 0
* @exception IOException If an I/O error occurs
*/
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
synchronized (lock) {
ensureOpen();
this.readAheadLimit = readAheadLimit;
markedChar = nextChar;
markedSkipLF = skipLF;
}
}
/**
* Resets the stream to the most recent mark.
*
* @exception IOException If the stream has never been marked,
* or if the mark has been invalidated
*/
public void reset() throws IOException {
synchronized (lock) {
ensureOpen();
if (markedChar < 0)
throw new IOException((markedChar == INVALIDATED)
? "Mark invalid"
: "Stream not marked");
nextChar = markedChar;
skipLF = markedSkipLF;
}
}
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
in.close();
in = null;
cb = null;
}
}
}
| haikuowuya/android_system_code | src/java/io/BufferedReader.java | Java | apache-2.0 | 17,179 |
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <p>
*/
package org.olat.repository;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Hibernate;
import org.olat.admin.securitygroup.gui.IdentitiesAddEvent;
import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.BaseSecurityManager;
import org.olat.basesecurity.Constants;
import org.olat.basesecurity.SecurityGroup;
import org.olat.bookmark.BookmarkManager;
import org.olat.catalog.CatalogManager;
import org.olat.core.commons.modules.bc.FolderConfig;
import org.olat.core.commons.persistence.DBFactory;
import org.olat.core.commons.persistence.DBQuery;
import org.olat.core.commons.persistence.PersistenceHelper;
import org.olat.core.commons.persistence.async.BackgroundTaskQueueManager;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.id.Identity;
import org.olat.core.id.OLATResourceable;
import org.olat.core.id.Roles;
import org.olat.core.logging.AssertException;
import org.olat.core.logging.Tracing;
import org.olat.core.logging.activity.ActionType;
import org.olat.core.logging.activity.OlatResourceableType;
import org.olat.core.logging.activity.ThreadLocalUserActivityLogger;
import org.olat.core.manager.BasicManager;
import org.olat.core.util.StringHelper;
import org.olat.group.BusinessGroup;
import org.olat.group.BusinessGroupManagerImpl;
import org.olat.group.GroupLoggingAction;
import org.olat.group.context.BGContext;
import org.olat.group.context.BGContextManagerImpl;
import org.olat.repository.async.IncrementDownloadCounterBackgroundTask;
import org.olat.repository.async.IncrementLaunchCounterBackgroundTask;
import org.olat.repository.async.SetAccessBackgroundTask;
import org.olat.repository.async.SetDescriptionNameBackgroundTask;
import org.olat.repository.async.SetLastUsageBackgroundTask;
import org.olat.repository.async.SetPropertiesBackgroundTask;
import org.olat.repository.controllers.RepositoryEntryImageController;
import org.olat.repository.handlers.RepositoryHandler;
import org.olat.repository.handlers.RepositoryHandlerFactory;
import org.olat.resource.OLATResource;
import org.olat.resource.OLATResourceManager;
import org.olat.util.logging.activity.LoggingResourceable;
/**
* Initial Date: Mar 31, 2004
*
* @author Mike Stock Comment:
*/
public class RepositoryManager extends BasicManager {
private static RepositoryManager INSTANCE;
private final BaseSecurity securityManager;
private static BackgroundTaskQueueManager taskQueueManager;
/**
* [used by spring]
*/
private RepositoryManager(final BaseSecurity securityManager, final BackgroundTaskQueueManager taskQueueManager) {
this.securityManager = securityManager;
this.taskQueueManager = taskQueueManager;
INSTANCE = this;
}
/**
* @return Singleton.
*/
public static RepositoryManager getInstance() {
return INSTANCE;
}
/**
* @param initialAuthor
* @return A repository instance which has not been persisted yet.
*/
public RepositoryEntry createRepositoryEntryInstance(final String initialAuthor) {
return createRepositoryEntryInstance(initialAuthor, null, null);
}
/**
* @param initialAuthor
* @param resourceName
* @param description
* @return A repository instance which has not been persisted yet, initialized with given data.
*/
public RepositoryEntry createRepositoryEntryInstance(final String initialAuthor, final String resourceName, final String description) {
final RepositoryEntry re = new RepositoryEntry();
re.setInitialAuthor(initialAuthor);
re.setResourcename(resourceName == null ? "" : resourceName);
re.setDescription(description == null ? "" : description);
re.setLastUsage(new Date());
return re;
}
/**
* @param repositoryEntryStatusCode
*/
public RepositoryEntryStatus createRepositoryEntryStatus(final int repositoryEntryStatusCode) {
return new RepositoryEntryStatus(repositoryEntryStatusCode);
}
/**
* Save repo entry.
*
* @param re
*/
public void saveRepositoryEntry(final RepositoryEntry re) {
if (re.getOwnerGroup() == null) { throw new AssertException("try to save RepositoryEntry without owner-group! Plase initialize owner-group."); }
re.setLastModified(new Date());
DBFactory.getInstance().saveObject(re);
}
/**
* Update repo entry.
*
* @param re
*/
public void updateRepositoryEntry(final RepositoryEntry re) {
re.setLastModified(new Date());
DBFactory.getInstance().updateObject(re);
}
/**
* Delete repo entry.
*
* @param re
*/
public void deleteRepositoryEntry(RepositoryEntry re) {
re = (RepositoryEntry) DBFactory.getInstance().loadObject(re, true);
DBFactory.getInstance().deleteObject(re);
// TODO:pb:b this should be called in a RepoEntryImageManager.delete
// instead of a controller.
RepositoryEntryImageController.deleteImage(re);
}
/**
* @param addedEntry
*/
public void deleteRepositoryEntryAndBasesecurity(RepositoryEntry entry) {
entry = (RepositoryEntry) DBFactory.getInstance().loadObject(entry, true);
DBFactory.getInstance().deleteObject(entry);
OLATResourceManager.getInstance().deleteOLATResourceable(entry);
final SecurityGroup ownerGroup = entry.getOwnerGroup();
if (ownerGroup != null) {
// delete secGroup
Tracing.logDebug("deleteRepositoryEntry deleteSecurityGroup ownerGroup=" + ownerGroup, this.getClass());
BaseSecurityManager.getInstance().deleteSecurityGroup(ownerGroup);
OLATResourceManager.getInstance().deleteOLATResourceable(ownerGroup);
}
// TODO:pb:b this should be called in a RepoEntryImageManager.delete
// instead of a controller.
RepositoryEntryImageController.deleteImage(entry);
}
/**
* clean up a repo entry with all children and associated data like bookmarks and user references to it
*
* @param ureq
* @param wControl
* @param entry
* @return FIXME: we need a delete method without ureq, wControl for manager use. In general, very bad idea to pass ureq and wControl down to the manger layer.
*/
public boolean deleteRepositoryEntryWithAllData(final UserRequest ureq, final WindowControl wControl, RepositoryEntry entry) {
// invoke handler delete callback
Tracing.logDebug("deleteRepositoryEntry start entry=" + entry, this.getClass());
entry = (RepositoryEntry) DBFactory.getInstance().loadObject(entry, true);
Tracing.logDebug("deleteRepositoryEntry after load entry=" + entry, this.getClass());
Tracing.logDebug("deleteRepositoryEntry after load entry.getOwnerGroup()=" + entry.getOwnerGroup(), this.getClass());
final RepositoryHandler handler = RepositoryHandlerFactory.getInstance().getRepositoryHandler(entry);
final OLATResource ores = entry.getOlatResource();
if (!handler.readyToDelete(ores, ureq, wControl)) { return false; }
// start transaction
// delete entry picture
final File uploadDir = new File(FolderConfig.getCanonicalRoot() + FolderConfig.getRepositoryHome());
final File picFile = new File(uploadDir, entry.getKey() + ".jpg");
if (picFile.exists()) {
picFile.delete();
}
// delete all bookmarks referencing deleted entry
BookmarkManager.getInstance().deleteAllBookmarksFor(entry);
// delete all catalog entries referencing deleted entry
CatalogManager.getInstance().resourceableDeleted(entry);
// delete the entry
entry = (RepositoryEntry) DBFactory.getInstance().loadObject(entry, true);
Tracing.logDebug("deleteRepositoryEntry after reload entry=" + entry, this.getClass());
deleteRepositoryEntryAndBasesecurity(entry);
// inform handler to do any cleanup work... handler must delete the
// referenced resourceable aswell.
handler.cleanupOnDelete(entry.getOlatResource());
Tracing.logDebug("deleteRepositoryEntry Done", this.getClass());
return true;
}
/**
* Lookup repo entry by key.
*
* @param the repository entry key (not the olatresourceable key)
* @return Repo entry represented by key or null if no such entry or key is null.
*/
public RepositoryEntry lookupRepositoryEntry(final Long key) {
if (key == null) { return null; }
return (RepositoryEntry) DBFactory.getInstance().findObject(RepositoryEntry.class, key);
}
/**
* Lookup the repository entry which references the given olat resourceable.
*
* @param resourceable
* @param strict true: throws exception if not found, false: returns null if not found
* @return the RepositorEntry or null if strict=false
* @throws AssertException if the softkey could not be found (strict=true)
*/
public RepositoryEntry lookupRepositoryEntry(final OLATResourceable resourceable, final boolean strict) {
final OLATResource ores = OLATResourceManager.getInstance().findResourceable(resourceable);
if (ores == null) {
if (!strict) { return null; }
throw new AssertException("Unable to fetch OLATResource for resourceable: " + resourceable.getResourceableTypeName() + ", "
+ resourceable.getResourceableId());
}
final String query = "select v from org.olat.repository.RepositoryEntry v" + " inner join fetch v.olatResource as ores" + " where ores.key = :oreskey";
final DBQuery dbQuery = DBFactory.getInstance().createQuery(query);
dbQuery.setLong("oreskey", ores.getKey().longValue());
dbQuery.setCacheable(true);
final List result = dbQuery.list();
final int size = result.size();
if (strict) {
if (size != 1) { throw new AssertException("Repository resourceable lookup returned zero or more than one result: " + size); }
} else { // not strict -> return null if zero entries found
if (size > 1) { throw new AssertException("Repository resourceable lookup returned more than one result: " + size); }
if (size == 0) { return null; }
}
return (RepositoryEntry) result.get(0);
}
/**
* Lookup a repository entry by its softkey.
*
* @param softkey
* @param strict true: throws exception if not found, false: returns null if not found
* @return the RepositorEntry or null if strict=false
* @throws AssertException if the softkey could not be found (strict=true)
*/
public RepositoryEntry lookupRepositoryEntryBySoftkey(final String softkey, final boolean strict) {
final String query = "select v from org.olat.repository.RepositoryEntry v" + " inner join fetch v.olatResource as ores" + " where v.softkey = :softkey";
final DBQuery dbQuery = DBFactory.getInstance().createQuery(query);
dbQuery.setString("softkey", softkey);
dbQuery.setCacheable(true);
final List result = dbQuery.list();
final int size = result.size();
if (strict) {
if (size != 1) { throw new AssertException("Repository softkey lookup returned zero or more than one result: " + size + ", softKey = " + softkey); }
} else { // not strict -> return null if zero entries found
if (size > 1) { throw new AssertException("Repository softkey lookup returned more than one result: " + size + ", softKey = " + softkey); }
if (size == 0) { return null; }
}
return (RepositoryEntry) result.get(0);
}
/**
* Convenience method to access the repositoryEntry displayname by the referenced OLATResourceable id. This only works if a repository entry has an referenced olat
* resourceable like a course or an content package repo entry
*
* @param resId
* @return the repositoryentry displayname or null if not found
*/
public String lookupDisplayNameByOLATResourceableId(final Long resId) {
final String query = "select v from org.olat.repository.RepositoryEntry v" + " inner join fetch v.olatResource as ores" + " where ores.resId = :resid";
final DBQuery dbQuery = DBFactory.getInstance().createQuery(query);
dbQuery.setLong("resid", resId.longValue());
dbQuery.setCacheable(true);
final List<RepositoryEntry> result = dbQuery.list();
final int size = result.size();
if (size > 1) {
throw new AssertException("Repository lookup returned zero or more than one result: " + size);
} else if (size == 0) { return null; }
final RepositoryEntry entry = result.get(0);
return entry.getDisplayname();
}
/**
* Test a repo entry if identity is allowed to launch.
*
* @param ureq
* @param re
* @return True if current identity is allowed to launch the given repo entry.
*/
public boolean isAllowedToLaunch(final UserRequest ureq, final RepositoryEntry re) {
return isAllowedToLaunch(ureq.getIdentity(), ureq.getUserSession().getRoles(), re);
}
/**
* Test a repo entry if identity is allowed to launch.
*
* @param identity
* @param roles
* @param re
* @return True if current identity is allowed to launch the given repo entry.
*/
public boolean isAllowedToLaunch(final Identity identity, final Roles roles, final RepositoryEntry re) {
if (!re.getCanLaunch()) { return false; // deny if not launcheable
}
// allow if identity is owner
if (BaseSecurityManager.getInstance().isIdentityPermittedOnResourceable(identity, Constants.PERMISSION_ACCESS, re.getOwnerGroup())) { return true; }
// allow if access limit matches identity's role
// allow for olat administrators
if (roles.isOLATAdmin()) { return true; }
// allow for institutional resource manager
if (isInstitutionalRessourceManagerFor(re, identity)) { return true; }
// allow for authors if access granted at least for authors
if (roles.isAuthor() && re.getAccess() >= RepositoryEntry.ACC_OWNERS_AUTHORS) { return true; }
// allow for guests if access granted for guests
if (roles.isGuestOnly()) {
if (re.getAccess() >= RepositoryEntry.ACC_USERS_GUESTS) {
return true;
} else {
return false;
}
}
// else allow if access granted for users
return re.getAccess() >= RepositoryEntry.ACC_USERS;
}
/**
* Increment the launch counter.
*
* @param re
*/
public void incrementLaunchCounter(final RepositoryEntry re) {
taskQueueManager.addTask(new IncrementLaunchCounterBackgroundTask(re));
}
/**
* Increment the download counter.
*
* @param re
*/
public void incrementDownloadCounter(final RepositoryEntry re) {
taskQueueManager.addTask(new IncrementDownloadCounterBackgroundTask(re));
}
/**
* Set last-usage date to to now for certain repository-entry.
*
* @param
*/
public static void setLastUsageNowFor(final RepositoryEntry re) {
if (re != null) {
taskQueueManager.addTask(new SetLastUsageBackgroundTask(re));
}
}
public void setAccess(final RepositoryEntry re, final int access) {
final SetAccessBackgroundTask task = new SetAccessBackgroundTask(re, access);
taskQueueManager.addTask(task);
task.waitForDone();
}
public void setDescriptionAndName(final RepositoryEntry re, final String displayName, final String description) {
final SetDescriptionNameBackgroundTask task = new SetDescriptionNameBackgroundTask(re, displayName, description);
taskQueueManager.addTask(task);
task.waitForDone();
}
public void setProperties(final RepositoryEntry re, final boolean canCopy, final boolean canReference, final boolean canLaunch, final boolean canDownload) {
final SetPropertiesBackgroundTask task = new SetPropertiesBackgroundTask(re, canCopy, canReference, canLaunch, canDownload);
taskQueueManager.addTask(task);
task.waitForDone();
}
/**
* Count by type, limit by role accessability.
*
* @param restrictedType
* @param roles
* @return Number of repo entries
*/
public int countByTypeLimitAccess(final String restrictedType, final int restrictedAccess) {
final StringBuilder query = new StringBuilder(400);
query.append("select count(*) from" + " org.olat.repository.RepositoryEntry v, " + " org.olat.resource.OLATResourceImpl res "
+ " where v.olatResource = res and res.resName= :restrictedType and v.access >= :restrictedAccess ");
final DBQuery dbquery = DBFactory.getInstance().createQuery(query.toString());
dbquery.setString("restrictedType", restrictedType);
dbquery.setInteger("restrictedAccess", restrictedAccess);
dbquery.setCacheable(true);
return ((Long) dbquery.list().get(0)).intValue();
}
/**
* Query by type without any other limitations
*
* @param restrictedType
* @param roles
* @return Results
*/
public List queryByType(final String restrictedType) {
final String query = "select v from" + " org.olat.repository.RepositoryEntry v" + " inner join fetch v.olatResource as res"
+ " where res.resName= :restrictedType";
final DBQuery dbquery = DBFactory.getInstance().createQuery(query);
dbquery.setString("restrictedType", restrictedType);
dbquery.setCacheable(true);
return dbquery.list();
}
/**
* Query by type, limit by ownership or role accessability.
*
* @param restrictedType
* @param roles
* @return Results
*/
public List queryByTypeLimitAccess(final String restrictedType, final Roles roles) {
final StringBuilder query = new StringBuilder(400);
query.append("select distinct v from" + " org.olat.repository.RepositoryEntry v" + " inner join fetch v.olatResource as res"
+ " where res.resName= :restrictedType and v.access >= ");
if (roles.isOLATAdmin()) {
query.append(RepositoryEntry.ACC_OWNERS); // treat admin special b/c admin is author as well
} else {
if (roles.isAuthor()) {
query.append(RepositoryEntry.ACC_OWNERS_AUTHORS);
} else if (roles.isGuestOnly()) {
query.append(RepositoryEntry.ACC_USERS_GUESTS);
} else {
query.append(RepositoryEntry.ACC_USERS);
}
}
final DBQuery dbquery = DBFactory.getInstance().createQuery(query.toString());
dbquery.setString("restrictedType", restrictedType);
dbquery.setCacheable(true);
return dbquery.list();
}
/**
* Query by type, limit by ownership or role accessability.
*
* @param restrictedType
* @param roles
* @return Results
*/
public List queryByTypeLimitAccess(final String restrictedType, final UserRequest ureq) {
final Roles roles = ureq.getUserSession().getRoles();
String institution = "";
institution = ureq.getIdentity().getUser().getProperty("institutionalName", null);
if (!roles.isOLATAdmin() && institution != null && institution.length() > 0 && roles.isInstitutionalResourceManager()) {
final StringBuilder query = new StringBuilder(400);
query.append("select distinct v from org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res"
+ ", org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi" + ", org.olat.basesecurity.IdentityImpl identity" + ", org.olat.user.UserImpl user "
+ " where sgmsi.securityGroup = v.ownerGroup" + " and sgmsi.identity = identity" + " and identity.user = user"
+ " and user.properties['institutionalName']= :institutionCourseManager " + " and res.resName= :restrictedType and v.access = 1");
final DBQuery dbquery = DBFactory.getInstance().createQuery(query.toString());
dbquery.setString("restrictedType", restrictedType);
dbquery.setString("institutionCourseManager", institution);
dbquery.setCacheable(true);
long start = System.currentTimeMillis();
final List result = dbquery.list();
final long timeQuery1 = System.currentTimeMillis() - start;
Tracing.logInfo("Repo-Perf: queryByTypeLimitAccess#3 takes " + timeQuery1, this.getClass());
start = System.currentTimeMillis();
result.addAll(queryByTypeLimitAccess(restrictedType, roles));
final long timeQuery2 = System.currentTimeMillis() - start;
Tracing.logInfo("Repo-Perf: queryByTypeLimitAccess#3 takes " + timeQuery2, this.getClass());
return result;
} else {
final long start = System.currentTimeMillis();
final List result = queryByTypeLimitAccess(restrictedType, roles);
final long timeQuery3 = System.currentTimeMillis() - start;
Tracing.logInfo("Repo-Perf: queryByTypeLimitAccess#3 takes " + timeQuery3, this.getClass());
return result;
}
}
/**
* Query by ownership, optionally limit by type.
*
* @param identity
* @param limitType
* @return Results
*/
public List queryByOwner(final Identity identity, final String limitType) {
return queryByOwner(identity, new String[] { limitType });
}
public List queryByOwner(final Identity identity, final String[] limitTypes) {
if (identity == null) { throw new AssertException("identity can not be null!"); }
final StringBuffer query = new StringBuffer(400);
query.append("select v from" + " org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res,"
+ " org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi" + " where " + " v.ownerGroup = sgmsi.securityGroup and" + " sgmsi.identity = :identity");
if (limitTypes != null && limitTypes.length > 0) {
for (int i = 0; i < limitTypes.length; i++) {
final String limitType = limitTypes[i];
if (i == 0) {
query.append(" and ( res.resName= '" + limitType + "'");
} else {
query.append(" or res.resName= '" + limitType + "'");
}
}
query.append(" )");
}
final DBQuery dbquery = DBFactory.getInstance().createQuery(query.toString());
dbquery.setEntity("identity", identity);
return dbquery.list();
}
/**
* Query by initial-author
*
* @param restrictedType
* @param roles
* @return Results
*/
public List queryByInitialAuthor(final String initialAuthor) {
final String query = "select v from" + " org.olat.repository.RepositoryEntry v" + " where v.initialAuthor= :initialAuthor";
final DBQuery dbquery = DBFactory.getInstance().createQuery(query);
dbquery.setString("initialAuthor", initialAuthor);
dbquery.setCacheable(true);
return dbquery.list();
}
/**
* Search for resources that can be referenced by an author. This is the case: 1) the user is the owner of the resource 2) the user is author and the resource is at
* least visible to authors (BA) and the resource is set to canReference
*
* @param identity The user initiating the query
* @param roles The current users role set
* @param resourceTypes Limit search result to this list of repo types. Can be NULL
* @param displayName Limit search to this repo title. Can be NULL
* @param author Limit search to this user (Name, firstname, loginname). Can be NULL
* @param desc Limit search to description. Can be NULL
* @return List of repository entries
*/
public List queryReferencableResourcesLimitType(final Identity identity, final Roles roles, List resourceTypes, String displayName, String author, String desc) {
if (identity == null) { throw new AssertException("identity can not be null!"); }
if (!roles.isAuthor()) {
// if user has no author right he can not reference to any resource at all
return new ArrayList();
}
// cleanup some data: use null values if emtpy
if (resourceTypes != null && resourceTypes.size() == 0) {
resourceTypes = null;
}
if (!StringHelper.containsNonWhitespace(displayName)) {
displayName = null;
}
if (!StringHelper.containsNonWhitespace(author)) {
author = null;
}
if (!StringHelper.containsNonWhitespace(desc)) {
desc = null;
}
// Build the query
// 1) Joining tables
final StringBuilder query = new StringBuilder(400);
query.append("select distinct v from");
query.append(" org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res");
query.append(", org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi");
if (author != null) {
query.append(", org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi2");
query.append(", org.olat.basesecurity.IdentityImpl identity");
query.append(", org.olat.user.UserImpl user ");
}
// 2) where clause
query.append(" where ");
// the join of v.ownerGropu and sgmsi.securityGroup mus be outside the sgmsi.identity = :identity
// otherwhise the join is not present in the second part of the or clause and the cross product will
// be to large (does not work when more than 100 repo entries present!)
query.append(" v.ownerGroup = sgmsi.securityGroup");
// restrict on ownership or referencability flag
query.append(" and ( sgmsi.identity = :identity ");
query.append(" or ");
query.append(" (v.access >= :access and v.canReference = true) )");
// restrict on type
if (resourceTypes != null) {
query.append(" and res.resName in (:resourcetypes)");
}
// restrict on author
if (author != null) { // fuzzy author search
author = author.replace('*', '%');
author = '%' + author + '%';
query.append(" and (sgmsi2.securityGroup = v.ownerGroup and " + "sgmsi2.identity = identity and " + "identity.user = user and "
+ "(user.properties['firstName'] like :author or user.properties['lastName'] like :author or identity.name like :author))");
}
// restrict on resource name
if (displayName != null) {
displayName = displayName.replace('*', '%');
displayName = '%' + displayName + '%';
query.append(" and v.displayname like :displayname");
}
// restrict on resource description
if (desc != null) {
desc = desc.replace('*', '%');
desc = '%' + desc + '%';
query.append(" and v.description like :desc");
}
// create query an set query data
final DBQuery dbquery = DBFactory.getInstance().createQuery(query.toString());
dbquery.setEntity("identity", identity);
dbquery.setInteger("access", RepositoryEntry.ACC_OWNERS_AUTHORS);
if (author != null) {
dbquery.setString("author", author);
}
if (displayName != null) {
dbquery.setString("displayname", displayName);
}
if (desc != null) {
dbquery.setString("desc", desc);
}
if (resourceTypes != null) {
dbquery.setParameterList("resourcetypes", resourceTypes, Hibernate.STRING);
}
return dbquery.list();
}
/**
* Query by ownership, limit by access.
*
* @param identity
* @param limitAccess
* @return Results
*/
public List queryByOwnerLimitAccess(final Identity identity, final int limitAccess) {
final String query = "select v from" + " org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res,"
+ " org.olat.basesecurity.SecurityGroupMembershipImpl as sgmsi" + " where" + " v.ownerGroup = sgmsi.securityGroup "
+ " and sgmsi.identity = :identity and v.access >= :limitAccess";
final DBQuery dbquery = DBFactory.getInstance().createQuery(query);
dbquery.setEntity("identity", identity);
dbquery.setInteger("limitAccess", limitAccess);
return dbquery.list();
}
/**
* check ownership of identiy for a resource
*
* @return true if the identity is member of the security group of the repository entry
*/
public boolean isOwnerOfRepositoryEntry(final Identity identity, final RepositoryEntry entry) {
// TODO:gs:a transform into direct hibernate query
final SecurityGroup ownerGroup = lookupRepositoryEntry(entry.getOlatResource(), true).getOwnerGroup();
return BaseSecurityManager.getInstance().isIdentityInSecurityGroup(identity, ownerGroup);
}
/**
* Query repository If any input data contains "*", then it replaced by "%" (search me*er -> sql: me%er)
*
* @param displayName null -> no restriction
* @param author null -> no restriction
* @param desc null -> no restriction
* @param resourceTypes NOTE: for null -> no restriction, or a list of resourceTypeNames
* @param roles The calling user's roles
* @return Results as List containing RepositoryEntries
*/
private List runGenericANDQueryWithRolesRestriction(String displayName, String author, String desc, final List resourceTypes, final Roles roles) {
final StringBuilder query = new StringBuilder(400);
final boolean var_author = (author != null && author.length() != 0);
final boolean var_displayname = (displayName != null && displayName.length() != 0);
final boolean var_desc = (desc != null && desc.length() != 0);
final boolean var_resourcetypes = (resourceTypes != null && resourceTypes.size() > 0);
// Use two different select prologues...
if (var_author) { // extended query for user search
query.append("select distinct v from" + " org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res,"
+ " org.olat.basesecurity.SecurityGroupMembershipImpl sgmsi, " + " org.olat.basesecurity.IdentityImpl identity," + " org.olat.user.UserImpl user ");
} else { // simple query
query.append("select distinct v from" + " org.olat.repository.RepositoryEntry v " + " inner join fetch v.olatResource as res ");
}
boolean isFirstOfWhereClause = false;
query.append("where v.access != 0 "); // access == 0 means invalid repo-entry (not complete created)
if (var_author) { // fuzzy author search
author = author.replace('*', '%');
author = '%' + author + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("sgmsi.securityGroup = v.ownerGroup and " + "sgmsi.identity = identity and " + "identity.user = user and "
+ "(user.properties['firstName'] like :author or user.properties['lastName'] like :author or identity.name like :author)");
isFirstOfWhereClause = false;
}
if (var_displayname) {
displayName = displayName.replace('*', '%');
displayName = '%' + displayName + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.displayname like :displayname");
isFirstOfWhereClause = false;
}
if (var_desc) {
desc = desc.replace('*', '%');
desc = '%' + desc + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.description like :desc");
isFirstOfWhereClause = false;
}
if (var_resourcetypes) {
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("res.resName in (:resourcetypes)");
isFirstOfWhereClause = false;
}
// finally limit on roles, if not olat admin
if (!roles.isOLATAdmin()) {
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.access >= ");
if (roles.isAuthor()) {
query.append(RepositoryEntry.ACC_OWNERS_AUTHORS);
} else if (roles.isGuestOnly()) {
query.append(RepositoryEntry.ACC_USERS_GUESTS);
} else {
query.append(RepositoryEntry.ACC_USERS);
}
isFirstOfWhereClause = false;
}
final DBQuery dbQuery = DBFactory.getInstance().createQuery(query.toString());
if (var_author) {
dbQuery.setString("author", author);
}
if (var_displayname) {
dbQuery.setString("displayname", displayName);
}
if (var_desc) {
dbQuery.setString("desc", desc);
}
if (var_resourcetypes) {
dbQuery.setParameterList("resourcetypes", resourceTypes, Hibernate.STRING);
}
return dbQuery.list();
}
/**
* Query repository If any input data contains "*", then it replaced by "%" (search me*er -> sql: me%er).
*
* @param ureq
* @param displayName null -> no restriction
* @param author null -> no restriction
* @param desc null -> no restriction
* @param resourceTypes NOTE: for null -> no restriction, or a list of resourceTypeNames
* @param roles The calling user's roles
* @param institution null -> no restriction
* @return Results as List containing RepositoryEntries
*/
public List genericANDQueryWithRolesRestriction(String displayName, String author, String desc, final List resourceTypes, final Roles roles, final String institution) {
if (!roles.isOLATAdmin() && institution != null && institution.length() > 0 && roles.isInstitutionalResourceManager()) {
final StringBuilder query = new StringBuilder(400);
if (author == null || author.length() == 0) {
author = "*";
}
final boolean var_author = true;
final boolean var_displayname = (displayName != null && displayName.length() != 0);
final boolean var_desc = (desc != null && desc.length() != 0);
final boolean var_resourcetypes = (resourceTypes != null && resourceTypes.size() > 0);
// Use two different select prologues...
if (var_author) { // extended query for user search
query.append("select distinct v from" + " org.olat.repository.RepositoryEntry v inner join fetch v.olatResource as res,"
+ " org.olat.basesecurity.SecurityGroupMembershipImpl sgmsi, " + " org.olat.basesecurity.IdentityImpl identity,"
+ " org.olat.user.UserImpl user ");
} else { // simple query
query.append("select distinct v from" + " org.olat.repository.RepositoryEntry v " + " inner join fetch v.olatResource as res ");
}
boolean isFirstOfWhereClause = false;
query.append("where v.access != 0 "); // access == 0 means invalid repo-entry (not complete created)
if (var_author) { // fuzzy author search
author = author.replace('*', '%');
author = '%' + author + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("sgmsi.securityGroup = v.ownerGroup and " + "sgmsi.identity = identity and " + "identity.user = user and "
+ "(user.properties['firstName'] like :author or user.properties['lastName'] like :author or identity.name like :author)");
isFirstOfWhereClause = false;
}
if (var_displayname) {
displayName = displayName.replace('*', '%');
displayName = '%' + displayName + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.displayname like :displayname");
isFirstOfWhereClause = false;
}
if (var_desc) {
desc = desc.replace('*', '%');
desc = '%' + desc + '%';
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.description like :desc");
isFirstOfWhereClause = false;
}
if (var_resourcetypes) {
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("res.resName in (:resourcetypes)");
isFirstOfWhereClause = false;
}
if (!isFirstOfWhereClause) {
query.append(" and ");
}
query.append("v.access = 1 and user.properties['institutionalName']= :institution ");
isFirstOfWhereClause = false;
final DBQuery dbQuery = DBFactory.getInstance().createQuery(query.toString());
dbQuery.setString("institution", institution);
if (var_author) {
dbQuery.setString("author", author);
}
if (var_displayname) {
dbQuery.setString("displayname", displayName);
}
if (var_desc) {
dbQuery.setString("desc", desc);
}
if (var_resourcetypes) {
dbQuery.setParameterList("resourcetypes", resourceTypes, Hibernate.STRING);
}
final List result = dbQuery.list();
result.addAll(runGenericANDQueryWithRolesRestriction(displayName, author, desc, resourceTypes, roles));
return result;
} else {
return runGenericANDQueryWithRolesRestriction(displayName, author, desc, resourceTypes, roles);
}
}
/**
* add provided list of identities as owners to the repo entry. silently ignore if some identities were already owners before.
*
* @param ureqIdentity
* @param addIdentities
* @param re
* @param userActivityLogger
*/
public void addOwners(final Identity ureqIdentity, final IdentitiesAddEvent iae, final RepositoryEntry re) {
final List<Identity> addIdentities = iae.getAddIdentities();
final List<Identity> reallyAddedId = new ArrayList<Identity>();
final SecurityGroup group = re.getOwnerGroup();
for (final Identity identity : addIdentities) {
if (!securityManager.isIdentityInSecurityGroup(identity, re.getOwnerGroup())) {
securityManager.addIdentityToSecurityGroup(identity, re.getOwnerGroup());
reallyAddedId.add(identity);
final ActionType actionType = ThreadLocalUserActivityLogger.getStickyActionType();
ThreadLocalUserActivityLogger.setStickyActionType(ActionType.admin);
try {
ThreadLocalUserActivityLogger.log(GroupLoggingAction.GROUP_OWNER_ADDED, getClass(), LoggingResourceable.wrap(re, OlatResourceableType.genRepoEntry),
LoggingResourceable.wrap(identity));
} finally {
ThreadLocalUserActivityLogger.setStickyActionType(actionType);
}
Tracing.logAudit("Idenitity(.key):" + ureqIdentity.getKey() + " added identity '" + identity.getName() + "' to securitygroup with key "
+ re.getOwnerGroup().getKey(), this.getClass());
}// else silently ignore already owner identities
}
iae.setIdentitiesAddedEvent(reallyAddedId);
}
/**
* remove list of identities as owners of given repository entry.
*
* @param ureqIdentity
* @param removeIdentities
* @param re
* @param logger
*/
public void removeOwners(final Identity ureqIdentity, final List<Identity> removeIdentities, final RepositoryEntry re) {
for (final Identity identity : removeIdentities) {
securityManager.removeIdentityFromSecurityGroup(identity, re.getOwnerGroup());
final String details = "Remove Owner from RepoEntry:" + re.getKey() + " USER:" + identity.getName();
final ActionType actionType = ThreadLocalUserActivityLogger.getStickyActionType();
ThreadLocalUserActivityLogger.setStickyActionType(ActionType.admin);
try {
ThreadLocalUserActivityLogger.log(GroupLoggingAction.GROUP_OWNER_REMOVED, getClass(), LoggingResourceable.wrap(re, OlatResourceableType.genRepoEntry),
LoggingResourceable.wrap(identity));
} finally {
ThreadLocalUserActivityLogger.setStickyActionType(actionType);
}
Tracing.logAudit("Idenitity(.key):" + ureqIdentity.getKey() + " removed identity '" + identity.getName() + "' from securitygroup with key "
+ re.getOwnerGroup().getKey(), this.getClass());
}
}
/**
* has one owner of repository entry the same institution like the resource manager
*
* @param RepositoryEntry repositoryEntry
* @param Identity identity
*/
public boolean isInstitutionalRessourceManagerFor(final RepositoryEntry repositoryEntry, final Identity identity) {
if (repositoryEntry == null || repositoryEntry.getOwnerGroup() == null) { return false; }
final BaseSecurity secMgr = BaseSecurityManager.getInstance();
// list of owners
final List<Identity> listIdentities = secMgr.getIdentitiesOfSecurityGroup(repositoryEntry.getOwnerGroup());
final String currentUserInstitutionalName = identity.getUser().getProperty("institutionalName", null);
final boolean isInstitutionalResourceManager = BaseSecurityManager.getInstance().isIdentityPermittedOnResourceable(identity, Constants.PERMISSION_HASROLE,
Constants.ORESOURCE_INSTORESMANAGER);
boolean sameInstitutional = false;
String identInstitutionalName = "";
for (final Identity ident : listIdentities) {
identInstitutionalName = ident.getUser().getProperty("institutionalName", null);
if ((identInstitutionalName != null) && (identInstitutionalName.equals(currentUserInstitutionalName))) {
sameInstitutional = true;
break;
}
}
return isInstitutionalResourceManager && sameInstitutional;
}
/**
* Gets all learning resources where the user is in a learning group as participant.
*
* @param identity
* @return list of RepositoryEntries
*/
public List<RepositoryEntry> getLearningResourcesAsStudent(final Identity identity) {
final List<RepositoryEntry> allRepoEntries = new ArrayList<RepositoryEntry>();
final List<BusinessGroup> groupList = BusinessGroupManagerImpl.getInstance().findBusinessGroupsAttendedBy(BusinessGroup.TYPE_LEARNINGROUP, identity, null);
for (final BusinessGroup group : groupList) {
final BGContext bgContext = group.getGroupContext();
if (bgContext == null) {
continue;
}
final List<RepositoryEntry> repoEntries = BGContextManagerImpl.getInstance().findRepositoryEntriesForBGContext(bgContext);
if (repoEntries == null || repoEntries.size() == 0) {
continue;
}
for (final RepositoryEntry repositoryEntry : repoEntries) {
// only find resources that are published
if (!PersistenceHelper.listContainsObjectByKey(allRepoEntries, repositoryEntry) && repositoryEntry.getAccess() >= RepositoryEntry.ACC_USERS) {
allRepoEntries.add(repositoryEntry);
}
}
}
return allRepoEntries;
}
/**
* Gets all learning resources where the user is coach of a learning group or where he is in a rights group or where he is in the repository entry owner group (course
* administrator)
*
* @param identity
* @return list of RepositoryEntries
*/
public List<RepositoryEntry> getLearningResourcesAsTeacher(final Identity identity) {
final List<RepositoryEntry> allRepoEntries = new ArrayList<RepositoryEntry>();
// 1: search for all learning groups where user is coach
final List<BusinessGroup> groupList = BusinessGroupManagerImpl.getInstance().findBusinessGroupsOwnedBy(BusinessGroup.TYPE_LEARNINGROUP, identity, null);
for (final BusinessGroup group : groupList) {
final BGContext bgContext = group.getGroupContext();
if (bgContext == null) {
continue;
}
final List<RepositoryEntry> repoEntries = BGContextManagerImpl.getInstance().findRepositoryEntriesForBGContext(bgContext);
if (repoEntries.size() == 0) {
continue;
}
for (final RepositoryEntry repositoryEntry : repoEntries) {
// only find resources that are published
if (!PersistenceHelper.listContainsObjectByKey(allRepoEntries, repositoryEntry) && repositoryEntry.getAccess() >= RepositoryEntry.ACC_USERS) {
allRepoEntries.add(repositoryEntry);
}
}
}
// 2: search for all learning groups where user is coach
final List<BusinessGroup> rightGrougList = BusinessGroupManagerImpl.getInstance().findBusinessGroupsAttendedBy(BusinessGroup.TYPE_RIGHTGROUP, identity, null);
for (final BusinessGroup group : rightGrougList) {
final BGContext bgContext = group.getGroupContext();
if (bgContext == null) {
continue;
}
final List<RepositoryEntry> repoEntries = BGContextManagerImpl.getInstance().findRepositoryEntriesForBGContext(bgContext);
if (repoEntries.size() == 0) {
continue;
}
for (final RepositoryEntry repositoryEntry : repoEntries) {
// only find resources that are published
if (!PersistenceHelper.listContainsObjectByKey(allRepoEntries, repositoryEntry) && repositoryEntry.getAccess() >= RepositoryEntry.ACC_USERS) {
allRepoEntries.add(repositoryEntry);
}
}
}
// 3) search for all published learning resources that user owns
final List<RepositoryEntry> repoEntries = RepositoryManager.getInstance().queryByOwnerLimitAccess(identity, RepositoryEntry.ACC_USERS);
for (final RepositoryEntry repositoryEntry : repoEntries) {
if (!PersistenceHelper.listContainsObjectByKey(allRepoEntries, repositoryEntry)) {
allRepoEntries.add(repositoryEntry);
}
}
return allRepoEntries;
}
} | RLDevOps/Demo | src/main/java/org/olat/repository/RepositoryManager.java | Java | apache-2.0 | 42,875 |
/*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.listener;
import gov.nasa.jpf.Config;
import gov.nasa.jpf.JPF;
import gov.nasa.jpf.ListenerAdapter;
import gov.nasa.jpf.jvm.bytecode.INVOKESPECIAL;
import gov.nasa.jpf.jvm.bytecode.JVMInvokeInstruction;
import gov.nasa.jpf.jvm.bytecode.VirtualInvocation;
import gov.nasa.jpf.search.Search;
import gov.nasa.jpf.vm.Instruction;
import gov.nasa.jpf.vm.VM;
import gov.nasa.jpf.vm.MethodInfo;
import gov.nasa.jpf.vm.ThreadInfo;
import java.io.PrintWriter;
/**
* simple tool to log stack invocations
*
* at this point, it doesn't do fancy things yet, but gives a more high
* level idea of what got executed by JPF than the ExecTracker
*/
public class StackTracker extends ListenerAdapter {
static final String INDENT = " ";
MethodInfo lastMi;
PrintWriter out;
long nextLog;
int logPeriod;
public StackTracker (Config conf, JPF jpf) {
out = new PrintWriter(System.out, true);
logPeriod = conf.getInt("jpf.stack_tracker.log_period", 5000);
}
void logStack(ThreadInfo ti) {
long time = System.currentTimeMillis();
if (time < nextLog) {
return;
}
nextLog = time + logPeriod;
out.println();
out.print("Thread: ");
out.print(ti.getId());
out.println(":");
out.println(ti.getStackTrace());
out.println();
}
@Override
public void executeInstruction (VM vm, ThreadInfo ti, Instruction insnToExecute) {
MethodInfo mi = insnToExecute.getMethodInfo();
if (mi != lastMi) {
logStack(ti);
lastMi = mi;
} else if (insnToExecute instanceof JVMInvokeInstruction) {
MethodInfo callee;
// that's the only little gist of it - if this is a VirtualInvocation,
// we have to dig the callee out by ourselves (it's not known
// before execution)
if (insnToExecute instanceof VirtualInvocation) {
VirtualInvocation callInsn = (VirtualInvocation)insnToExecute;
int objref = callInsn.getCalleeThis(ti);
callee = callInsn.getInvokedMethod(ti, objref);
} else if (insnToExecute instanceof INVOKESPECIAL) {
INVOKESPECIAL callInsn = (INVOKESPECIAL)insnToExecute;
callee = callInsn.getInvokedMethod(ti);
} else {
JVMInvokeInstruction callInsn = (JVMInvokeInstruction)insnToExecute;
callee = callInsn.getInvokedMethod(ti);
}
if (callee != null) {
if (callee.isMJI()) {
logStack(ti);
}
} else {
out.println("ERROR: unknown callee of: " + insnToExecute);
}
}
}
@Override
public void stateAdvanced(Search search) {
lastMi = null;
}
@Override
public void stateBacktracked(Search search) {
lastMi = null;
}
}
| grzesuav/jpf-core | src/main/gov/nasa/jpf/listener/StackTracker.java | Java | apache-2.0 | 3,479 |
from __future__ import absolute_import, print_function, unicode_literals
import json
import logging
import os
import sys
from abc import ABCMeta, abstractmethod
from argparse import ArgumentTypeError
from ast import literal_eval
from collections import OrderedDict
from textwrap import dedent
from ...six import add_metaclass
from ..discovery.cached_py_info import LogCmd
from ..info import WIN_CPYTHON_2
from ..util.path import Path, safe_delete
from ..util.six import ensure_str, ensure_text
from ..util.subprocess import run_cmd
from ..version import __version__
from .pyenv_cfg import PyEnvCfg
HERE = Path(os.path.abspath(__file__)).parent
DEBUG_SCRIPT = HERE / "debug.py"
class CreatorMeta(object):
def __init__(self):
self.error = None
@add_metaclass(ABCMeta)
class Creator(object):
"""A class that given a python Interpreter creates a virtual environment"""
def __init__(self, options, interpreter):
"""Construct a new virtual environment creator.
:param options: the CLI option as parsed from :meth:`add_parser_arguments`
:param interpreter: the interpreter to create virtual environment from
"""
self.interpreter = interpreter
self._debug = None
self.dest = Path(options.dest)
self.clear = options.clear
self.no_vcs_ignore = options.no_vcs_ignore
self.pyenv_cfg = PyEnvCfg.from_folder(self.dest)
self.app_data = options.app_data
self.env = options.env
def __repr__(self):
return ensure_str(self.__unicode__())
def __unicode__(self):
return "{}({})".format(self.__class__.__name__, ", ".join("{}={}".format(k, v) for k, v in self._args()))
def _args(self):
return [
("dest", ensure_text(str(self.dest))),
("clear", self.clear),
("no_vcs_ignore", self.no_vcs_ignore),
]
@classmethod
def can_create(cls, interpreter):
"""Determine if we can create a virtual environment.
:param interpreter: the interpreter in question
:return: ``None`` if we can't create, any other object otherwise that will be forwarded to \
:meth:`add_parser_arguments`
"""
return True
@classmethod
def add_parser_arguments(cls, parser, interpreter, meta, app_data):
"""Add CLI arguments for the creator.
:param parser: the CLI parser
:param app_data: the application data folder
:param interpreter: the interpreter we're asked to create virtual environment for
:param meta: value as returned by :meth:`can_create`
"""
parser.add_argument(
"dest",
help="directory to create virtualenv at",
type=cls.validate_dest,
)
parser.add_argument(
"--clear",
dest="clear",
action="store_true",
help="remove the destination directory if exist before starting (will overwrite files otherwise)",
default=False,
)
parser.add_argument(
"--no-vcs-ignore",
dest="no_vcs_ignore",
action="store_true",
help="don't create VCS ignore directive in the destination directory",
default=False,
)
@abstractmethod
def create(self):
"""Perform the virtual environment creation."""
raise NotImplementedError
@classmethod
def validate_dest(cls, raw_value):
"""No path separator in the path, valid chars and must be write-able"""
def non_write_able(dest, value):
common = Path(*os.path.commonprefix([value.parts, dest.parts]))
raise ArgumentTypeError(
"the destination {} is not write-able at {}".format(dest.relative_to(common), common),
)
# the file system must be able to encode
# note in newer CPython this is always utf-8 https://www.python.org/dev/peps/pep-0529/
encoding = sys.getfilesystemencoding()
refused = OrderedDict()
kwargs = {"errors": "ignore"} if encoding != "mbcs" else {}
for char in ensure_text(raw_value):
try:
trip = char.encode(encoding, **kwargs).decode(encoding)
if trip == char:
continue
raise ValueError(trip)
except ValueError:
refused[char] = None
if refused:
raise ArgumentTypeError(
"the file system codec ({}) cannot handle characters {!r} within {!r}".format(
encoding,
"".join(refused.keys()),
raw_value,
),
)
if os.pathsep in raw_value:
raise ArgumentTypeError(
"destination {!r} must not contain the path separator ({}) as this would break "
"the activation scripts".format(raw_value, os.pathsep),
)
value = Path(raw_value)
if value.exists() and value.is_file():
raise ArgumentTypeError("the destination {} already exists and is a file".format(value))
if (3, 3) <= sys.version_info <= (3, 6):
# pre 3.6 resolve is always strict, aka must exists, sidestep by using os.path operation
dest = Path(os.path.realpath(raw_value))
else:
dest = Path(os.path.abspath(str(value))).resolve() # on Windows absolute does not imply resolve so use both
value = dest
while dest:
if dest.exists():
if os.access(ensure_text(str(dest)), os.W_OK):
break
else:
non_write_able(dest, value)
base, _ = dest.parent, dest.name
if base == dest:
non_write_able(dest, value) # pragma: no cover
dest = base
return str(value)
def run(self):
if self.dest.exists() and self.clear:
logging.debug("delete %s", self.dest)
safe_delete(self.dest)
self.create()
self.set_pyenv_cfg()
if not self.no_vcs_ignore:
self.setup_ignore_vcs()
def set_pyenv_cfg(self):
self.pyenv_cfg.content = OrderedDict()
self.pyenv_cfg["home"] = self.interpreter.system_exec_prefix
self.pyenv_cfg["implementation"] = self.interpreter.implementation
self.pyenv_cfg["version_info"] = ".".join(str(i) for i in self.interpreter.version_info)
self.pyenv_cfg["virtualenv"] = __version__
def setup_ignore_vcs(self):
"""Generate ignore instructions for version control systems."""
# mark this folder to be ignored by VCS, handle https://www.python.org/dev/peps/pep-0610/#registered-vcs
git_ignore = self.dest / ".gitignore"
if not git_ignore.exists():
git_ignore.write_text(
dedent(
"""
# created by virtualenv automatically
*
""",
).lstrip(),
)
# Mercurial - does not support the .hgignore file inside a subdirectory directly, but only if included via the
# subinclude directive from root, at which point on might as well ignore the directory itself, see
# https://www.selenic.com/mercurial/hgignore.5.html for more details
# Bazaar - does not support ignore files in sub-directories, only at root level via .bzrignore
# Subversion - does not support ignore files, requires direct manipulation with the svn tool
@property
def debug(self):
"""
:return: debug information about the virtual environment (only valid after :meth:`create` has run)
"""
if self._debug is None and self.exe is not None:
self._debug = get_env_debug_info(self.exe, self.debug_script(), self.app_data, self.env)
return self._debug
# noinspection PyMethodMayBeStatic
def debug_script(self):
return DEBUG_SCRIPT
def get_env_debug_info(env_exe, debug_script, app_data, env):
env = env.copy()
env.pop(str("PYTHONPATH"), None)
with app_data.ensure_extracted(debug_script) as debug_script:
cmd = [str(env_exe), str(debug_script)]
if WIN_CPYTHON_2:
cmd = [ensure_text(i) for i in cmd]
logging.debug(str("debug via %r"), LogCmd(cmd))
code, out, err = run_cmd(cmd)
# noinspection PyBroadException
try:
if code != 0:
result = literal_eval(out)
else:
result = json.loads(out)
if err:
result["err"] = err
except Exception as exception:
return {"out": out, "err": err, "returncode": code, "exception": repr(exception)}
if "sys" in result and "path" in result["sys"]:
del result["sys"]["path"][0]
return result
| pybuilder/pybuilder | src/main/python/pybuilder/_vendor/virtualenv/create/creator.py | Python | apache-2.0 | 8,877 |
//
// StructureReader.cs
//
// Author:
// Jb Evain ([email protected])
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using System.IO;
using Mono.Cecil.Binary;
using Mono.Cecil.Metadata;
internal sealed class StructureReader : BaseStructureVisitor {
ImageReader m_ir;
Image m_img;
bool m_manifestOnly;
AssemblyDefinition m_asmDef;
ModuleDefinition m_module;
MetadataStreamCollection m_streams;
TablesHeap m_tHeap;
MetadataTableReader m_tableReader;
public bool ManifestOnly {
get { return m_manifestOnly; }
}
public ImageReader ImageReader {
get { return m_ir; }
}
public Image Image {
get { return m_img; }
}
public StructureReader (ImageReader ir)
{
m_ir = ir;
m_img = ir.Image;
m_streams = m_img.MetadataRoot.Streams;
m_tHeap = m_streams.TablesHeap;
m_tableReader = ir.MetadataReader.TableReader;
}
public StructureReader (ImageReader ir, bool manifestOnly) : this (ir)
{
m_manifestOnly = manifestOnly;
}
byte [] ReadBlob (uint pointer)
{
if (pointer == 0)
return new byte [0];
return m_streams.BlobHeap.Read (pointer);
}
string ReadString (uint pointer)
{
return m_streams.StringsHeap [pointer];
}
public override void VisitAssemblyDefinition (AssemblyDefinition asm)
{
if (!m_tHeap.HasTable (AssemblyTable.RId))
throw new ReflectionException ("No assembly manifest");
asm.MetadataToken = new MetadataToken (TokenType.Assembly, 1);
m_asmDef = asm;
switch (m_img.MetadataRoot.Header.Version) {
case "v1.0.3705" :
asm.Runtime = TargetRuntime.NET_1_0;
break;
case "v1.1.4322" :
asm.Runtime = TargetRuntime.NET_1_1;
break;
default :
asm.Runtime = TargetRuntime.NET_2_0;
break;
}
if ((m_img.PEFileHeader.Characteristics & ImageCharacteristics.Dll) != 0)
asm.Kind = AssemblyKind.Dll;
else if (m_img.PEOptionalHeader.NTSpecificFields.SubSystem == SubSystem.WindowsGui ||
m_img.PEOptionalHeader.NTSpecificFields.SubSystem == SubSystem.WindowsCeGui)
asm.Kind = AssemblyKind.Windows;
else
asm.Kind = AssemblyKind.Console;
}
public override void VisitAssemblyNameDefinition (AssemblyNameDefinition name)
{
AssemblyTable atable = m_tableReader.GetAssemblyTable ();
AssemblyRow arow = atable [0];
name.Name = ReadString (arow.Name);
name.Flags = arow.Flags;
name.PublicKey = ReadBlob (arow.PublicKey);
name.Culture = ReadString (arow.Culture);
name.Version = new Version (
arow.MajorVersion, arow.MinorVersion,
arow.BuildNumber, arow.RevisionNumber);
name.HashAlgorithm = arow.HashAlgId;
name.MetadataToken = new MetadataToken (TokenType.Assembly, 1);
}
public override void VisitAssemblyNameReferenceCollection (AssemblyNameReferenceCollection names)
{
if (!m_tHeap.HasTable (AssemblyRefTable.RId))
return;
AssemblyRefTable arTable = m_tableReader.GetAssemblyRefTable ();
for (int i = 0; i < arTable.Rows.Count; i++) {
AssemblyRefRow arRow = arTable [i];
AssemblyNameReference aname = new AssemblyNameReference (
ReadString (arRow.Name),
ReadString (arRow.Culture),
new Version (arRow.MajorVersion, arRow.MinorVersion,
arRow.BuildNumber, arRow.RevisionNumber));
aname.PublicKeyToken = ReadBlob (arRow.PublicKeyOrToken);
aname.Hash = ReadBlob (arRow.HashValue);
aname.MetadataToken = new MetadataToken (TokenType.AssemblyRef, (uint) i + 1);
names.Add (aname);
}
}
public override void VisitResourceCollection (ResourceCollection resources)
{
if (!m_tHeap.HasTable (ManifestResourceTable.RId))
return;
ManifestResourceTable mrTable = m_tableReader.GetManifestResourceTable ();
FileTable fTable = m_tableReader.GetFileTable ();
for (int i = 0; i < mrTable.Rows.Count; i++) {
ManifestResourceRow mrRow = mrTable [i];
if (mrRow.Implementation.RID == 0) {
EmbeddedResource eres = new EmbeddedResource (
ReadString (mrRow.Name), mrRow.Flags);
BinaryReader br = m_ir.MetadataReader.GetDataReader (
m_img.CLIHeader.Resources.VirtualAddress);
br.BaseStream.Position += mrRow.Offset;
eres.Data = br.ReadBytes (br.ReadInt32 ());
resources.Add (eres);
continue;
}
switch (mrRow.Implementation.TokenType) {
case TokenType.File :
FileRow fRow = fTable [(int) mrRow.Implementation.RID - 1];
LinkedResource lres = new LinkedResource (
ReadString (mrRow.Name), mrRow.Flags,
ReadString (fRow.Name));
lres.Hash = ReadBlob (fRow.HashValue);
resources.Add (lres);
break;
case TokenType.AssemblyRef :
AssemblyNameReference asm =
m_module.AssemblyReferences [(int) mrRow.Implementation.RID - 1];
AssemblyLinkedResource alr = new AssemblyLinkedResource (
ReadString (mrRow.Name),
mrRow.Flags, asm);
resources.Add (alr);
break;
}
}
}
public override void VisitModuleDefinitionCollection (ModuleDefinitionCollection modules)
{
ModuleTable mt = m_tableReader.GetModuleTable ();
if (mt == null || mt.Rows.Count != 1)
throw new ReflectionException ("Can not read main module");
ModuleRow mr = mt [0];
string name = ReadString (mr.Name);
ModuleDefinition main = new ModuleDefinition (name, m_asmDef, this, true);
main.Mvid = m_streams.GuidHeap [mr.Mvid];
main.MetadataToken = new MetadataToken (TokenType.Module, 1);
modules.Add (main);
m_module = main;
m_module.Accept (this);
FileTable ftable = m_tableReader.GetFileTable ();
if (ftable == null || ftable.Rows.Count == 0)
return;
foreach (FileRow frow in ftable.Rows) {
if (frow.Flags != FileAttributes.ContainsMetaData)
continue;
name = ReadString (frow.Name);
FileInfo location = new FileInfo (
m_img.FileInformation != null ? Path.Combine (m_img.FileInformation.DirectoryName, name) : name);
if (!File.Exists (location.FullName))
throw new FileNotFoundException ("Module not found : " + name);
try {
ImageReader module = ImageReader.Read (location.FullName);
mt = module.Image.MetadataRoot.Streams.TablesHeap [ModuleTable.RId] as ModuleTable;
if (mt == null || mt.Rows.Count != 1)
throw new ReflectionException ("Can not read module : " + name);
mr = mt [0];
ModuleDefinition modext = new ModuleDefinition (name, m_asmDef,
new StructureReader (module, m_manifestOnly), false);
modext.Mvid = module.Image.MetadataRoot.Streams.GuidHeap [mr.Mvid];
modules.Add (modext);
modext.Accept (this);
} catch (ReflectionException) {
throw;
} catch (Exception e) {
throw new ReflectionException ("Can not read module : " + name, e);
}
}
}
public override void VisitModuleReferenceCollection (ModuleReferenceCollection modules)
{
if (!m_tHeap.HasTable (ModuleRefTable.RId))
return;
ModuleRefTable mrTable = m_tableReader.GetModuleRefTable ();
for (int i = 0; i < mrTable.Rows.Count; i++) {
ModuleRefRow mrRow = mrTable [i];
ModuleReference mod = new ModuleReference (ReadString (mrRow.Name));
mod.MetadataToken = new MetadataToken (TokenType.ModuleRef, (uint) i + 1);
modules.Add (mod);
}
}
public override void TerminateAssemblyDefinition (AssemblyDefinition asm)
{
if (m_manifestOnly)
return;
foreach (ModuleDefinition mod in asm.Modules)
mod.Controller.Reader.VisitModuleDefinition (mod);
}
}
}
| liyuanlin/DecompileMe | DecompileMe/Obfuscation2/CECIL/Mono.Cecil/StructureReader.cs | C# | apache-2.0 | 8,522 |
// Copyright 2014 Google Inc. All rights reserved.
//
// 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 platform
/*
#include "kvm_run.h"
*/
import "C"
import (
"novmm/utils"
"sync"
"syscall"
)
type RunInfo struct {
// C-level nformation.
info C.struct_kvm_run_info
// Are we running?
is_running bool
// Are we paused manually?
is_paused bool
// Our internal pause count.
// This is for internal services that may need
// to pause vcpus (such as suspend/resume), and
// is tracked independently of the manual pause.
paused int
// Our run lock.
lock *sync.Mutex
pause_event *sync.Cond
resume_event *sync.Cond
}
func (vcpu *Vcpu) initRunInfo() error {
// Initialize our structure.
e := syscall.Errno(C.kvm_run_init(C.int(vcpu.fd), &vcpu.RunInfo.info))
if e != 0 {
return e
}
// Setup the lock.
vcpu.RunInfo.lock = &sync.Mutex{}
vcpu.RunInfo.pause_event = sync.NewCond(vcpu.RunInfo.lock)
vcpu.RunInfo.resume_event = sync.NewCond(vcpu.RunInfo.lock)
// We're okay.
return nil
}
func (vcpu *Vcpu) Run() error {
for {
// Make sure our registers are flushed.
// This will also refresh registers after we
// execute but are interrupted (i.e. EINTR).
err := vcpu.flushAllRegs()
if err != nil {
return err
}
// Ensure we can run.
//
// For exact semantics, see Pause() and Unpause().
// NOTE: By default, we are always "running". We are
// only not running when we arrive at this point in
// the pipeline and are waiting on the resume_event.
//
// This is because we want to ensure that our registers
// have been flushed and all that devices are up-to-date
// before we can declare a VCPU as "paused".
vcpu.RunInfo.lock.Lock()
for vcpu.RunInfo.is_paused || vcpu.RunInfo.paused > 0 {
// Note that we are not running,
// See NOTE above about what this means.
vcpu.RunInfo.is_running = false
// Send a notification that we are paused.
vcpu.RunInfo.pause_event.Broadcast()
// Wait for a wakeup notification.
vcpu.RunInfo.resume_event.Wait()
}
vcpu.RunInfo.is_running = true
vcpu.RunInfo.lock.Unlock()
// Execute our run ioctl.
rc := C.kvm_run(
C.int(vcpu.fd),
C.int(utils.SigVcpuInt),
&vcpu.RunInfo.info)
e := syscall.Errno(rc)
if e == syscall.EINTR || e == syscall.EAGAIN {
continue
} else if e != 0 {
return e
} else {
break
}
}
return vcpu.GetExitError()
}
func (vcpu *Vcpu) Pause(manual bool) error {
// Acquire our runlock.
vcpu.RunInfo.lock.Lock()
defer vcpu.RunInfo.lock.Unlock()
if manual {
// Already paused?
if vcpu.RunInfo.is_paused {
return AlreadyPaused
}
vcpu.RunInfo.is_paused = true
} else {
// Bump our pause count.
vcpu.RunInfo.paused += 1
}
// Are we running? Need to interrupt.
// We don't return from this function (even if there
// are multiple callers) until we are sure that the VCPU
// is actually paused, and all devices are up-to-date.
if vcpu.is_running {
// Only the first caller need interrupt.
if manual || vcpu.RunInfo.paused == 1 {
e := C.kvm_run_interrupt(
C.int(vcpu.fd),
C.int(utils.SigVcpuInt),
&vcpu.RunInfo.info)
if e != 0 {
return syscall.Errno(e)
}
}
// Wait for the vcpu to notify that it is paused.
vcpu.RunInfo.pause_event.Wait()
}
return nil
}
func (vcpu *Vcpu) Unpause(manual bool) error {
// Acquire our runlock.
vcpu.RunInfo.lock.Lock()
defer vcpu.RunInfo.lock.Unlock()
// Are we actually paused?
// This was not a valid call.
if manual {
// Already unpaused?
if !vcpu.RunInfo.is_paused {
return NotPaused
}
vcpu.RunInfo.is_paused = false
} else {
if vcpu.RunInfo.paused == 0 {
return NotPaused
}
// Decrease our pause count.
vcpu.RunInfo.paused -= 1
}
// Are we still paused?
if vcpu.RunInfo.is_paused || vcpu.RunInfo.paused > 0 {
return nil
}
// Allow the vcpu to resume.
vcpu.RunInfo.resume_event.Broadcast()
return nil
}
| nathanaelle/novm | src/novmm/platform/kvm_run.go | GO | apache-2.0 | 4,443 |
package org.elasticsearch.kafka.indexer.service;
import java.net.InetSocketAddress;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.kafka.indexer.exception.IndexerESNotRecoverableException;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* Created by dhyan on 8/31/15.
*/
// TODO convert to a singleton Spring ES service when ready
@Service
public class ElasticSearchClientService {
private static final Logger logger = LoggerFactory.getLogger(ElasticSearchClientService.class);
public static final String CLUSTER_NAME = "cluster.name";
@Value("${elasticsearch.cluster.name:elasticsearch}")
private String esClusterName;
@Value("#{'${elasticsearch.hosts.list:localhost:9300}'.split(',')}")
private List<String> esHostPortList;
// sleep time in ms between attempts to index data into ES again
@Value("${elasticsearch.indexing.retry.sleep.ms:10000}")
private int esIndexingRetrySleepTimeMs;
// number of times to try to index data into ES if ES cluster is not reachable
@Value("${elasticsearch.indexing.retry.attempts:2}")
private int numberOfEsIndexingRetryAttempts;
// TODO add when we can inject partition number into each bean
//private int currentPartition;
private TransportClient esTransportClient;
@PostConstruct
public void init() throws Exception {
logger.info("Initializing ElasticSearchClient ...");
// connect to elasticsearch cluster
Settings settings = Settings.builder().put(CLUSTER_NAME, esClusterName).build();
try {
//new PreBuiltTransportClient(
esTransportClient = new PreBuiltTransportClient(settings);
for (String eachHostPort : esHostPortList) {
logger.info("adding [{}] to TransportClient ... ", eachHostPort);
String[] hostPortTokens = eachHostPort.split(":");
if (hostPortTokens.length < 2)
throw new Exception("ERROR: bad ElasticSearch host:port configuration - wrong format: " +
eachHostPort);
int port = 9300; // default ES port
try {
port = Integer.parseInt(hostPortTokens[1].trim());
} catch (Throwable e){
logger.error("ERROR parsing port from the ES config [{}]- using default port 9300", eachHostPort);
}
esTransportClient.addTransportAddress(new TransportAddress(
new InetSocketAddress(hostPortTokens[0].trim(), port)));
}
logger.info("ElasticSearch Client created and intialized OK");
} catch (Exception e) {
logger.error("Exception trying to connect and create ElasticSearch Client: "+ e.getMessage());
throw e;
}
}
@PreDestroy
public void cleanup() throws Exception {
//logger.info("About to stop ES client for partition={} ...", currentPartition);
logger.info("About to stop ES client ...");
if (esTransportClient != null)
esTransportClient.close();
}
public void reInitElasticSearch() throws InterruptedException, IndexerESNotRecoverableException {
for (int i=1; i<=numberOfEsIndexingRetryAttempts; i++ ){
Thread.sleep(esIndexingRetrySleepTimeMs);
logger.warn("Re-trying to connect to ES, try# {} out of {}", i, numberOfEsIndexingRetryAttempts);
try {
init();
// we succeeded - get out of the loop
return;
} catch (Exception e) {
if (i<numberOfEsIndexingRetryAttempts){
//logger.warn("Re-trying to connect to ES, partition {}, try# {} - failed again: {}",
// currentPartition, i, e.getMessage());
logger.warn("Re-trying to connect to ES, try# {} - failed again: {}",
i, e.getMessage());
} else {
//we've exhausted the number of retries - throw a IndexerESException to stop the IndexerJob thread
//logger.error("Re-trying connect to ES, partition {}, "
// + "try# {} - failed after the last retry; Will keep retrying ", currentPartition, i);
logger.error("Re-trying connect to ES, try# {} - failed after the last retry", i);
//throw new IndexerESException("ERROR: failed to connect to ES after max number of retiries, partition: " +
// currentPartition);
throw new IndexerESNotRecoverableException("ERROR: failed to connect to ES after max number of retries: " + numberOfEsIndexingRetryAttempts);
}
}
}
}
public void deleteIndex(String index) {
esTransportClient.admin().indices().prepareDelete(index).execute().actionGet();
logger.info("Delete index {} successfully", index);
}
public void createIndex(String indexName){
esTransportClient.admin().indices().prepareCreate(indexName).execute().actionGet();
logger.info("Created index {} successfully", indexName);
}
public void createIndexAndAlias(String indexName,String aliasName){
esTransportClient.admin().indices().prepareCreate(indexName).addAlias(new Alias(aliasName)).execute().actionGet();
logger.info("Created index {} with alias {} successfully" ,indexName,aliasName);
}
public void addAliasToExistingIndex(String indexName, String aliasName) {
esTransportClient.admin().indices().prepareAliases().addAlias(indexName, aliasName).execute().actionGet();
logger.info("Added alias {} to index {} successfully" ,aliasName,indexName);
}
public void addAliasWithRoutingToExistingIndex(String indexName, String aliasName, String field, String fieldValue) {
esTransportClient.admin().indices().prepareAliases().addAlias(indexName, aliasName, QueryBuilders.termQuery(field, fieldValue)).execute().actionGet();
logger.info("Added alias {} to index {} successfully" ,aliasName,indexName);
}
public IndexRequestBuilder prepareIndex(String indexName, String indexType, String eventUUID) {
return esTransportClient.prepareIndex(indexName, indexType, eventUUID);
}
public IndexRequestBuilder prepareIndex(String indexName, String indexType) {
return esTransportClient.prepareIndex(indexName, indexType);
}
public BulkRequestBuilder prepareBulk() {
return esTransportClient.prepareBulk();
}
public TransportClient getEsTransportClient() {
return esTransportClient;
}
}
| ppine7/kafka-elasticsearch-standalone-consumer | src/main/java/org/elasticsearch/kafka/indexer/service/ElasticSearchClientService.java | Java | apache-2.0 | 6,855 |
// Copyright 2018-2019 opcua authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
// Code generated by cmd/service. DO NOT EDIT!
package ua
import "time"
type Request interface {
Header() *RequestHeader
SetHeader(*RequestHeader)
}
type Response interface {
Header() *ResponseHeader
SetHeader(*ResponseHeader)
}
type KeyValuePair struct {
Key *QualifiedName
Value *Variant
}
type AdditionalParametersType struct {
Parameters []*KeyValuePair
}
type EphemeralKeyType struct {
PublicKey []byte
Signature []byte
}
type EndpointType struct {
EndpointURL string
SecurityMode MessageSecurityMode
SecurityPolicyURI string
TransportProfileURI string
}
type IdentityMappingRuleType struct {
CriteriaType IdentityCriteriaType
Criteria string
}
type TrustListDataType struct {
SpecifiedLists uint32
TrustedCertificates [][]byte
TrustedCrls [][]byte
IssuerCertificates [][]byte
IssuerCrls [][]byte
}
type DecimalDataType struct {
Scale int16
Value []byte
}
type DataTypeSchemaHeader struct {
Namespaces []string
StructureDataTypes []*StructureDescription
EnumDataTypes []*EnumDescription
SimpleDataTypes []*SimpleTypeDescription
}
type DataTypeDescription struct {
DataTypeID *NodeID
Name *QualifiedName
}
type StructureDescription struct {
DataTypeID *NodeID
Name *QualifiedName
StructureDefinition *StructureDefinition
}
type EnumDescription struct {
DataTypeID *NodeID
Name *QualifiedName
EnumDefinition *EnumDefinition
BuiltInType uint8
}
type SimpleTypeDescription struct {
DataTypeID *NodeID
Name *QualifiedName
BaseDataType *NodeID
BuiltInType uint8
}
type UABinaryFileDataType struct {
Namespaces []string
StructureDataTypes []*StructureDescription
EnumDataTypes []*EnumDescription
SimpleDataTypes []*SimpleTypeDescription
SchemaLocation string
FileHeader []*KeyValuePair
Body *Variant
}
type DataSetMetaDataType struct {
Namespaces []string
StructureDataTypes []*StructureDescription
EnumDataTypes []*EnumDescription
SimpleDataTypes []*SimpleTypeDescription
Name string
Description *LocalizedText
Fields []*FieldMetaData
DataSetClassID *GUID
ConfigurationVersion *ConfigurationVersionDataType
}
type FieldMetaData struct {
Name string
Description *LocalizedText
FieldFlags DataSetFieldFlags
BuiltInType uint8
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
MaxStringLength uint32
DataSetFieldID *GUID
Properties []*KeyValuePair
}
type ConfigurationVersionDataType struct {
MajorVersion uint32
MinorVersion uint32
}
type PublishedDataSetDataType struct {
Name string
DataSetFolder []string
DataSetMetaData *DataSetMetaDataType
ExtensionFields []*KeyValuePair
DataSetSource *ExtensionObject
}
type PublishedVariableDataType struct {
PublishedVariable *NodeID
AttributeID AttributeID
SamplingIntervalHint float64
DeadbandType uint32
DeadbandValue float64
IndexRange string
SubstituteValue *Variant
MetaDataProperties []*QualifiedName
}
type PublishedDataItemsDataType struct {
PublishedData []*PublishedVariableDataType
}
type PublishedEventsDataType struct {
EventNotifier *NodeID
SelectedFields []*SimpleAttributeOperand
Filter *ContentFilter
}
type DataSetWriterDataType struct {
Name string
Enabled bool
DataSetWriterID uint16
DataSetFieldContentMask DataSetFieldContentMask
KeyFrameCount uint32
DataSetName string
DataSetWriterProperties []*KeyValuePair
TransportSettings *ExtensionObject
MessageSettings *ExtensionObject
}
type PubSubGroupDataType struct {
Name string
Enabled bool
SecurityMode MessageSecurityMode
SecurityGroupID string
SecurityKeyServices []*EndpointDescription
MaxNetworkMessageSize uint32
GroupProperties []*KeyValuePair
}
type WriterGroupDataType struct {
Name string
Enabled bool
SecurityMode MessageSecurityMode
SecurityGroupID string
SecurityKeyServices []*EndpointDescription
MaxNetworkMessageSize uint32
GroupProperties []*KeyValuePair
WriterGroupID uint16
PublishingInterval float64
KeepAliveTime float64
Priority uint8
LocaleIDs []string
HeaderLayoutURI string
TransportSettings *ExtensionObject
MessageSettings *ExtensionObject
DataSetWriters []*DataSetWriterDataType
}
type PubSubConnectionDataType struct {
Name string
Enabled bool
PublisherID *Variant
TransportProfileURI string
Address *ExtensionObject
ConnectionProperties []*KeyValuePair
TransportSettings *ExtensionObject
WriterGroups []*WriterGroupDataType
ReaderGroups []*ReaderGroupDataType
}
type NetworkAddressDataType struct {
NetworkInterface string
}
type NetworkAddressURLDataType struct {
NetworkInterface string
URL string
}
type ReaderGroupDataType struct {
Name string
Enabled bool
SecurityMode MessageSecurityMode
SecurityGroupID string
SecurityKeyServices []*EndpointDescription
MaxNetworkMessageSize uint32
GroupProperties []*KeyValuePair
TransportSettings *ExtensionObject
MessageSettings *ExtensionObject
DataSetReaders []*DataSetReaderDataType
}
type DataSetReaderDataType struct {
Name string
Enabled bool
PublisherID *Variant
WriterGroupID uint16
DataSetWriterID uint16
DataSetMetaData *DataSetMetaDataType
DataSetFieldContentMask DataSetFieldContentMask
MessageReceiveTimeout float64
KeyFrameCount uint32
HeaderLayoutURI string
SecurityMode MessageSecurityMode
SecurityGroupID string
SecurityKeyServices []*EndpointDescription
DataSetReaderProperties []*KeyValuePair
TransportSettings *ExtensionObject
MessageSettings *ExtensionObject
SubscribedDataSet *ExtensionObject
}
type TargetVariablesDataType struct {
TargetVariables []*FieldTargetDataType
}
type FieldTargetDataType struct {
DataSetFieldID *GUID
ReceiverIndexRange string
TargetNodeID *NodeID
AttributeID AttributeID
WriteIndexRange string
OverrideValueHandling OverrideValueHandling
OverrideValue *Variant
}
type SubscribedDataSetMirrorDataType struct {
ParentNodeName string
RolePermissions []*RolePermissionType
}
type PubSubConfigurationDataType struct {
PublishedDataSets []*PublishedDataSetDataType
Connections []*PubSubConnectionDataType
Enabled bool
}
type UADPWriterGroupMessageDataType struct {
GroupVersion uint32
DataSetOrdering DataSetOrderingType
NetworkMessageContentMask UADPNetworkMessageContentMask
SamplingOffset float64
PublishingOffset []float64
}
type UADPDataSetWriterMessageDataType struct {
DataSetMessageContentMask UADPDataSetMessageContentMask
ConfiguredSize uint16
NetworkMessageNumber uint16
DataSetOffset uint16
}
type UADPDataSetReaderMessageDataType struct {
GroupVersion uint32
NetworkMessageNumber uint16
DataSetOffset uint16
DataSetClassID *GUID
NetworkMessageContentMask UADPNetworkMessageContentMask
DataSetMessageContentMask UADPDataSetMessageContentMask
PublishingInterval float64
ReceiveOffset float64
ProcessingOffset float64
}
type JSONWriterGroupMessageDataType struct {
NetworkMessageContentMask JSONNetworkMessageContentMask
}
type JSONDataSetWriterMessageDataType struct {
DataSetMessageContentMask JSONDataSetMessageContentMask
}
type JSONDataSetReaderMessageDataType struct {
NetworkMessageContentMask JSONNetworkMessageContentMask
DataSetMessageContentMask JSONDataSetMessageContentMask
}
type DatagramConnectionTransportDataType struct {
DiscoveryAddress *ExtensionObject
}
type DatagramWriterGroupTransportDataType struct {
MessageRepeatCount uint8
MessageRepeatDelay float64
}
type BrokerConnectionTransportDataType struct {
ResourceURI string
AuthenticationProfileURI string
}
type BrokerWriterGroupTransportDataType struct {
QueueName string
ResourceURI string
AuthenticationProfileURI string
RequestedDeliveryGuarantee BrokerTransportQoS
}
type BrokerDataSetWriterTransportDataType struct {
QueueName string
ResourceURI string
AuthenticationProfileURI string
RequestedDeliveryGuarantee BrokerTransportQoS
MetaDataQueueName string
MetaDataUpdateTime float64
}
type BrokerDataSetReaderTransportDataType struct {
QueueName string
ResourceURI string
AuthenticationProfileURI string
RequestedDeliveryGuarantee BrokerTransportQoS
MetaDataQueueName string
}
type RolePermissionType struct {
RoleID *NodeID
Permissions PermissionType
}
type StructureField struct {
Name string
Description *LocalizedText
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
MaxStringLength uint32
IsOptional bool
}
type StructureDefinition struct {
DefaultEncodingID *NodeID
BaseDataType *NodeID
StructureType StructureType
Fields []*StructureField
}
type EnumDefinition struct {
Fields []*EnumField
}
type Node struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
}
type InstanceNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
}
type TypeNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
}
type ObjectNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
EventNotifier uint8
}
type ObjectTypeNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
IsAbstract bool
}
type VariableNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
Value *Variant
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
AccessLevel uint8
UserAccessLevel uint8
MinimumSamplingInterval float64
Historizing bool
AccessLevelEx uint32
}
type VariableTypeNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
Value *Variant
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
IsAbstract bool
}
type ReferenceTypeNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
IsAbstract bool
Symmetric bool
InverseName *LocalizedText
}
type MethodNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
Executable bool
UserExecutable bool
}
type ViewNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
ContainsNoLoops bool
EventNotifier uint8
}
type DataTypeNode struct {
NodeID *NodeID
NodeClass NodeClass
BrowseName *QualifiedName
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
RolePermissions []*RolePermissionType
UserRolePermissions []*RolePermissionType
AccessRestrictions uint16
References []*ReferenceNode
IsAbstract bool
DataTypeDefinition *ExtensionObject
}
type ReferenceNode struct {
ReferenceTypeID *NodeID
IsInverse bool
TargetID *ExpandedNodeID
}
type Argument struct {
Name string
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
Description *LocalizedText
}
type EnumValueType struct {
Value int64
DisplayName *LocalizedText
Description *LocalizedText
}
type EnumField struct {
Value int64
DisplayName *LocalizedText
Description *LocalizedText
Name string
}
type OptionSet struct {
Value []byte
ValidBits []byte
}
type TimeZoneDataType struct {
Offset int16
DaylightSavingInOffset bool
}
type ApplicationDescription struct {
ApplicationURI string
ProductURI string
ApplicationName *LocalizedText
ApplicationType ApplicationType
GatewayServerURI string
DiscoveryProfileURI string
DiscoveryURLs []string
}
type RequestHeader struct {
AuthenticationToken *NodeID
Timestamp time.Time
RequestHandle uint32
ReturnDiagnostics uint32
AuditEntryID string
TimeoutHint uint32
AdditionalHeader *ExtensionObject
}
type ResponseHeader struct {
Timestamp time.Time
RequestHandle uint32
ServiceResult StatusCode
ServiceDiagnostics *DiagnosticInfo
StringTable []string
AdditionalHeader *ExtensionObject
}
type ServiceFault struct {
ResponseHeader *ResponseHeader
}
func (t *ServiceFault) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *ServiceFault) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type SessionlessInvokeRequestType struct {
URIsVersion []uint32
NamespaceURIs []string
ServerURIs []string
LocaleIDs []string
ServiceID uint32
}
type SessionlessInvokeResponseType struct {
NamespaceURIs []string
ServerURIs []string
ServiceID uint32
}
type FindServersRequest struct {
RequestHeader *RequestHeader
EndpointURL string
LocaleIDs []string
ServerURIs []string
}
func (t *FindServersRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *FindServersRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type FindServersResponse struct {
ResponseHeader *ResponseHeader
Servers []*ApplicationDescription
}
func (t *FindServersResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *FindServersResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type ServerOnNetwork struct {
RecordID uint32
ServerName string
DiscoveryURL string
ServerCapabilities []string
}
type FindServersOnNetworkRequest struct {
RequestHeader *RequestHeader
StartingRecordID uint32
MaxRecordsToReturn uint32
ServerCapabilityFilter []string
}
func (t *FindServersOnNetworkRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *FindServersOnNetworkRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type FindServersOnNetworkResponse struct {
ResponseHeader *ResponseHeader
LastCounterResetTime time.Time
Servers []*ServerOnNetwork
}
func (t *FindServersOnNetworkResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *FindServersOnNetworkResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type UserTokenPolicy struct {
PolicyID string
TokenType UserTokenType
IssuedTokenType string
IssuerEndpointURL string
SecurityPolicyURI string
}
type EndpointDescription struct {
EndpointURL string
Server *ApplicationDescription
ServerCertificate []byte
SecurityMode MessageSecurityMode
SecurityPolicyURI string
UserIdentityTokens []*UserTokenPolicy
TransportProfileURI string
SecurityLevel uint8
}
type GetEndpointsRequest struct {
RequestHeader *RequestHeader
EndpointURL string
LocaleIDs []string
ProfileURIs []string
}
func (t *GetEndpointsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *GetEndpointsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type GetEndpointsResponse struct {
ResponseHeader *ResponseHeader
Endpoints []*EndpointDescription
}
func (t *GetEndpointsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *GetEndpointsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type RegisteredServer struct {
ServerURI string
ProductURI string
ServerNames []*LocalizedText
ServerType ApplicationType
GatewayServerURI string
DiscoveryURLs []string
SemaphoreFilePath string
IsOnline bool
}
type RegisterServerRequest struct {
RequestHeader *RequestHeader
Server *RegisteredServer
}
func (t *RegisterServerRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *RegisterServerRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type RegisterServerResponse struct {
ResponseHeader *ResponseHeader
}
func (t *RegisterServerResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *RegisterServerResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type MdnsDiscoveryConfiguration struct {
MdnsServerName string
ServerCapabilities []string
}
type RegisterServer2Request struct {
RequestHeader *RequestHeader
Server *RegisteredServer
DiscoveryConfiguration []*ExtensionObject
}
func (t *RegisterServer2Request) Header() *RequestHeader {
return t.RequestHeader
}
func (t *RegisterServer2Request) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type RegisterServer2Response struct {
ResponseHeader *ResponseHeader
ConfigurationResults []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *RegisterServer2Response) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *RegisterServer2Response) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type ChannelSecurityToken struct {
ChannelID uint32
TokenID uint32
CreatedAt time.Time
RevisedLifetime uint32
}
type OpenSecureChannelRequest struct {
RequestHeader *RequestHeader
ClientProtocolVersion uint32
RequestType SecurityTokenRequestType
SecurityMode MessageSecurityMode
ClientNonce []byte
RequestedLifetime uint32
}
func (t *OpenSecureChannelRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *OpenSecureChannelRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type OpenSecureChannelResponse struct {
ResponseHeader *ResponseHeader
ServerProtocolVersion uint32
SecurityToken *ChannelSecurityToken
ServerNonce []byte
}
func (t *OpenSecureChannelResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *OpenSecureChannelResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type CloseSecureChannelRequest struct {
RequestHeader *RequestHeader
}
func (t *CloseSecureChannelRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CloseSecureChannelRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CloseSecureChannelResponse struct {
ResponseHeader *ResponseHeader
}
func (t *CloseSecureChannelResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CloseSecureChannelResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type SignedSoftwareCertificate struct {
CertificateData []byte
Signature []byte
}
type SignatureData struct {
Algorithm string
Signature []byte
}
type CreateSessionRequest struct {
RequestHeader *RequestHeader
ClientDescription *ApplicationDescription
ServerURI string
EndpointURL string
SessionName string
ClientNonce []byte
ClientCertificate []byte
RequestedSessionTimeout float64
MaxResponseMessageSize uint32
}
func (t *CreateSessionRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CreateSessionRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CreateSessionResponse struct {
ResponseHeader *ResponseHeader
SessionID *NodeID
AuthenticationToken *NodeID
RevisedSessionTimeout float64
ServerNonce []byte
ServerCertificate []byte
ServerEndpoints []*EndpointDescription
ServerSoftwareCertificates []*SignedSoftwareCertificate
ServerSignature *SignatureData
MaxRequestMessageSize uint32
}
func (t *CreateSessionResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CreateSessionResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type UserIdentityToken struct {
PolicyID string
}
type AnonymousIdentityToken struct {
PolicyID string
}
type UserNameIdentityToken struct {
PolicyID string
UserName string
Password []byte
EncryptionAlgorithm string
}
type X509IdentityToken struct {
PolicyID string
CertificateData []byte
}
type IssuedIdentityToken struct {
PolicyID string
TokenData []byte
EncryptionAlgorithm string
}
type ActivateSessionRequest struct {
RequestHeader *RequestHeader
ClientSignature *SignatureData
ClientSoftwareCertificates []*SignedSoftwareCertificate
LocaleIDs []string
UserIdentityToken *ExtensionObject
UserTokenSignature *SignatureData
}
func (t *ActivateSessionRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *ActivateSessionRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type ActivateSessionResponse struct {
ResponseHeader *ResponseHeader
ServerNonce []byte
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *ActivateSessionResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *ActivateSessionResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type CloseSessionRequest struct {
RequestHeader *RequestHeader
DeleteSubscriptions bool
}
func (t *CloseSessionRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CloseSessionRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CloseSessionResponse struct {
ResponseHeader *ResponseHeader
}
func (t *CloseSessionResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CloseSessionResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type CancelRequest struct {
RequestHeader *RequestHeader
RequestHandle uint32
}
func (t *CancelRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CancelRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CancelResponse struct {
ResponseHeader *ResponseHeader
CancelCount uint32
}
func (t *CancelResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CancelResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type NodeAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
}
type ObjectAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
EventNotifier uint8
}
type VariableAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
Value *Variant
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
AccessLevel uint8
UserAccessLevel uint8
MinimumSamplingInterval float64
Historizing bool
}
type MethodAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
Executable bool
UserExecutable bool
}
type ObjectTypeAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
IsAbstract bool
}
type VariableTypeAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
Value *Variant
DataType *NodeID
ValueRank int32
ArrayDimensions []uint32
IsAbstract bool
}
type ReferenceTypeAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
IsAbstract bool
Symmetric bool
InverseName *LocalizedText
}
type DataTypeAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
IsAbstract bool
}
type ViewAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
ContainsNoLoops bool
EventNotifier uint8
}
type GenericAttributeValue struct {
AttributeID AttributeID
Value *Variant
}
type GenericAttributes struct {
SpecifiedAttributes uint32
DisplayName *LocalizedText
Description *LocalizedText
WriteMask uint32
UserWriteMask uint32
AttributeValues []*GenericAttributeValue
}
type AddNodesItem struct {
ParentNodeID *ExpandedNodeID
ReferenceTypeID *NodeID
RequestedNewNodeID *ExpandedNodeID
BrowseName *QualifiedName
NodeClass NodeClass
NodeAttributes *ExtensionObject
TypeDefinition *ExpandedNodeID
}
type AddNodesResult struct {
StatusCode StatusCode
AddedNodeID *NodeID
}
type AddNodesRequest struct {
RequestHeader *RequestHeader
NodesToAdd []*AddNodesItem
}
func (t *AddNodesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *AddNodesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type AddNodesResponse struct {
ResponseHeader *ResponseHeader
Results []*AddNodesResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *AddNodesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *AddNodesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type AddReferencesItem struct {
SourceNodeID *NodeID
ReferenceTypeID *NodeID
IsForward bool
TargetServerURI string
TargetNodeID *ExpandedNodeID
TargetNodeClass NodeClass
}
type AddReferencesRequest struct {
RequestHeader *RequestHeader
ReferencesToAdd []*AddReferencesItem
}
func (t *AddReferencesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *AddReferencesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type AddReferencesResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *AddReferencesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *AddReferencesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type DeleteNodesItem struct {
NodeID *NodeID
DeleteTargetReferences bool
}
type DeleteNodesRequest struct {
RequestHeader *RequestHeader
NodesToDelete []*DeleteNodesItem
}
func (t *DeleteNodesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *DeleteNodesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type DeleteNodesResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *DeleteNodesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *DeleteNodesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type DeleteReferencesItem struct {
SourceNodeID *NodeID
ReferenceTypeID *NodeID
IsForward bool
TargetNodeID *ExpandedNodeID
DeleteBidirectional bool
}
type DeleteReferencesRequest struct {
RequestHeader *RequestHeader
ReferencesToDelete []*DeleteReferencesItem
}
func (t *DeleteReferencesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *DeleteReferencesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type DeleteReferencesResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *DeleteReferencesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *DeleteReferencesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type ViewDescription struct {
ViewID *NodeID
Timestamp time.Time
ViewVersion uint32
}
type BrowseDescription struct {
NodeID *NodeID
BrowseDirection BrowseDirection
ReferenceTypeID *NodeID
IncludeSubtypes bool
NodeClassMask uint32
ResultMask uint32
}
type ReferenceDescription struct {
ReferenceTypeID *NodeID
IsForward bool
NodeID *ExpandedNodeID
BrowseName *QualifiedName
DisplayName *LocalizedText
NodeClass NodeClass
TypeDefinition *ExpandedNodeID
}
type BrowseResult struct {
StatusCode StatusCode
ContinuationPoint []byte
References []*ReferenceDescription
}
type BrowseRequest struct {
RequestHeader *RequestHeader
View *ViewDescription
RequestedMaxReferencesPerNode uint32
NodesToBrowse []*BrowseDescription
}
func (t *BrowseRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *BrowseRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type BrowseResponse struct {
ResponseHeader *ResponseHeader
Results []*BrowseResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *BrowseResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *BrowseResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type BrowseNextRequest struct {
RequestHeader *RequestHeader
ReleaseContinuationPoints bool
ContinuationPoints [][]byte
}
func (t *BrowseNextRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *BrowseNextRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type BrowseNextResponse struct {
ResponseHeader *ResponseHeader
Results []*BrowseResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *BrowseNextResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *BrowseNextResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type RelativePathElement struct {
ReferenceTypeID *NodeID
IsInverse bool
IncludeSubtypes bool
TargetName *QualifiedName
}
type RelativePath struct {
Elements []*RelativePathElement
}
type BrowsePath struct {
StartingNode *NodeID
RelativePath *RelativePath
}
type BrowsePathTarget struct {
TargetID *ExpandedNodeID
RemainingPathIndex uint32
}
type BrowsePathResult struct {
StatusCode StatusCode
Targets []*BrowsePathTarget
}
type TranslateBrowsePathsToNodeIDsRequest struct {
RequestHeader *RequestHeader
BrowsePaths []*BrowsePath
}
func (t *TranslateBrowsePathsToNodeIDsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *TranslateBrowsePathsToNodeIDsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type TranslateBrowsePathsToNodeIDsResponse struct {
ResponseHeader *ResponseHeader
Results []*BrowsePathResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *TranslateBrowsePathsToNodeIDsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *TranslateBrowsePathsToNodeIDsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type RegisterNodesRequest struct {
RequestHeader *RequestHeader
NodesToRegister []*NodeID
}
func (t *RegisterNodesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *RegisterNodesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type RegisterNodesResponse struct {
ResponseHeader *ResponseHeader
RegisteredNodeIDs []*NodeID
}
func (t *RegisterNodesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *RegisterNodesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type UnregisterNodesRequest struct {
RequestHeader *RequestHeader
NodesToUnregister []*NodeID
}
func (t *UnregisterNodesRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *UnregisterNodesRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type UnregisterNodesResponse struct {
ResponseHeader *ResponseHeader
}
func (t *UnregisterNodesResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *UnregisterNodesResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type EndpointConfiguration struct {
OperationTimeout int32
UseBinaryEncoding bool
MaxStringLength int32
MaxByteStringLength int32
MaxArrayLength int32
MaxMessageSize int32
MaxBufferSize int32
ChannelLifetime int32
SecurityTokenLifetime int32
}
type QueryDataDescription struct {
RelativePath *RelativePath
AttributeID AttributeID
IndexRange string
}
type NodeTypeDescription struct {
TypeDefinitionNode *ExpandedNodeID
IncludeSubTypes bool
DataToReturn []*QueryDataDescription
}
type QueryDataSet struct {
NodeID *ExpandedNodeID
TypeDefinitionNode *ExpandedNodeID
Values []*Variant
}
type NodeReference struct {
NodeID *NodeID
ReferenceTypeID *NodeID
IsForward bool
ReferencedNodeIDs []*NodeID
}
type ContentFilterElement struct {
FilterOperator FilterOperator
FilterOperands []*ExtensionObject
}
type ContentFilter struct {
Elements []*ContentFilterElement
}
type ElementOperand struct {
Index uint32
}
type LiteralOperand struct {
Value *Variant
}
type AttributeOperand struct {
NodeID *NodeID
Alias string
BrowsePath *RelativePath
AttributeID AttributeID
IndexRange string
}
type SimpleAttributeOperand struct {
TypeDefinitionID *NodeID
BrowsePath []*QualifiedName
AttributeID AttributeID
IndexRange string
}
type ContentFilterElementResult struct {
StatusCode StatusCode
OperandStatusCodes []StatusCode
OperandDiagnosticInfos []*DiagnosticInfo
}
type ContentFilterResult struct {
ElementResults []*ContentFilterElementResult
ElementDiagnosticInfos []*DiagnosticInfo
}
type ParsingResult struct {
StatusCode StatusCode
DataStatusCodes []StatusCode
DataDiagnosticInfos []*DiagnosticInfo
}
type QueryFirstRequest struct {
RequestHeader *RequestHeader
View *ViewDescription
NodeTypes []*NodeTypeDescription
Filter *ContentFilter
MaxDataSetsToReturn uint32
MaxReferencesToReturn uint32
}
func (t *QueryFirstRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *QueryFirstRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type QueryFirstResponse struct {
ResponseHeader *ResponseHeader
QueryDataSets []*QueryDataSet
ContinuationPoint []byte
ParsingResults []*ParsingResult
DiagnosticInfos []*DiagnosticInfo
FilterResult *ContentFilterResult
}
func (t *QueryFirstResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *QueryFirstResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type QueryNextRequest struct {
RequestHeader *RequestHeader
ReleaseContinuationPoint bool
ContinuationPoint []byte
}
func (t *QueryNextRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *QueryNextRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type QueryNextResponse struct {
ResponseHeader *ResponseHeader
QueryDataSets []*QueryDataSet
RevisedContinuationPoint []byte
}
func (t *QueryNextResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *QueryNextResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type ReadValueID struct {
NodeID *NodeID
AttributeID AttributeID
IndexRange string
DataEncoding *QualifiedName
}
type ReadRequest struct {
RequestHeader *RequestHeader
MaxAge float64
TimestampsToReturn TimestampsToReturn
NodesToRead []*ReadValueID
}
func (t *ReadRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *ReadRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type ReadResponse struct {
ResponseHeader *ResponseHeader
Results []*DataValue
DiagnosticInfos []*DiagnosticInfo
}
func (t *ReadResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *ReadResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type HistoryReadValueID struct {
NodeID *NodeID
IndexRange string
DataEncoding *QualifiedName
ContinuationPoint []byte
}
type HistoryReadResult struct {
StatusCode StatusCode
ContinuationPoint []byte
HistoryData *ExtensionObject
}
type ReadEventDetails struct {
NumValuesPerNode uint32
StartTime time.Time
EndTime time.Time
Filter *EventFilter
}
type ReadRawModifiedDetails struct {
IsReadModified bool
StartTime time.Time
EndTime time.Time
NumValuesPerNode uint32
ReturnBounds bool
}
type ReadProcessedDetails struct {
StartTime time.Time
EndTime time.Time
ProcessingInterval float64
AggregateType []*NodeID
AggregateConfiguration *AggregateConfiguration
}
type ReadAtTimeDetails struct {
ReqTimes []time.Time
UseSimpleBounds bool
}
type HistoryData struct {
DataValues []*DataValue
}
type ModificationInfo struct {
ModificationTime time.Time
UpdateType HistoryUpdateType
UserName string
}
type HistoryModifiedData struct {
DataValues []*DataValue
ModificationInfos []*ModificationInfo
}
type HistoryEvent struct {
Events []*HistoryEventFieldList
}
type HistoryReadRequest struct {
RequestHeader *RequestHeader
HistoryReadDetails *ExtensionObject
TimestampsToReturn TimestampsToReturn
ReleaseContinuationPoints bool
NodesToRead []*HistoryReadValueID
}
func (t *HistoryReadRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *HistoryReadRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type HistoryReadResponse struct {
ResponseHeader *ResponseHeader
Results []*HistoryReadResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *HistoryReadResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *HistoryReadResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type WriteValue struct {
NodeID *NodeID
AttributeID AttributeID
IndexRange string
Value *DataValue
}
type WriteRequest struct {
RequestHeader *RequestHeader
NodesToWrite []*WriteValue
}
func (t *WriteRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *WriteRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type WriteResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *WriteResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *WriteResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type HistoryUpdateDetails struct {
NodeID *NodeID
}
type UpdateDataDetails struct {
NodeID *NodeID
PerformInsertReplace PerformUpdateType
UpdateValues []*DataValue
}
type UpdateStructureDataDetails struct {
NodeID *NodeID
PerformInsertReplace PerformUpdateType
UpdateValues []*DataValue
}
type UpdateEventDetails struct {
NodeID *NodeID
PerformInsertReplace PerformUpdateType
Filter *EventFilter
EventData []*HistoryEventFieldList
}
type DeleteRawModifiedDetails struct {
NodeID *NodeID
IsDeleteModified bool
StartTime time.Time
EndTime time.Time
}
type DeleteAtTimeDetails struct {
NodeID *NodeID
ReqTimes []time.Time
}
type DeleteEventDetails struct {
NodeID *NodeID
EventIDs [][]byte
}
type HistoryUpdateResult struct {
StatusCode StatusCode
OperationResults []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
type HistoryUpdateRequest struct {
RequestHeader *RequestHeader
HistoryUpdateDetails []*ExtensionObject
}
func (t *HistoryUpdateRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *HistoryUpdateRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type HistoryUpdateResponse struct {
ResponseHeader *ResponseHeader
Results []*HistoryUpdateResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *HistoryUpdateResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *HistoryUpdateResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type CallMethodRequest struct {
ObjectID *NodeID
MethodID *NodeID
InputArguments []*Variant
}
type CallMethodResult struct {
StatusCode StatusCode
InputArgumentResults []StatusCode
InputArgumentDiagnosticInfos []*DiagnosticInfo
OutputArguments []*Variant
}
type CallRequest struct {
RequestHeader *RequestHeader
MethodsToCall []*CallMethodRequest
}
func (t *CallRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CallRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CallResponse struct {
ResponseHeader *ResponseHeader
Results []*CallMethodResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *CallResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CallResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type DataChangeFilter struct {
Trigger DataChangeTrigger
DeadbandType uint32
DeadbandValue float64
}
type EventFilter struct {
SelectClauses []*SimpleAttributeOperand
WhereClause *ContentFilter
}
type AggregateConfiguration struct {
UseServerCapabilitiesDefaults bool
TreatUncertainAsBad bool
PercentDataBad uint8
PercentDataGood uint8
UseSlopedExtrapolation bool
}
type AggregateFilter struct {
StartTime time.Time
AggregateType *NodeID
ProcessingInterval float64
AggregateConfiguration *AggregateConfiguration
}
type EventFilterResult struct {
SelectClauseResults []StatusCode
SelectClauseDiagnosticInfos []*DiagnosticInfo
WhereClauseResult *ContentFilterResult
}
type AggregateFilterResult struct {
RevisedStartTime time.Time
RevisedProcessingInterval float64
RevisedAggregateConfiguration *AggregateConfiguration
}
type MonitoringParameters struct {
ClientHandle uint32
SamplingInterval float64
Filter *ExtensionObject
QueueSize uint32
DiscardOldest bool
}
type MonitoredItemCreateRequest struct {
ItemToMonitor *ReadValueID
MonitoringMode MonitoringMode
RequestedParameters *MonitoringParameters
}
type MonitoredItemCreateResult struct {
StatusCode StatusCode
MonitoredItemID uint32
RevisedSamplingInterval float64
RevisedQueueSize uint32
FilterResult *ExtensionObject
}
type CreateMonitoredItemsRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
TimestampsToReturn TimestampsToReturn
ItemsToCreate []*MonitoredItemCreateRequest
}
func (t *CreateMonitoredItemsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CreateMonitoredItemsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CreateMonitoredItemsResponse struct {
ResponseHeader *ResponseHeader
Results []*MonitoredItemCreateResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *CreateMonitoredItemsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CreateMonitoredItemsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type MonitoredItemModifyRequest struct {
MonitoredItemID uint32
RequestedParameters *MonitoringParameters
}
type MonitoredItemModifyResult struct {
StatusCode StatusCode
RevisedSamplingInterval float64
RevisedQueueSize uint32
FilterResult *ExtensionObject
}
type ModifyMonitoredItemsRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
TimestampsToReturn TimestampsToReturn
ItemsToModify []*MonitoredItemModifyRequest
}
func (t *ModifyMonitoredItemsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *ModifyMonitoredItemsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type ModifyMonitoredItemsResponse struct {
ResponseHeader *ResponseHeader
Results []*MonitoredItemModifyResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *ModifyMonitoredItemsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *ModifyMonitoredItemsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type SetMonitoringModeRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
MonitoringMode MonitoringMode
MonitoredItemIDs []uint32
}
func (t *SetMonitoringModeRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *SetMonitoringModeRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type SetMonitoringModeResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *SetMonitoringModeResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *SetMonitoringModeResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type SetTriggeringRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
TriggeringItemID uint32
LinksToAdd []uint32
LinksToRemove []uint32
}
func (t *SetTriggeringRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *SetTriggeringRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type SetTriggeringResponse struct {
ResponseHeader *ResponseHeader
AddResults []StatusCode
AddDiagnosticInfos []*DiagnosticInfo
RemoveResults []StatusCode
RemoveDiagnosticInfos []*DiagnosticInfo
}
func (t *SetTriggeringResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *SetTriggeringResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type DeleteMonitoredItemsRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
MonitoredItemIDs []uint32
}
func (t *DeleteMonitoredItemsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *DeleteMonitoredItemsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type DeleteMonitoredItemsResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *DeleteMonitoredItemsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *DeleteMonitoredItemsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type CreateSubscriptionRequest struct {
RequestHeader *RequestHeader
RequestedPublishingInterval float64
RequestedLifetimeCount uint32
RequestedMaxKeepAliveCount uint32
MaxNotificationsPerPublish uint32
PublishingEnabled bool
Priority uint8
}
func (t *CreateSubscriptionRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *CreateSubscriptionRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type CreateSubscriptionResponse struct {
ResponseHeader *ResponseHeader
SubscriptionID uint32
RevisedPublishingInterval float64
RevisedLifetimeCount uint32
RevisedMaxKeepAliveCount uint32
}
func (t *CreateSubscriptionResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *CreateSubscriptionResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type ModifySubscriptionRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
RequestedPublishingInterval float64
RequestedLifetimeCount uint32
RequestedMaxKeepAliveCount uint32
MaxNotificationsPerPublish uint32
Priority uint8
}
func (t *ModifySubscriptionRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *ModifySubscriptionRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type ModifySubscriptionResponse struct {
ResponseHeader *ResponseHeader
RevisedPublishingInterval float64
RevisedLifetimeCount uint32
RevisedMaxKeepAliveCount uint32
}
func (t *ModifySubscriptionResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *ModifySubscriptionResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type SetPublishingModeRequest struct {
RequestHeader *RequestHeader
PublishingEnabled bool
SubscriptionIDs []uint32
}
func (t *SetPublishingModeRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *SetPublishingModeRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type SetPublishingModeResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *SetPublishingModeResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *SetPublishingModeResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type NotificationMessage struct {
SequenceNumber uint32
PublishTime time.Time
NotificationData []*ExtensionObject
}
type DataChangeNotification struct {
MonitoredItems []*MonitoredItemNotification
DiagnosticInfos []*DiagnosticInfo
}
type MonitoredItemNotification struct {
ClientHandle uint32
Value *DataValue
}
type EventNotificationList struct {
Events []*EventFieldList
}
type EventFieldList struct {
ClientHandle uint32
EventFields []*Variant
}
type HistoryEventFieldList struct {
EventFields []*Variant
}
type StatusChangeNotification struct {
Status StatusCode
DiagnosticInfo *DiagnosticInfo
}
type SubscriptionAcknowledgement struct {
SubscriptionID uint32
SequenceNumber uint32
}
type PublishRequest struct {
RequestHeader *RequestHeader
SubscriptionAcknowledgements []*SubscriptionAcknowledgement
}
func (t *PublishRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *PublishRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type PublishResponse struct {
ResponseHeader *ResponseHeader
SubscriptionID uint32
AvailableSequenceNumbers []uint32
MoreNotifications bool
NotificationMessage *NotificationMessage
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *PublishResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *PublishResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type RepublishRequest struct {
RequestHeader *RequestHeader
SubscriptionID uint32
RetransmitSequenceNumber uint32
}
func (t *RepublishRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *RepublishRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type RepublishResponse struct {
ResponseHeader *ResponseHeader
NotificationMessage *NotificationMessage
}
func (t *RepublishResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *RepublishResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type TransferResult struct {
StatusCode StatusCode
AvailableSequenceNumbers []uint32
}
type TransferSubscriptionsRequest struct {
RequestHeader *RequestHeader
SubscriptionIDs []uint32
SendInitialValues bool
}
func (t *TransferSubscriptionsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *TransferSubscriptionsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type TransferSubscriptionsResponse struct {
ResponseHeader *ResponseHeader
Results []*TransferResult
DiagnosticInfos []*DiagnosticInfo
}
func (t *TransferSubscriptionsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *TransferSubscriptionsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type DeleteSubscriptionsRequest struct {
RequestHeader *RequestHeader
SubscriptionIDs []uint32
}
func (t *DeleteSubscriptionsRequest) Header() *RequestHeader {
return t.RequestHeader
}
func (t *DeleteSubscriptionsRequest) SetHeader(h *RequestHeader) {
t.RequestHeader = h
}
type DeleteSubscriptionsResponse struct {
ResponseHeader *ResponseHeader
Results []StatusCode
DiagnosticInfos []*DiagnosticInfo
}
func (t *DeleteSubscriptionsResponse) Header() *ResponseHeader {
return t.ResponseHeader
}
func (t *DeleteSubscriptionsResponse) SetHeader(h *ResponseHeader) {
t.ResponseHeader = h
}
type BuildInfo struct {
ProductURI string
ManufacturerName string
ProductName string
SoftwareVersion string
BuildNumber string
BuildDate time.Time
}
type RedundantServerDataType struct {
ServerID string
ServiceLevel uint8
ServerState ServerState
}
type EndpointURLListDataType struct {
EndpointURLList []string
}
type NetworkGroupDataType struct {
ServerURI string
NetworkPaths []*EndpointURLListDataType
}
type SamplingIntervalDiagnosticsDataType struct {
SamplingInterval float64
MonitoredItemCount uint32
MaxMonitoredItemCount uint32
DisabledMonitoredItemCount uint32
}
type ServerDiagnosticsSummaryDataType struct {
ServerViewCount uint32
CurrentSessionCount uint32
CumulatedSessionCount uint32
SecurityRejectedSessionCount uint32
RejectedSessionCount uint32
SessionTimeoutCount uint32
SessionAbortCount uint32
CurrentSubscriptionCount uint32
CumulatedSubscriptionCount uint32
PublishingIntervalCount uint32
SecurityRejectedRequestsCount uint32
RejectedRequestsCount uint32
}
type ServerStatusDataType struct {
StartTime time.Time
CurrentTime time.Time
State ServerState
BuildInfo *BuildInfo
SecondsTillShutdown uint32
ShutdownReason *LocalizedText
}
type SessionDiagnosticsDataType struct {
SessionID *NodeID
SessionName string
ClientDescription *ApplicationDescription
ServerURI string
EndpointURL string
LocaleIDs []string
ActualSessionTimeout float64
MaxResponseMessageSize uint32
ClientConnectionTime time.Time
ClientLastContactTime time.Time
CurrentSubscriptionsCount uint32
CurrentMonitoredItemsCount uint32
CurrentPublishRequestsInQueue uint32
TotalRequestCount *ServiceCounterDataType
UnauthorizedRequestCount uint32
ReadCount *ServiceCounterDataType
HistoryReadCount *ServiceCounterDataType
WriteCount *ServiceCounterDataType
HistoryUpdateCount *ServiceCounterDataType
CallCount *ServiceCounterDataType
CreateMonitoredItemsCount *ServiceCounterDataType
ModifyMonitoredItemsCount *ServiceCounterDataType
SetMonitoringModeCount *ServiceCounterDataType
SetTriggeringCount *ServiceCounterDataType
DeleteMonitoredItemsCount *ServiceCounterDataType
CreateSubscriptionCount *ServiceCounterDataType
ModifySubscriptionCount *ServiceCounterDataType
SetPublishingModeCount *ServiceCounterDataType
PublishCount *ServiceCounterDataType
RepublishCount *ServiceCounterDataType
TransferSubscriptionsCount *ServiceCounterDataType
DeleteSubscriptionsCount *ServiceCounterDataType
AddNodesCount *ServiceCounterDataType
AddReferencesCount *ServiceCounterDataType
DeleteNodesCount *ServiceCounterDataType
DeleteReferencesCount *ServiceCounterDataType
BrowseCount *ServiceCounterDataType
BrowseNextCount *ServiceCounterDataType
TranslateBrowsePathsToNodeIDsCount *ServiceCounterDataType
QueryFirstCount *ServiceCounterDataType
QueryNextCount *ServiceCounterDataType
RegisterNodesCount *ServiceCounterDataType
UnregisterNodesCount *ServiceCounterDataType
}
type SessionSecurityDiagnosticsDataType struct {
SessionID *NodeID
ClientUserIDOfSession string
ClientUserIDHistory []string
AuthenticationMechanism string
Encoding string
TransportProtocol string
SecurityMode MessageSecurityMode
SecurityPolicyURI string
ClientCertificate []byte
}
type ServiceCounterDataType struct {
TotalCount uint32
ErrorCount uint32
}
type StatusResult struct {
StatusCode StatusCode
DiagnosticInfo *DiagnosticInfo
}
type SubscriptionDiagnosticsDataType struct {
SessionID *NodeID
SubscriptionID uint32
Priority uint8
PublishingInterval float64
MaxKeepAliveCount uint32
MaxLifetimeCount uint32
MaxNotificationsPerPublish uint32
PublishingEnabled bool
ModifyCount uint32
EnableCount uint32
DisableCount uint32
RepublishRequestCount uint32
RepublishMessageRequestCount uint32
RepublishMessageCount uint32
TransferRequestCount uint32
TransferredToAltClientCount uint32
TransferredToSameClientCount uint32
PublishRequestCount uint32
DataChangeNotificationsCount uint32
EventNotificationsCount uint32
NotificationsCount uint32
LatePublishRequestCount uint32
CurrentKeepAliveCount uint32
CurrentLifetimeCount uint32
UnacknowledgedMessageCount uint32
DiscardedMessageCount uint32
MonitoredItemCount uint32
DisabledMonitoredItemCount uint32
MonitoringQueueOverflowCount uint32
NextSequenceNumber uint32
EventQueueOverFlowCount uint32
}
type ModelChangeStructureDataType struct {
Affected *NodeID
AffectedType *NodeID
Verb uint8
}
type SemanticChangeStructureDataType struct {
Affected *NodeID
AffectedType *NodeID
}
type Range struct {
Low float64
High float64
}
type EUInformation struct {
NamespaceURI string
UnitID int32
DisplayName *LocalizedText
Description *LocalizedText
}
type ComplexNumberType struct {
Real float32
Imaginary float32
}
type DoubleComplexNumberType struct {
Real float64
Imaginary float64
}
type AxisInformation struct {
EngineeringUnits *EUInformation
EURange *Range
Title *LocalizedText
AxisScaleType AxisScaleEnumeration
AxisSteps []float64
}
type XVType struct {
X float64
Value float32
}
type ProgramDiagnosticDataType struct {
CreateSessionID *NodeID
CreateClientName string
InvocationCreationTime time.Time
LastTransitionTime time.Time
LastMethodCall string
LastMethodSessionID *NodeID
LastMethodInputArguments []*Argument
LastMethodOutputArguments []*Argument
LastMethodCallTime time.Time
LastMethodReturnStatus *StatusResult
}
type ProgramDiagnostic2DataType struct {
CreateSessionID *NodeID
CreateClientName string
InvocationCreationTime time.Time
LastTransitionTime time.Time
LastMethodCall string
LastMethodSessionID *NodeID
LastMethodInputArguments []*Argument
LastMethodOutputArguments []*Argument
LastMethodInputValues []*Variant
LastMethodOutputValues []*Variant
LastMethodCallTime time.Time
LastMethodReturnStatus *StatusResult
}
type Annotation struct {
Message string
UserName string
AnnotationTime time.Time
}
| Mainflux/mainflux-lite | vendor/github.com/gopcua/opcua/ua/extobjs_gen.go | GO | apache-2.0 | 63,585 |
/*
* Copyright (C) 2012-2015 DataStax Inc.
*
* 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 com.datastax.driver.core.policies;
import com.datastax.driver.core.*;
import com.datastax.driver.core.exceptions.OverloadedException;
import com.datastax.driver.core.exceptions.ServerError;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.mockito.Mockito;
import org.scassandra.Scassandra;
import org.scassandra.http.client.ClosedConnectionConfig.CloseType;
import org.scassandra.http.client.Config;
import org.scassandra.http.client.PrimingRequest;
import org.scassandra.http.client.PrimingRequest.PrimingRequestBuilder;
import org.scassandra.http.client.Result;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import java.util.List;
import java.util.Map;
import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.times;
import static org.scassandra.http.client.Result.overloaded;
import static org.scassandra.http.client.Result.server_error;
/**
* Base class for retry policy integration tests.
* <p/>
* We use SCassandra to easily simulate specific errors (unavailable, read timeout...) on nodes,
* and SortingLoadBalancingPolicy to get a predictable order of the query plan (always host1, host2, host3).
* <p/>
* Note that SCassandra only allows a limited number of test cases, for instance it always returns errors
* with receivedResponses = 0. If that becomes more finely tuneable in the future, we'll be able to add more
* tests in child classes.
*/
public class AbstractRetryPolicyIntegrationTest {
protected ScassandraCluster scassandras;
protected Cluster cluster = null;
protected Metrics.Errors errors;
protected Host host1, host2, host3;
protected Session session;
protected ExtendedRetryPolicy retryPolicy;
protected AbstractRetryPolicyIntegrationTest() {
}
protected AbstractRetryPolicyIntegrationTest(ExtendedRetryPolicy retryPolicy) {
setRetryPolicy(retryPolicy);
}
protected final void setRetryPolicy(ExtendedRetryPolicy retryPolicy) {
this.retryPolicy = Mockito.spy(retryPolicy);
}
@BeforeMethod(groups = "short")
public void beforeMethod() {
scassandras = ScassandraCluster.builder().withNodes(3).build();
scassandras.init();
cluster = Cluster.builder()
.addContactPoints(scassandras.address(1).getAddress())
.withPort(scassandras.getBinaryPort())
.withRetryPolicy(retryPolicy)
.withLoadBalancingPolicy(new SortingLoadBalancingPolicy())
// Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
.withProtocolVersion(ProtocolVersion.V2)
.withPoolingOptions(new PoolingOptions()
.setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
.setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
.setHeartbeatIntervalSeconds(0))
.withNettyOptions(nonQuietClusterCloseOptions)
.build();
session = cluster.connect();
host1 = TestUtils.findHost(cluster, 1);
host2 = TestUtils.findHost(cluster, 2);
host3 = TestUtils.findHost(cluster, 3);
errors = cluster.getMetrics().getErrorMetrics();
Mockito.reset(retryPolicy);
for (Scassandra node : scassandras.nodes()) {
node.activityClient().clearAllRecordedActivity();
}
}
protected void simulateError(int hostNumber, Result result) {
simulateError(hostNumber, result, null);
}
protected void simulateError(int hostNumber, Result result, Config config) {
PrimingRequestBuilder builder = PrimingRequest.queryBuilder()
.withQuery("mock query")
.withResult(result);
if (config != null)
builder = builder.withConfig(config);
scassandras.node(hostNumber).primingClient().prime(builder.build());
}
protected void simulateNormalResponse(int hostNumber) {
scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
.withQuery("mock query")
.withRows(row("result", "result1"))
.build());
}
protected static List<Map<String, ?>> row(String key, String value) {
return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
}
protected ResultSet query() {
return query(session);
}
protected ResultSet queryWithCL(ConsistencyLevel cl) {
Statement statement = new SimpleStatement("mock query").setConsistencyLevel(cl);
return session.execute(statement);
}
protected ResultSet query(Session session) {
return session.execute("mock query");
}
protected void assertOnReadTimeoutWasCalled(int times) {
Mockito.verify(retryPolicy, times(times)).onReadTimeout(
any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt());
}
protected void assertOnWriteTimeoutWasCalled(int times) {
Mockito.verify(retryPolicy, times(times)).onWriteTimeout(
any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt());
}
protected void assertOnUnavailableWasCalled(int times) {
Mockito.verify(retryPolicy, times(times)).onUnavailable(
any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
}
protected void assertOnRequestErrorWasCalled(int times) {
Mockito.verify(retryPolicy, times(times)).onRequestError(
any(Statement.class), any(ConsistencyLevel.class), any(Exception.class), anyInt());
}
protected void assertQueried(int hostNumber, int times) {
assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
}
@AfterMethod(groups = "short", alwaysRun = true)
public void afterMethod() {
if (cluster != null)
cluster.close();
if (scassandras != null)
scassandras.stop();
}
@DataProvider
public static Object[][] serverSideErrors() {
return new Object[][]{
{server_error, ServerError.class},
{overloaded, OverloadedException.class},
};
}
@DataProvider
public static Object[][] connectionErrors() {
return new Object[][]{
{CloseType.CLOSE},
{CloseType.HALFCLOSE},
{CloseType.RESET}
};
}
}
| tommystendahl/java-driver | driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java | Java | apache-2.0 | 7,400 |
# Part of get-flash-videos. See get_flash_videos for copyright.
package FlashVideo::VideoPreferences;
use strict;
use FlashVideo::VideoPreferences::Quality;
use FlashVideo::VideoPreferences::Account;
sub new {
my($class, %opt) = @_;
return bless {
raw => $opt{raw} || 0,
quality => $opt{quality} || "high",
subtitles => $opt{subtitles} || 0,
type => $opt{type} || "",
}, $class;
}
sub quality {
my($self) = @_;
return FlashVideo::VideoPreferences::Quality->new($self->{quality});
}
sub subtitles {
my($self) = @_;
return $self->{subtitles};
}
sub account {
my($self, $site, $prompt) = @_;
return FlashVideo::VideoPreferences::Account->new($site, $prompt);
}
1;
| monsieurvideo/get-flash-videos | lib/FlashVideo/VideoPreferences.pm | Perl | apache-2.0 | 705 |
/// <reference path='fourslash.ts' />
////const a = 1, b = 1;
////b = 2;
verify.codeFix({
description: "Convert 'const' to 'let'",
index: 0,
newFileContent:
`let a = 1, b = 1;
b = 2;`
});
| kpreisser/TypeScript | tests/cases/fourslash/codeFixConstToLet2.ts | TypeScript | apache-2.0 | 202 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 ml.dmlc.tvm;
import ml.dmlc.tvm.rpc.RPC;
import java.util.HashMap;
import java.util.Map;
public class TVMContext {
private static final Map<Integer, String> MASK2STR = new HashMap<Integer, String>();
private static final Map<String, Integer> STR2MASK = new HashMap<String, Integer>();
static {
MASK2STR.put(1, "cpu");
MASK2STR.put(2, "gpu");
MASK2STR.put(4, "opencl");
MASK2STR.put(7, "vulkan");
MASK2STR.put(8, "metal");
MASK2STR.put(9, "vpi");
STR2MASK.put("cpu", 1);
STR2MASK.put("gpu", 2);
STR2MASK.put("cuda", 2);
STR2MASK.put("cl", 4);
STR2MASK.put("opencl", 4);
STR2MASK.put("vulkan", 7);
STR2MASK.put("metal", 8);
STR2MASK.put("vpi", 9);
}
/**
* Construct a CPU device.
* @param devId The device id
* @return The created context
*/
public static TVMContext cpu(int devId) {
return new TVMContext(1, devId);
}
public static TVMContext cpu() {
return cpu(0);
}
/**
* Construct a GPU device.
* @param devId The device id
* @return The created context
*/
public static TVMContext gpu(int devId) {
return new TVMContext(2, devId);
}
public static TVMContext gpu() {
return gpu(0);
}
/**
* Construct a OpenCL device.
* @param devId The device id
* @return The created context
*/
public static TVMContext opencl(int devId) {
return new TVMContext(4, devId);
}
public static TVMContext opencl() {
return opencl(0);
}
/**
* Construct a Vulkan device.
* @param devId The device id
* @return The created context
*/
public static TVMContext vulkan(int devId) {
return new TVMContext(7, devId);
}
public static TVMContext vulkan() {
return vulkan(0);
}
/**
* Construct a metal device.
* @param devId The device id
* @return The created context
*/
public static TVMContext metal(int devId) {
return new TVMContext(8, devId);
}
public static TVMContext metal() {
return metal(0);
}
/**
* Construct a VPI simulated device.
* @param devId The device id
* @return The created context
*/
public static TVMContext vpi(int devId) {
return new TVMContext(9, devId);
}
public static TVMContext vpi() {
return vpi(0);
}
public final int deviceType;
public final int deviceId;
public TVMContext(int deviceType, int deviceId) {
this.deviceType = deviceType;
this.deviceId = deviceId;
}
public TVMContext(String deviceType, int deviceId) {
this(STR2MASK.get(deviceType), deviceId);
}
/**
* Whether this device exists.
* @return true if exists.
*/
public boolean exist() {
TVMValue ret = APIInternal.get("_GetDeviceAttr")
.pushArg(deviceType).pushArg(deviceId).pushArg(0).invoke();
return ((TVMValueLong) ret).value != 0;
}
/**
* Maximum number of threads on each block.
* @return the maximum thread number.
*/
public long maxThreadsPerBlock() {
TVMValue ret = APIInternal.get("_GetDeviceAttr")
.pushArg(deviceType).pushArg(deviceId).pushArg(1).invoke();
return ((TVMValueLong) ret).value;
}
/**
* Number of threads that executes in concurrent.
* @return the thread number.
*/
public long warpSize() {
TVMValue ret = APIInternal.get("_GetDeviceAttr")
.pushArg(deviceType).pushArg(deviceId).pushArg(2).invoke();
return ((TVMValueLong) ret).value;
}
/**
* Synchronize until jobs finished at the context.
*/
public void sync() {
Base.checkCall(Base._LIB.tvmSynchronize(deviceType, deviceId));
}
@Override public int hashCode() {
return (deviceType << 16) | deviceId;
}
@Override public boolean equals(Object other) {
if (other != null && other instanceof TVMContext) {
TVMContext obj = (TVMContext) other;
return deviceId == obj.deviceId && deviceType == obj.deviceType;
}
return false;
}
@Override public String toString() {
if (deviceType >= RPC.RPC_SESS_MASK) {
int tblId = deviceType / RPC.RPC_SESS_MASK - 1;
int devType = deviceType % RPC.RPC_SESS_MASK;
return String.format("remote[%d]:%s(%d)", tblId, MASK2STR.get(devType), deviceId);
}
return String.format("%s(%d)", MASK2STR.get(deviceType), deviceId);
}
}
| Huyuwei/tvm | jvm/core/src/main/java/ml/dmlc/tvm/TVMContext.java | Java | apache-2.0 | 5,077 |
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* 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.
*/
#include <vnet/dpo/dpo.h>
#include <vnet/lisp-gpe/lisp_gpe.h>
#include <vnet/lisp-cp/control.h>
/**
* The static array of LISP punt DPOs
*/
static dpo_id_t lisp_cp_dpos[DPO_PROTO_NUM];
const dpo_id_t *
lisp_cp_dpo_get (dpo_proto_t proto)
{
/*
* there are only two instances of this DPO type.
* we can use the protocol as the index
*/
return (&lisp_cp_dpos[proto]);
}
static u8 *
format_lisp_cp_dpo (u8 * s, va_list * args)
{
index_t index = va_arg (*args, index_t);
CLIB_UNUSED (u32 indent) = va_arg (*args, u32);
return (format (s, "lisp-cp-punt-%U", format_dpo_proto, index));
}
static void
lisp_cp_dpo_lock (dpo_id_t * dpo)
{
}
static void
lisp_cp_dpo_unlock (dpo_id_t * dpo)
{
}
const static dpo_vft_t lisp_cp_vft = {
.dv_lock = lisp_cp_dpo_lock,
.dv_unlock = lisp_cp_dpo_unlock,
.dv_format = format_lisp_cp_dpo,
};
/**
* @brief The per-protocol VLIB graph nodes that are assigned to a LISP-CP
* object.
*
* this means that these graph nodes are ones from which a LISP-CP is the
* parent object in the DPO-graph.
*/
const static char *const lisp_cp_ip4_nodes[] = {
"lisp-cp-lookup-ip4",
NULL,
};
const static char *const lisp_cp_ip6_nodes[] = {
"lisp-cp-lookup-ip6",
NULL,
};
const static char *const lisp_cp_ethernet_nodes[] = {
"lisp-cp-lookup-l2",
NULL,
};
const static char *const lisp_cp_nsh_nodes[] = {
"lisp-cp-lookup-nsh",
NULL,
};
const static char *const *const lisp_cp_nodes[DPO_PROTO_NUM] = {
[DPO_PROTO_IP4] = lisp_cp_ip4_nodes,
[DPO_PROTO_IP6] = lisp_cp_ip6_nodes,
[DPO_PROTO_ETHERNET] = lisp_cp_ethernet_nodes,
[DPO_PROTO_MPLS] = NULL,
[DPO_PROTO_NSH] = lisp_cp_nsh_nodes,
};
clib_error_t *
lisp_cp_dpo_module_init (vlib_main_t * vm)
{
dpo_proto_t dproto;
/*
* there are no exit arcs from the LIS-CP VLIB node, so we
* pass NULL as said node array.
*/
dpo_register (DPO_LISP_CP, &lisp_cp_vft, lisp_cp_nodes);
FOR_EACH_DPO_PROTO (dproto)
{
dpo_set (&lisp_cp_dpos[dproto], DPO_LISP_CP, dproto, dproto);
}
return (NULL);
}
VLIB_INIT_FUNCTION (lisp_cp_dpo_module_init);
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| milanlenco/vpp | src/vnet/lisp-cp/lisp_cp_dpo.c | C | apache-2.0 | 2,823 |
/* $NetBSD: segments.h,v 1.54 2011/04/26 15:51:23 joerg Exp $ */
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)segments.h 7.1 (Berkeley) 5/9/91
*/
/*-
* Copyright (c) 1995, 1997
* Charles M. Hannum. All rights reserved.
* Copyright (c) 1989, 1990 William F. Jolitz
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)segments.h 7.1 (Berkeley) 5/9/91
*/
/*
* 386 Segmentation Data Structures and definitions
* William F. Jolitz ([email protected]) 6/20/1989
*/
#ifndef _I386_SEGMENTS_H_
#define _I386_SEGMENTS_H_
#ifdef _KERNEL_OPT
#include "opt_xen.h"
#endif
/*
* Selectors
*/
#define ISPL(s) ((s) & SEL_RPL) /* what is the priority level of a selector */
#ifndef XEN
#define SEL_KPL 0 /* kernel privilege level */
#else
#define SEL_XEN 0 /* Xen privilege level */
#define SEL_KPL 1 /* kernel privilege level */
#endif /* XEN */
#define SEL_UPL 3 /* user privilege level */
#define SEL_RPL 3 /* requester's privilege level mask */
#ifdef XEN
#define CHK_UPL 2 /* user privilege level mask */
#else
#define CHK_UPL SEL_RPL
#endif /* XEN */
#define ISLDT(s) ((s) & SEL_LDT) /* is it local or global */
#define SEL_LDT 4 /* local descriptor table */
#define IDXSEL(s) (((s) >> 3) & 0x1fff) /* index of selector */
#define IDXSELN(s) (((s) >> 3)) /* index of selector */
#define GSEL(s,r) (((s) << 3) | r) /* a global selector */
#define LSEL(s,r) (((s) << 3) | r | SEL_LDT) /* a local selector */
#define GSYSSEL(s,r) GSEL(s,r) /* compat with amd64 */
#if defined(_KERNEL_OPT)
#include "opt_vm86.h"
#endif
#ifdef VM86
#define USERMODE(c, f) (ISPL(c) == SEL_UPL || ((f) & PSL_VM) != 0)
#define KERNELMODE(c, f) (ISPL(c) == SEL_KPL && ((f) & PSL_VM) == 0)
#else
#define USERMODE(c, f) (ISPL(c) == SEL_UPL)
#define KERNELMODE(c, f) (ISPL(c) == SEL_KPL)
#endif
#ifndef _LOCORE
#if __GNUC__ == 2 && __GNUC_MINOR__ < 7
#pragma pack(1)
#endif
/*
* Memory and System segment descriptors
*/
struct segment_descriptor {
unsigned sd_lolimit:16; /* segment extent (lsb) */
unsigned sd_lobase:24; /* segment base address (lsb) */
unsigned sd_type:5; /* segment type */
unsigned sd_dpl:2; /* segment descriptor priority level */
unsigned sd_p:1; /* segment descriptor present */
unsigned sd_hilimit:4; /* segment extent (msb) */
unsigned sd_xx:2; /* unused */
unsigned sd_def32:1; /* default 32 vs 16 bit size */
unsigned sd_gran:1; /* limit granularity (byte/page) */
unsigned sd_hibase:8; /* segment base address (msb) */
} __packed;
/*
* Gate descriptors (e.g. indirect descriptors)
*/
struct gate_descriptor {
unsigned gd_looffset:16; /* gate offset (lsb) */
unsigned gd_selector:16; /* gate segment selector */
unsigned gd_stkcpy:5; /* number of stack wds to cpy */
unsigned gd_xx:3; /* unused */
unsigned gd_type:5; /* segment type */
unsigned gd_dpl:2; /* segment descriptor priority level */
unsigned gd_p:1; /* segment descriptor present */
unsigned gd_hioffset:16; /* gate offset (msb) */
} __packed;
struct ldt_descriptor {
vaddr_t ld_base;
uint32_t ld_entries;
} __packed;
/*
* Generic descriptor
*/
union descriptor {
struct segment_descriptor sd;
struct gate_descriptor gd;
struct ldt_descriptor ld;
uint32_t raw[2];
uint64_t raw64;
} __packed;
/*
* region descriptors, used to load gdt/idt tables before segments yet exist.
*/
struct region_descriptor {
unsigned rd_limit:16; /* segment extent */
unsigned rd_base:32; /* base address */
} __packed;
#if __GNUC__ == 2 && __GNUC_MINOR__ < 7
#pragma pack(4)
#endif
#ifdef _KERNEL
extern union descriptor *gdt, *ldt;
extern struct gate_descriptor *idt;
void setgate(struct gate_descriptor *, void *, int, int, int, int);
void setregion(struct region_descriptor *, void *, size_t);
void setsegment(struct segment_descriptor *, const void *, size_t, int, int,
int, int);
void setgdt(int, const void *, size_t, int, int, int, int);
void unsetgate(struct gate_descriptor *);
void cpu_init_idt(void);
void update_descriptor(union descriptor *, union descriptor *);
#if !defined(XEN)
void idt_init(void);
void idt_vec_reserve(int);
int idt_vec_alloc(int, int);
void idt_vec_set(int, void (*)(void));
void idt_vec_free(int);
#endif
#endif /* _KERNEL */
#endif /* !_LOCORE */
/* system segments and gate types */
#define SDT_SYSNULL 0 /* system null */
#define SDT_SYS286TSS 1 /* system 286 TSS available */
#define SDT_SYSLDT 2 /* system local descriptor table */
#define SDT_SYS286BSY 3 /* system 286 TSS busy */
#define SDT_SYS286CGT 4 /* system 286 call gate */
#define SDT_SYSTASKGT 5 /* system task gate */
#define SDT_SYS286IGT 6 /* system 286 interrupt gate */
#define SDT_SYS286TGT 7 /* system 286 trap gate */
#define SDT_SYSNULL2 8 /* system null again */
#define SDT_SYS386TSS 9 /* system 386 TSS available */
#define SDT_SYSNULL3 10 /* system null again */
#define SDT_SYS386BSY 11 /* system 386 TSS busy */
#define SDT_SYS386CGT 12 /* system 386 call gate */
#define SDT_SYSNULL4 13 /* system null again */
#define SDT_SYS386IGT 14 /* system 386 interrupt gate */
#define SDT_SYS386TGT 15 /* system 386 trap gate */
/* memory segment types */
#define SDT_MEMRO 16 /* memory read only */
#define SDT_MEMROA 17 /* memory read only accessed */
#define SDT_MEMRW 18 /* memory read write */
#define SDT_MEMRWA 19 /* memory read write accessed */
#define SDT_MEMROD 20 /* memory read only expand dwn limit */
#define SDT_MEMRODA 21 /* memory read only expand dwn limit accessed */
#define SDT_MEMRWD 22 /* memory read write expand dwn limit */
#define SDT_MEMRWDA 23 /* memory read write expand dwn limit acessed */
#define SDT_MEME 24 /* memory execute only */
#define SDT_MEMEA 25 /* memory execute only accessed */
#define SDT_MEMER 26 /* memory execute read */
#define SDT_MEMERA 27 /* memory execute read accessed */
#define SDT_MEMEC 28 /* memory execute only conforming */
#define SDT_MEMEAC 29 /* memory execute only accessed conforming */
#define SDT_MEMERC 30 /* memory execute read conforming */
#define SDT_MEMERAC 31 /* memory execute read accessed conforming */
#define SDTYPE(p) (((const struct segment_descriptor *)(p))->sd_type)
/* is memory segment descriptor pointer ? */
#define ISMEMSDP(s) (SDTYPE(s) >= SDT_MEMRO && \
SDTYPE(s) <= SDT_MEMERAC)
/* is 286 gate descriptor pointer ? */
#define IS286GDP(s) (SDTYPE(s) >= SDT_SYS286CGT && \
SDTYPE(s) < SDT_SYS286TGT)
/* is 386 gate descriptor pointer ? */
#define IS386GDP(s) (SDTYPE(s) >= SDT_SYS386CGT && \
SDTYPE(s) < SDT_SYS386TGT)
/* is gate descriptor pointer ? */
#define ISGDP(s) (IS286GDP(s) || IS386GDP(s))
/* is segment descriptor pointer ? */
#define ISSDP(s) (ISMEMSDP(s) || !ISGDP(s))
/* is system segment descriptor pointer ? */
#define ISSYSSDP(s) (!ISMEMSDP(s) && !ISGDP(s))
/*
* Segment Protection Exception code bits
*/
#define SEGEX_EXT 0x01 /* recursive or externally induced */
#define SEGEX_IDT 0x02 /* interrupt descriptor table */
#define SEGEX_TI 0x04 /* local descriptor table */
/*
* Entries in the Interrupt Descriptor Table (IDT)
*/
#define NIDT 256
#define NRSVIDT 32 /* reserved entries for CPU exceptions */
/*
* Entries in the Global Descriptor Table (GDT).
*
* NB: If you change GBIOSCODE/GBIOSDATA, you *must* rebuild arch/i386/
* bioscall/biostramp.inc, as that relies on GBIOSCODE/GBIOSDATA and a
* normal kernel build does not rebuild it (it's merely included whole-
* sale from i386/bioscall.s)
*
* Also, note that the GEXTBIOSDATA_SEL selector is special, as it maps
* to the value 0x0040 (when created as a KPL global selector). Some
* BIOSes reference the extended BIOS data area at segment 0040 in a non
* relocatable fashion (even when in protected mode); mapping the zero page
* via the GEXTBIOSDATA_SEL allows these buggy BIOSes to continue to work
* under NetBSD.
*
* The order if the first 5 descriptors is special; the sysenter/sysexit
* instructions depend on them.
*/
#define GNULL_SEL 0 /* Null descriptor */
#define GCODE_SEL 1 /* Kernel code descriptor */
#define GDATA_SEL 2 /* Kernel data descriptor */
#define GUCODE_SEL 3 /* User code descriptor */
#define GUDATA_SEL 4 /* User data descriptor */
#define GLDT_SEL 5 /* Default LDT descriptor */
#define GCPU_SEL 6 /* per-CPU segment */
#define GEXTBIOSDATA_SEL 8 /* magic to catch BIOS refs to EBDA */
#define GAPM32CODE_SEL 9 /* 3 APM segments must be consecutive */
#define GAPM16CODE_SEL 10 /* and in the specified order: code32 */
#define GAPMDATA_SEL 11 /* code16 and then data per APM spec */
#define GBIOSCODE_SEL 12
#define GBIOSDATA_SEL 13
#define GPNPBIOSCODE_SEL 14
#define GPNPBIOSDATA_SEL 15
#define GPNPBIOSSCRATCH_SEL 16
#define GPNPBIOSTRAMP_SEL 17
#define GTRAPTSS_SEL 18
#define GIPITSS_SEL 19
#define GUCODEBIG_SEL 20 /* User code with executable stack */
#define GUFS_SEL 21 /* Per-thread %fs */
#define GUGS_SEL 22 /* Per-thread %gs */
#define NGDT 23
/*
* Entries in the Local Descriptor Table (LDT).
* DO NOT ADD KERNEL DATA/CODE SEGMENTS TO THIS TABLE.
*/
#define LSYS5CALLS_SEL 0 /* iBCS system call gate */
#define LSYS5SIGR_SEL 1 /* iBCS sigreturn gate */
#define LUCODE_SEL 2 /* User code descriptor */
#define LUDATA_SEL 3 /* User data descriptor */
#define LSOL26CALLS_SEL 4 /* Solaris 2.6 system call gate */
#define LUCODEBIG_SEL 5 /* User code with executable stack */
#define LBSDICALLS_SEL 16 /* BSDI system call gate */
#define NLDT 17
#endif /* _I386_SEGMENTS_H_ */
| veritas-shine/minix3-rpi | sys/arch/i386/include/segments.h | C | apache-2.0 | 12,813 |
<html>
<head>
<title>Elda licence conditions</title>
<link href="style.css" type="text/css" rel="stylesheet"></link>
</head>
<body>
<h1>Elda licence conditions</h1>
© Copyright 2010 Epimorphics Limited.
<p>
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
<pre>
<a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
</pre>
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.
</p>
</body>
</html>
| health-and-care-developer-network/health-and-care-developer-network | library/elda/1.2.16/elda-LICENCE.html | HTML | apache-2.0 | 831 |
{%- set activities = [{
'name': 'tag_list',
'url': '/tags/',
'text': _("Tags"),
'description': _("View all tags"),
'icon': 'tag'
},{
'name': 'tag_add',
'url': '/tags/add/',
'text': _("Add Tag"),
'description': _("Create a new tag"),
'icon': 'plus'
},{
'name': 'filter_list',
'url': '/filter/list/',
'text': _("Filters"),
'description': _("All current filters"),
'icon': 'filters'
}] -%}
{%- set display_modes = [{
'name': 'display_tag_type',
'icon': 'eye',
'url': '/tags/',
'text': _("Type"),
'description': _("Show Tag by type")
}] -%}
{%- include('partials/tools_default.html') -%} | laborautonomo/Mailpile | mailpile/www/default/html/partials/tools_tags.html | HTML | apache-2.0 | 663 |
package scalarules.test
object TestPointB {
def getV: Int = 66
}
| smparkes/rules_scala | test/DataRoot2.scala | Scala | apache-2.0 | 69 |
<div class="header">
<div class="fan"></div>
<div class="container-fluid">
<div class="row">
<nav class="nav-primary">
<div class="container-fluid">
<div class="navbar-header">
<img class="logo" src="../images/docker-docs-logo.svg" alt="Docker Docs" title="Docker Docs">
</div>
<div class="navbar-collapse collapse">
<ul class="primary nav navbar-nav">
<li><a href="https://docker.com/what-docker">What is Docker?</a></li>
<li><a href="https://docker.com/get-docker">Product</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Get Docker <span class="caret"></span></a>
<ul class="dropdown-menu nav-main">
<h6 class="dropdown-header">For Desktops</h6>
<li><a href="https://docker.com/docker-mac">Mac</a></li>
<li><a href="https://docker.com/docker-windows">Windows</a></li>
<h6 class="dropdown-header">For Cloud Providers</h6>
<li><a href="https://docker.com/docker-aws">AWS</a></li>
<li><a href="https://docker.com/docker-microsoft-azure">Azure</a></li>
<h6 class="dropdown-header">For Servers</h6>
<li><a href="https://docker.com/docker-windows-server">Windows Server</a></li>
<li><a href="https://docker.com/docker-centos">CentOS</a></li>
<li><a href="https://docker.com/docker-debian">Debian</a></li>
<li><a href="https://docker.com/docker-fedora">Fedora</a></li>
<li><a href="https://docker.com/docker-oracle-linux">Oracle Enterprise Linux</a></li>
<li><a href="https://docker.com/docker-rhel">RHEL</a></li>
<li><a href="https://docker.com/docker-sles">SLES</a></li>
<li><a href="https://docker.com/docker-ubuntu">Ubuntu</a></li>
</ul>
</li>
<li><a href="https://docs.docker.com">Docs</a></li>
<li><a href="https://docker.com/docker-community">Community</a></li>
<li><a href="https://cloud.docker.com/">Create Docker ID</a></li>
<li><a href="https://cloud.docker.com/login">Sign In</a></li>
</ul>
<!-- <div class="user-nav hidden-sm">
<ul>
<li><a href="https://cloud.docker.com/">Create Docker ID</a></li>
<li><a href="https://cloud.docker.com/login">Sign In</a></li>
</ul>
</div> -->
</div>
<!--/.nav-collapse -->
</div>
</nav>
</div>
</div>
<!-- hero banner text -->
<div class="container-fluid">
<div class="row">
<div class="hero-text">
<div class="hero-text-centered">
<h1>{{ site.name }}</h1>
<p>Docker provides a way to run applications securely isolated in a container, packaged with all its dependencies and libraries.</p>
<ul class="buttons">
<li><a class="button transparent-btn" href="/engine/installation/" target="_blank">Get Docker</a></li>
<li> <a class="button secondary-btn" href="/get-started/" target="_blank">Get Started</a></li>
</ul>
</div>
</div>
</div>
<a href="http://2017.dockercon.com/register-dockercon-2017/" target="_blank">
<div class="banner">
<img src="images/dockercon-register-now.svg">
</div>
</a>
</div>
<!-- nav-secondary -->
<!-- data-offset-top should calculated as follows: (height of <header> - header of <nav>) -->
<nav class="nav-secondary-tabs" data-spy="affix" data-offset-top="385">
<div class="container-fluid">
<div class="navbar-collapse" aria-expanded="false" style="height: 1px;">
{% include navigation.html %}
</div>
</div>
</nav>
</div> | phiroict/docker | _includes/global-header.html | HTML | apache-2.0 | 4,831 |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 org.drools.core.phreak;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.reteoo.LeftTuple;
import org.drools.core.reteoo.LeftTupleSinkNode;
import org.drools.core.reteoo.ReactiveFromNode;
import org.drools.core.reteoo.ReactiveFromNodeLeftTuple;
import org.drools.core.reteoo.RightTupleImpl;
import org.drools.core.rule.ContextEntry;
import org.drools.core.spi.PropagationContext;
import org.drools.core.spi.Tuple;
import java.util.Collection;
import static org.drools.core.phreak.PhreakFromNode.*;
public class ReactiveObjectUtil {
public enum ModificationType {
NONE, MODIFY, ADD, REMOVE
}
public static void notifyModification(ReactiveObject reactiveObject) {
notifyModification( reactiveObject, reactiveObject.getLeftTuples(), ModificationType.MODIFY);
}
public static void notifyModification( Object object, Collection<Tuple> leftTuples, ModificationType type ) {
for (Tuple leftTuple : leftTuples) {
if (!( (ReactiveFromNodeLeftTuple) leftTuple ).updateModificationState( object, type )) {
continue;
}
PropagationContext propagationContext = leftTuple.getPropagationContext();
ReactiveFromNode node = (ReactiveFromNode)leftTuple.getTupleSink();
LeftTupleSinkNode sink = node.getSinkPropagator().getFirstLeftTupleSink();
InternalWorkingMemory wm = getInternalWorkingMemory(propagationContext);
wm.addPropagation(new ReactivePropagation(object, (ReactiveFromNodeLeftTuple)leftTuple, propagationContext, node, sink, type));
}
}
private static InternalWorkingMemory getInternalWorkingMemory(PropagationContext propagationContext) {
InternalFactHandle fh = propagationContext.getFactHandle();
return fh.getEntryPoint().getInternalWorkingMemory();
}
static class ReactivePropagation extends PropagationEntry.AbstractPropagationEntry {
private final Object object;
private final ReactiveFromNodeLeftTuple leftTuple;
private final PropagationContext propagationContext;
private final ReactiveFromNode node;
private final LeftTupleSinkNode sink;
private final ModificationType type;
ReactivePropagation( Object object, ReactiveFromNodeLeftTuple leftTuple, PropagationContext propagationContext, ReactiveFromNode node, LeftTupleSinkNode sink, ModificationType type ) {
this.object = object;
this.leftTuple = leftTuple;
this.propagationContext = propagationContext;
this.node = node;
this.sink = sink;
this.type = type;
}
@Override
public void execute( InternalWorkingMemory wm ) {
if ( leftTuple.resetModificationState( object ) == ModificationType.NONE ) {
return;
}
ReactiveFromNode.ReactiveFromMemory mem = wm.getNodeMemory(node);
InternalFactHandle factHandle = node.createFactHandle( leftTuple, propagationContext, wm, object );
if ( type != ModificationType.REMOVE && isAllowed( factHandle, node.getAlphaConstraints(), wm, mem ) ) {
ContextEntry[] context = mem.getBetaMemory().getContext();
BetaConstraints betaConstraints = node.getBetaConstraints();
betaConstraints.updateFromTuple( context,
wm,
leftTuple );
propagate( sink,
leftTuple,
new RightTupleImpl( factHandle ),
betaConstraints,
propagationContext,
context,
RuleNetworkEvaluator.useLeftMemory( node, leftTuple ),
mem.getStagedLeftTuples(),
null );
} else {
LeftTuple childLeftTuple = ((LeftTuple)leftTuple).getFirstChild();
while (childLeftTuple != null) {
LeftTuple next = childLeftTuple.getHandleNext();
if ( object == childLeftTuple.getFactHandle().getObject() ) {
deleteChildLeftTuple( propagationContext, mem.getStagedLeftTuples(), null, childLeftTuple );
}
childLeftTuple = next;
}
}
mem.getBetaMemory().setNodeDirty(wm);
}
}
}
| ngs-mtech/drools | drools-core/src/main/java/org/drools/core/phreak/ReactiveObjectUtil.java | Java | apache-2.0 | 5,219 |
import compiletime.uninitialized
object Test {
var x1: Int => Float => Double = uninitialized
var x2: (Int => Float) => Double = uninitialized
var x3: Int => Double
def main(args: Array[String]): Unit = {
x1 = "a"
x2 = "b"
x3 = "c"
}
}
| dotty-staging/dotty | tests/untried/neg/nested-fn-print.scala | Scala | apache-2.0 | 259 |
#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
#
# This script is provided as an example of how to parse the Kerberos CSV file.
# It is for illustrative purposes only and should not be used for any other purpose.
#
############################
## NOTE:
## 1) This script should be executed on NameNode host as that host is guaranteed to have all the users needed while creating keytab file
## 2) The script has been verified to work in gce environment and
## vagrant environment documented at ambari wiki: https://cwiki.apache.org/confluence/display/AMBARI/Quick+Start+Guide
###########################
usage () {
echo "Usage: keytabs.sh <HOST_PRINCIPAL_KEYTABLE.csv> <SSH_LOGIN_KEY_PATH>";
echo " <HOST_PRINCIPAL_KEYTABLE.csv>: CSV file generated by 'Enable Security Wizard' of Ambari";
echo " <SSH_LOGIN_KEY_PATH>: File path to the ssh login key for root user";
exit 1;
}
###################
## processCSVFile()
###################
processCSVFile () {
csvFile=$1;
csvFile=$(printf '%q' "$csvFile")
# Remove blank lines
sed -i '/^\s*$/d' $csvFile
touch generate_keytabs.sh;
chmod 755 generate_keytabs.sh;
echo "#!/bin/bash" > generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "## " >> generate_keytabs.sh;
echo "## Ambari Security Script Generator" >> generate_keytabs.sh;
echo "## " >> generate_keytabs.sh;
echo "## Ambari security script is generated which should be run on the" >> generate_keytabs.sh;
echo "## Kerberos server machine." >> generate_keytabs.sh;
echo "## " >> generate_keytabs.sh;
echo "## Running the generated script will create host specific keytabs folders." >> generate_keytabs.sh;
echo "## Each of those folders will contain service specific keytab files with " >> generate_keytabs.sh;
echo "## appropriate permissions. There folders should be copied as the appropriate" >> generate_keytabs.sh;
echo "## host's '/etc/security/keytabs' folder" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
rm -f commands.mkdir;
rm -f commands.chmod;
rm -f commands.addprinc;
rm -f commands.xst
rm -f commands.xst.cp
rm -f commands.chown.1
rm -f commands.chmod.1
rm -f commands.chmod.2
rm -f commands.tar
seenHosts="";
seenPrincipals="";
echo "mkdir -p ./tmp_keytabs" >> commands.mkdir;
sed 1d $csvFile | while read line; do
hostName=`echo $line|cut -d , -f 1`;
service=`echo $line|cut -d , -f 2`;
principal=`echo $line|cut -d , -f 3`;
localUserName=`echo $line|cut -d , -f 5`;
keytabFile=`echo $line|cut -d , -f 6 | cut -d , -f 6 | rev | cut -d '/' -f 1 | rev`;
fullKeytabFilePath=`echo $line|cut -d , -f 6`;
keytabFilePath=${fullKeytabFilePath%/*};
owner=`echo $line|cut -d , -f 7`;
group=`echo $line|cut -d , -f 9`;
acl=`echo $line|cut -d , -f 11`;
if [[ $seenHosts != *$hostName* ]]; then
echo "mkdir -p ./keytabs_$hostName" >> commands.mkdir;
echo "chmod 755 ./keytabs_$hostName" >> commands.chmod;
echo "chown -R root:$group `pwd`/keytabs_$hostName" >> commands.chown.1
echo "tar -cvf keytabs_$hostName.tar -C keytabs_$hostName ." >> commands.tar
seenHosts="$seenHosts$hostName";
fi
if [[ $seenPrincipals != *" $principal"* ]]; then
echo -e "kadmin.local -q \"addprinc -randkey $principal\"" >> commands.addprinc;
seenPrincipals="$seenPrincipals $principal"
fi
tmpKeytabFile="`pwd`/tmp_keytabs/$keytabFile";
newKeytabPath="`pwd`/keytabs_$hostName$keytabFilePath";
newKeytabFile="$newKeytabPath/$keytabFile";
if [ ! -f $tmpKeytabFile ]; then
echo "kadmin.local -q \"xst -k $tmpKeytabFile $principal\"" >> commands.xst;
fi
if [ ! -d $newKeytabPath ]; then
echo "mkdir -p $newKeytabPath" >> commands.mkdir;
fi
echo "cp $tmpKeytabFile $newKeytabFile" >> commands.xst.cp
echo "chmod $acl $newKeytabFile" >> commands.chmod.2
echo "chown $owner:$group $newKeytabFile" >> commands.chown.1
done;
echo "" >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Making host specific keytab folders" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.mkdir >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Changing permissions for host specific keytab folders" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.chmod >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Creating Kerberos Principals" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.addprinc >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Creating Kerberos Principal keytabs in host specific keytab folders" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.xst >> generate_keytabs.sh;
cat commands.xst.cp >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Changing ownerships of host specific keytab files" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.chown.1 >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Changing access permissions of host specific keytab files" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
#cat commands.chmod.1
cat commands.chmod.2 >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Packaging keytab folders" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
cat commands.tar >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "# Cleanup" >> generate_keytabs.sh;
echo "###########################################################################" >> generate_keytabs.sh;
echo "rm -rf ./tmp_keytabs" >> generate_keytabs.sh;
echo "" >> generate_keytabs.sh;
echo "echo \"****************************************************************************\"" >> generate_keytabs.sh;
echo "echo \"****************************************************************************\"" >> generate_keytabs.sh;
echo "echo \"** Copy and extract 'keytabs_[hostname].tar' files onto respective hosts. **\"" >> generate_keytabs.sh;
echo "echo \"** **\"" >> generate_keytabs.sh;
echo "echo \"** Generated keytab files are preserved in the 'tmp_keytabs' folder. **\"" >> generate_keytabs.sh;
echo "echo \"****************************************************************************\"" >> generate_keytabs.sh;
echo "echo \"****************************************************************************\"" >> generate_keytabs.sh;
rm -f commands.mkdir >> generate_keytabs.sh;
rm -f commands.chmod >> generate_keytabs.sh;
rm -f commands.addprinc >> generate_keytabs.sh;
rm -f commands.xst >> generate_keytabs.sh;
rm -f commands.xst.cp >> generate_keytabs.sh;
rm -f commands.chown.1 >> generate_keytabs.sh;
rm -f commands.chmod.1 >> generate_keytabs.sh;
rm -f commands.chmod.2 >> generate_keytabs.sh;
rm -f commands.tar >> generate_keytabs.sh;
# generate keytabs
sh ./generate_keytabs.sh
}
########################
## installKDC () : Install rng tools,pdsh on KDC host and KDC packages on all host. Modify krb5 file
########################
installKDC () {
csvFile=$1;
sshLoginKey=$2;
HOSTNAME=`hostname --fqdn`
scriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
krb5_new_conf=$scriptDir"/krb5.conf"
krb5_conf="/etc/krb5.conf"
#export additional path for suse and centos5
PATH=$PATH:/usr/lib/mit/sbin/:/usr/kerberos/sbin/:/usr/sbin/:/sbin/
# Install rng tools
installRngtools
# Install kdc server on this host
$inst_cmd $server_packages
# Configure /etc/krb5.conf
cp $krb5_conf $krb5_conf".bak"
cp $krb5_new_conf $krb5_conf
sed -i "s/\(kdc *= *\).*kerberos.example.com.*/\1$HOSTNAME/" $krb5_conf
sed -i "s/\(admin_server *= *\).*kerberos.example.com.*/\1$HOSTNAME/" $krb5_conf
# Create principal key and start services
if [[ ! -f $principal_file ]]; then
echo -ne '\n\n' | kdb5_util create -s
fi
eval $kdc_service_start
eval $kadmin_service_start
# Install pdsh on this host
$inst_cmd pdsh;
chown root:root -R /usr;
eval `ssh-agent`
ssh-add $sshLoginKey
hostNames='';
# remove empty lines
sed -i "/^\s*$/d" $csvFile;
sed 1d $csvFile > $csvFile.tmp
while read line; do
hostName=`echo $line|cut -d , -f 1`;
if [ -z "$hostNames" ]; then
hostNames=$hostName;
continue;
fi
if [[ $hostNames != *$hostName* ]]; then
hostNames=$hostNames,$hostName;
fi
echo "hostNames $hostNames";
done < $csvFile.tmp;
rm -f $csvFile.tmp
# Check all hosts for passwordless ssh
OLD_IFS=$IFS
IFS=,
for host in $hostNames; do
checkSSH $host
done
IFS=$OLD_IFS
export PDSH_SSH_ARGS_APPEND="-q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=publickey"
pdsh -R ssh -w $hostNames "$inst_cmd $client_packages"
pdsh -R ssh -w $hostNames "$inst_cmd pdsh"
pdsh -R ssh -w $hostNames chown root:root -R /usr
pdcp -R ssh -w $hostNames $krb5_conf $krb5_conf
}
########################
## distributeKeytabs () : Distribute the tar on all respective hosts root directory and untar it
########################
distributeKeytabs () {
shopt -s nullglob
filearray=(keytabs_*tar)
for i in ${filearray[@]}; do
derivedname=${i%.*}
derivedname=${derivedname##keytabs_}
echo $derivedname
scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $i root@$derivedname:/
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@$derivedname "cd /;tar xvf $i --no-overwrite-dir"
done
}
########################
## getEnvironmentCMD () : get linux distribution type and package manager
########################
getEnvironmentCMD () {
os=`python -c 'import sys; sys.path.append("/usr/lib/python2.6/site-packages/"); from ambari_commons import OSCheck; print OSCheck.get_os_family()'`
version=`python -c 'import sys; sys.path.append("/usr/lib/python2.6/site-packages/"); from ambari_commons import OSCheck; print OSCheck.get_os_major_version()'`
os=$os$version;
case $os in
'ubuntu12' )
pkgmgr='apt-get'
inst_cmd="env DEBIAN_FRONTEND=noninteractive /usr/bin/$pkgmgr --allow-unauthenticated --assume-yes install -f "
client_packages="krb5-user libpam-krb5 libpam-ccreds auth-client-config"
server_packages="krb5-kdc krb5-admin-server $client_packages"
rng_tools="rng-tools"
principal_file="/etc/krb5kdc/principal"
kdc_service_start="service krb5-kdc start || service krb5-kdc status"
kadmin_service_start="service krb5-admin-server start || service krb5-admin-server status"
;;
'redhat5' )
pkgmgr='yum'
inst_cmd="/usr/bin/$pkgmgr -y install "
client_packages="krb5-workstation"
server_packages="krb5-server krb5-libs krb5-auth-dialog $client_packages"
rng_tools="rng-utils"
principal_file="/var/kerberos/krb5kdc/principal"
kdc_service_start="service kadmin start; service kadmin status"
kadmin_service_start="service krb5kdc start || service krb5kdc status"
;;
'redhat6' )
pkgmgr='yum'
inst_cmd="/usr/bin/$pkgmgr -y install "
client_packages="krb5-workstation"
server_packages="krb5-server krb5-libs krb5-auth-dialog $client_packages"
rng_tools="rng-tools"
principal_file="/var/kerberos/krb5kdc/principal"
kdc_service_start="service kadmin start; service kadmin status"
kadmin_service_start="service krb5kdc start || service krb5kdc status"
;;
'suse11' )
pkgmgr='zypper'
inst_cmd="/usr/bin/$pkgmgr install --auto-agree-with-licenses --no-confirm "
client_packages="krb5-client"
server_packages="krb5 krb5-server $client_packages"
rng_tools="rng-tools"
principal_file="/var/lib/kerberos/krb5kdc/principal"
kdc_service_start="service kadmind start || service kadmind status"
kadmin_service_start="service krb5kdc start || service krb5kdc status"
;;
esac
}
########################
## checkUser () : If the user executing the script is not "root" then exit
########################
checkUser () {
userid=`id -u`;
if (($userid != 0)); then
echo "ERROR: The script needs to be executed by root user"
exit 1;
fi
}
########################
## checkSSH () : If passwordless ssh for root is not configured then exit
########################
checkSSH () {
host=$1
ssh -oPasswordAuthentication=no -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $host "exit 0" && return_value=0 || return_value=$? && true
if [[ $return_value != 0 ]]; then
echo "ERROR: Passwordless ssh for user root is not configured for host $host"
exit 1;
fi
}
########################
## installRngtools () : Install and start rng-tools
########################
installRngtools () {
$inst_cmd $rng_tools
echo $inst_cmd $rng_utils
if [ $os == 'ubuntu12' ] || [ $os == 'suse11' ]; then
echo "HRNGDEVICE=/dev/urandom" >> /etc/default/rng-tools
/etc/init.d/rng-tools start || true
elif [ $os == 'redhat5' ]; then
/sbin/rngd -r /dev/urandom -o /dev/random -f -t .001 --background
else
sed -i "s/\(EXTRAOPTIONS *= *\).*/\1\"-r \/dev\/urandom\"/" "/etc/sysconfig/rngd"
# start rngd
/etc/init.d/rngd start
fi
}
if (($# != 2)); then
usage
fi
set -e
checkUser
getEnvironmentCMD
installKDC $@
processCSVFile $@
distributeKeytabs $@ | zouzhberk/ambaridemo | demo-server/src/main/resources/scripts/kerberos-setup.sh | Shell | apache-2.0 | 16,267 |
//// [trailingCommasInFunctionParametersAndArguments.ts]
function f1(x,) {}
f1(1,);
function f2(...args,) {}
f2(...[],);
// Not confused by overloads
declare function f3(x, ): number;
declare function f3(x, y,): string;
<number>f3(1,);
<string>f3(1, 2,);
// Works for constructors too
class X {
constructor(a,) { }
// See trailingCommasInGetter.ts
set x(value,) { }
}
interface Y {
new(x,);
(x,);
}
new X(1,);
//// [trailingCommasInFunctionParametersAndArguments.js]
function f1(x) { }
f1(1);
function f2() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
}
f2.apply(void 0, []);
f3(1);
f3(1, 2);
// Works for constructors too
var X = (function () {
function X(a) {
}
Object.defineProperty(X.prototype, "x", {
// See trailingCommasInGetter.ts
set: function (value) { },
enumerable: true,
configurable: true
});
return X;
}());
new X(1);
| chuckjaz/TypeScript | tests/baselines/reference/trailingCommasInFunctionParametersAndArguments.js | JavaScript | apache-2.0 | 1,010 |
<?php
$encrypted = "9hzft/nQs7HTlazA8khf67wIBizBBEXCj5/VbSxcEuPMPb6pmB9bZeiFxc7eUsfU";
$cipher= "des-ecb";
$key="Fs9H083h5TtLdkAePgmgOxxIPEEptSOz59MzCR4sh5w=";
$iv="FuK2LSE8rnYPLU/P9Z7d2w==";
$ciphertext = @openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
echo $cipher . " : " . $ciphertext."\n";
$cipher= "des-cbc";
$encrypted = "YNGhhYZopS4ac5SaENpICZR1wSJkcyL99Xda9091S9xYihPqeaI1HYxBpv0zmWw7";
$ciphertext = @openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
echo $cipher . " : " . $ciphertext."\n"; | iolevel/peachpie-concept | tests/openssl/openssl_decrypt_002.php | PHP | apache-2.0 | 511 |
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
// This source code is also licensed under the GPLv2 license found in the
// COPYING file in the root directory of this source tree.
#ifndef ROCKSDB_LITE
#ifndef GFLAGS
#include <cstdio>
int main() {
fprintf(stderr, "Please install gflags to run rocksdb tools\n");
return 1;
}
#else
#include <cstdio>
#include <atomic>
#include <gflags/gflags.h>
#include "db/write_batch_internal.h"
#include "rocksdb/db.h"
#include "rocksdb/types.h"
#include "util/testutil.h"
// Run a thread to perform Put's.
// Another thread uses GetUpdatesSince API to keep getting the updates.
// options :
// --num_inserts = the num of inserts the first thread should perform.
// --wal_ttl = the wal ttl for the run.
using namespace rocksdb;
using GFLAGS::ParseCommandLineFlags;
using GFLAGS::SetUsageMessage;
struct DataPumpThread {
size_t no_records;
DB* db; // Assumption DB is Open'ed already.
};
static std::string RandomString(Random* rnd, int len) {
std::string r;
test::RandomString(rnd, len, &r);
return r;
}
static void DataPumpThreadBody(void* arg) {
DataPumpThread* t = reinterpret_cast<DataPumpThread*>(arg);
DB* db = t->db;
Random rnd(301);
size_t i = 0;
while(i++ < t->no_records) {
if(!db->Put(WriteOptions(), Slice(RandomString(&rnd, 500)),
Slice(RandomString(&rnd, 500))).ok()) {
fprintf(stderr, "Error in put\n");
exit(1);
}
}
}
struct ReplicationThread {
std::atomic<bool> stop;
DB* db;
volatile size_t no_read;
};
static void ReplicationThreadBody(void* arg) {
ReplicationThread* t = reinterpret_cast<ReplicationThread*>(arg);
DB* db = t->db;
unique_ptr<TransactionLogIterator> iter;
SequenceNumber currentSeqNum = 1;
while (!t->stop.load(std::memory_order_acquire)) {
iter.reset();
Status s;
while(!db->GetUpdatesSince(currentSeqNum, &iter).ok()) {
if (t->stop.load(std::memory_order_acquire)) {
return;
}
}
fprintf(stderr, "Refreshing iterator\n");
for(;iter->Valid(); iter->Next(), t->no_read++, currentSeqNum++) {
BatchResult res = iter->GetBatch();
if (res.sequence != currentSeqNum) {
fprintf(stderr,
"Missed a seq no. b/w %ld and %ld\n",
(long)currentSeqNum,
(long)res.sequence);
exit(1);
}
}
}
}
DEFINE_uint64(num_inserts, 1000, "the num of inserts the first thread should"
" perform.");
DEFINE_uint64(wal_ttl_seconds, 1000, "the wal ttl for the run(in seconds)");
DEFINE_uint64(wal_size_limit_MB, 10, "the wal size limit for the run"
"(in MB)");
int main(int argc, const char** argv) {
SetUsageMessage(
std::string("\nUSAGE:\n") + std::string(argv[0]) +
" --num_inserts=<num_inserts> --wal_ttl_seconds=<WAL_ttl_seconds>" +
" --wal_size_limit_MB=<WAL_size_limit_MB>");
ParseCommandLineFlags(&argc, const_cast<char***>(&argv), true);
Env* env = Env::Default();
std::string default_db_path;
env->GetTestDirectory(&default_db_path);
default_db_path += "db_repl_stress";
Options options;
options.create_if_missing = true;
options.WAL_ttl_seconds = FLAGS_wal_ttl_seconds;
options.WAL_size_limit_MB = FLAGS_wal_size_limit_MB;
DB* db;
DestroyDB(default_db_path, options);
Status s = DB::Open(options, default_db_path, &db);
if (!s.ok()) {
fprintf(stderr, "Could not open DB due to %s\n", s.ToString().c_str());
exit(1);
}
DataPumpThread dataPump;
dataPump.no_records = FLAGS_num_inserts;
dataPump.db = db;
env->StartThread(DataPumpThreadBody, &dataPump);
ReplicationThread replThread;
replThread.db = db;
replThread.no_read = 0;
replThread.stop.store(false, std::memory_order_release);
env->StartThread(ReplicationThreadBody, &replThread);
while(replThread.no_read < FLAGS_num_inserts);
replThread.stop.store(true, std::memory_order_release);
if (replThread.no_read < dataPump.no_records) {
// no. read should be => than inserted.
fprintf(stderr,
"No. of Record's written and read not same\nRead : %" ROCKSDB_PRIszt
" Written : %" ROCKSDB_PRIszt "\n",
replThread.no_read, dataPump.no_records);
exit(1);
}
fprintf(stderr, "Successful!\n");
exit(0);
}
#endif // GFLAGS
#else // ROCKSDB_LITE
#include <stdio.h>
int main(int argc, char** argv) {
fprintf(stderr, "Not supported in lite mode.\n");
return 1;
}
#endif // ROCKSDB_LITE
| hkernbach/arangodb | 3rdParty/rocksdb/v5.6.X/tools/db_repl_stress.cc | C++ | apache-2.0 | 4,726 |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for recurrent v2 layers functionality other than GRU, LSTM.
See also: lstm_v2_test.py, gru_v2_test.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import test_util
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.layers import recurrent_v2 as rnn_v2
from tensorflow.python.platform import test
@keras_parameterized.run_all_keras_modes
class RNNV2Test(keras_parameterized.TestCase):
@parameterized.parameters([rnn_v2.LSTM, rnn_v2.GRU])
def test_device_placement(self, layer):
if not test.is_gpu_available():
self.skipTest('Need GPU for testing.')
vocab_size = 20
embedding_dim = 10
batch_size = 8
timestep = 12
units = 5
x = np.random.randint(0, vocab_size, size=(batch_size, timestep))
y = np.random.randint(0, vocab_size, size=(batch_size, timestep))
# Test when GPU is available but not used, the graph should be properly
# created with CPU ops.
with test_util.device(use_gpu=False):
model = keras.Sequential([
keras.layers.Embedding(vocab_size, embedding_dim,
batch_input_shape=[batch_size, timestep]),
layer(units, return_sequences=True, stateful=True),
keras.layers.Dense(vocab_size)
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
run_eagerly=testing_utils.should_run_eagerly())
model.fit(x, y, epochs=1, shuffle=False)
@parameterized.parameters([rnn_v2.LSTM, rnn_v2.GRU])
def test_reset_dropout_mask_between_batch(self, layer):
# See https://github.com/tensorflow/tensorflow/issues/29187 for more details
batch_size = 8
timestep = 12
embedding_dim = 10
units = 5
layer = layer(units, dropout=0.5, recurrent_dropout=0.5)
inputs = np.random.random((batch_size, timestep, embedding_dim)).astype(
np.float32)
previous_dropout, previous_recurrent_dropout = None, None
for _ in range(5):
layer(inputs, training=True)
dropout = layer.cell.get_dropout_mask_for_cell(inputs, training=True)
recurrent_dropout = layer.cell.get_recurrent_dropout_mask_for_cell(
inputs, training=True)
if previous_dropout is not None:
self.assertNotAllClose(self.evaluate(previous_dropout),
self.evaluate(dropout))
previous_dropout = dropout
if previous_recurrent_dropout is not None:
self.assertNotAllClose(self.evaluate(previous_recurrent_dropout),
self.evaluate(recurrent_dropout))
previous_recurrent_dropout = recurrent_dropout
@parameterized.parameters([rnn_v2.LSTM, rnn_v2.GRU])
def test_recurrent_dropout_with_stateful_RNN(self, layer):
# See https://github.com/tensorflow/tensorflow/issues/27829 for details.
# The issue was caused by using inplace mul for a variable, which was a
# warning for RefVariable, but an error for ResourceVariable in 2.0
keras.models.Sequential([
layer(128, stateful=True, return_sequences=True, dropout=0.2,
batch_input_shape=[32, None, 5], recurrent_dropout=0.2)
])
def test_recurrent_dropout_saved_model(self):
if not context.executing_eagerly():
self.skipTest('v2-only test')
inputs = keras.Input(shape=(784, 3), name='digits')
x = keras.layers.GRU(64, activation='relu', name='GRU', dropout=0.1)(inputs)
x = keras.layers.Dense(64, activation='relu', name='dense')(x)
outputs = keras.layers.Dense(
10, activation='softmax', name='predictions')(
x)
model = keras.Model(inputs=inputs, outputs=outputs, name='3_layer')
model.save(os.path.join(self.get_temp_dir(), 'model'), save_format='tf')
if __name__ == '__main__':
test.main()
| gunan/tensorflow | tensorflow/python/keras/layers/recurrent_v2_test.py | Python | apache-2.0 | 4,779 |
package com.pushtorefresh.storio.contentresolver.operations.delete;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import com.pushtorefresh.storio.contentresolver.ContentResolverTypeMapping;
import com.pushtorefresh.storio.contentresolver.StorIOContentResolver;
import com.pushtorefresh.storio.operations.internal.OnSubscribeExecuteAsBlocking;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.schedulers.Schedulers;
import static com.pushtorefresh.storio.internal.Environment.throwExceptionIfRxJavaIsNotAvailable;
/**
* Prepared Delete Operation for {@link StorIOContentResolver}.
*
* @param <T> type of objects to delete.
*/
public final class PreparedDeleteCollectionOfObjects<T> extends PreparedDelete<DeleteResults<T>> {
@NonNull
private final Collection<T> objects;
@Nullable
private final DeleteResolver<T> explicitDeleteResolver;
PreparedDeleteCollectionOfObjects(@NonNull StorIOContentResolver storIOContentResolver,
@NonNull Collection<T> objects,
@Nullable DeleteResolver<T> explicitDeleteResolver) {
super(storIOContentResolver);
this.objects = objects;
this.explicitDeleteResolver = explicitDeleteResolver;
}
/**
* Executes Delete Operation immediately in current thread.
* <p>
* Notice: This is blocking I/O operation that should not be executed on the Main Thread,
* it can cause ANR (Activity Not Responding dialog), block the UI and drop animations frames.
* So please, call this method on some background thread. See {@link WorkerThread}.
*
* @return non-null results of Delete Operation.
*/
@SuppressWarnings("unchecked")
@WorkerThread
@NonNull
@Override
public DeleteResults<T> executeAsBlocking() {
final StorIOContentResolver.Internal internal = storIOContentResolver.internal();
// Nullable
final List<SimpleImmutableEntry> objectsAndDeleteResolvers;
if (explicitDeleteResolver != null) {
objectsAndDeleteResolvers = null;
} else {
objectsAndDeleteResolvers = new ArrayList<SimpleImmutableEntry>(objects.size());
for (final T object : objects) {
final ContentResolverTypeMapping<T> typeMapping
= (ContentResolverTypeMapping<T>) internal.typeMapping(object.getClass());
if (typeMapping == null) {
throw new IllegalStateException("One of the objects from the collection does not have type mapping: " +
"object = " + object + ", object.class = " + object.getClass() + "," +
"ContentProvider was not affected by this operation, please add type mapping for this type");
}
objectsAndDeleteResolvers.add(new SimpleImmutableEntry(
object,
typeMapping.deleteResolver()
));
}
}
final Map<T, DeleteResult> results = new HashMap<T, DeleteResult>(objects.size());
if (explicitDeleteResolver != null) {
for (final T object : objects) {
final DeleteResult deleteResult = explicitDeleteResolver.performDelete(storIOContentResolver, object);
results.put(object, deleteResult);
}
} else {
for (final SimpleImmutableEntry<T, DeleteResolver<T>> objectAndDeleteResolver : objectsAndDeleteResolvers) {
final T object = objectAndDeleteResolver.getKey();
final DeleteResolver<T> deleteResolver = objectAndDeleteResolver.getValue();
final DeleteResult deleteResult = deleteResolver.performDelete(storIOContentResolver, object);
results.put(object, deleteResult);
}
}
return DeleteResults.newInstance(results);
}
/**
* Creates {@link Observable} which will perform Delete Operation and send result to observer.
* <p>
* Returned {@link Observable} will be "Cold Observable", which means that it performs
* delete only after subscribing to it. Also, it emits the result once.
* <p>
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>Operates on {@link Schedulers#io()}.</dd>
* </dl>
*
* @return non-null {@link Observable} which will perform Delete Operation.
* and send result to observer.
*/
@NonNull
@Override
public Observable<DeleteResults<T>> createObservable() {
throwExceptionIfRxJavaIsNotAvailable("createObservable()");
return Observable
.create(OnSubscribeExecuteAsBlocking.newInstance(this))
.subscribeOn(Schedulers.io());
}
/**
* Builder for {@link PreparedDeleteCollectionOfObjects}.
*
* @param <T> type of objects.
*/
public static final class Builder<T> {
@NonNull
private final StorIOContentResolver storIOContentResolver;
@NonNull
private final Collection<T> objects;
@Nullable
private DeleteResolver<T> deleteResolver;
/**
* Creates builder for {@link PreparedDeleteCollectionOfObjects}.
*
* @param storIOContentResolver non-null instance of {@link StorIOContentResolver}.
* @param objects non-null collection of objects to delete.
*/
public Builder(@NonNull StorIOContentResolver storIOContentResolver, @NonNull Collection<T> objects) {
this.storIOContentResolver = storIOContentResolver;
this.objects = objects;
}
/**
* Optional: Specifies resolver for Delete Operation.
* Allows you to customise behavior of Delete Operation.
* <p>
* Can be set via {@link ContentResolverTypeMapping},
* If value is not set via {@link ContentResolverTypeMapping}
* or explicitly — exception will be thrown.
*
* @param deleteResolver nullable resolver for Delete Operation.
* @return builder.
*/
@NonNull
public Builder<T> withDeleteResolver(@Nullable DeleteResolver<T> deleteResolver) {
this.deleteResolver = deleteResolver;
return this;
}
/**
* Builds instance of {@link PreparedDeleteCollectionOfObjects}.
*
* @return instance of {@link PreparedDeleteCollectionOfObjects}.
*/
@NonNull
public PreparedDeleteCollectionOfObjects<T> prepare() {
return new PreparedDeleteCollectionOfObjects<T>(
storIOContentResolver,
objects,
deleteResolver
);
}
}
}
| gostik/tweets-key-value | storio-content-resolver/src/main/java/com/pushtorefresh/storio/contentresolver/operations/delete/PreparedDeleteCollectionOfObjects.java | Java | apache-2.0 | 7,040 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto
namespace Google\Cloud\Compute\V1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
*
* Generated from protobuf message <code>google.cloud.compute.v1.NodeTypeAggregatedList</code>
*/
class NodeTypeAggregatedList extends \Google\Protobuf\Internal\Message
{
/**
* [Output Only] Unique identifier for the resource; defined by the server.
*
* Generated from protobuf field <code>optional string id = 3355;</code>
*/
private $id = null;
/**
* A list of NodeTypesScopedList resources.
*
* Generated from protobuf field <code>map<string, .google.cloud.compute.v1.NodeTypesScopedList> items = 100526016;</code>
*/
private $items;
/**
* [Output Only] Type of resource.Always compute#nodeTypeAggregatedList for aggregated lists of node types.
*
* Generated from protobuf field <code>optional string kind = 3292052;</code>
*/
private $kind = null;
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
*
* Generated from protobuf field <code>optional string next_page_token = 79797525;</code>
*/
private $next_page_token = null;
/**
* [Output Only] Server-defined URL for this resource.
*
* Generated from protobuf field <code>optional string self_link = 456214797;</code>
*/
private $self_link = null;
/**
* [Output Only] Unreachable resources.
*
* Generated from protobuf field <code>repeated string unreachables = 243372063;</code>
*/
private $unreachables;
/**
* [Output Only] Informational warning message.
*
* Generated from protobuf field <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
private $warning = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type string $id
* [Output Only] Unique identifier for the resource; defined by the server.
* @type array|\Google\Protobuf\Internal\MapField $items
* A list of NodeTypesScopedList resources.
* @type string $kind
* [Output Only] Type of resource.Always compute#nodeTypeAggregatedList for aggregated lists of node types.
* @type string $next_page_token
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
* @type string $self_link
* [Output Only] Server-defined URL for this resource.
* @type string[]|\Google\Protobuf\Internal\RepeatedField $unreachables
* [Output Only] Unreachable resources.
* @type \Google\Cloud\Compute\V1\Warning $warning
* [Output Only] Informational warning message.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
parent::__construct($data);
}
/**
* [Output Only] Unique identifier for the resource; defined by the server.
*
* Generated from protobuf field <code>optional string id = 3355;</code>
* @return string
*/
public function getId()
{
return isset($this->id) ? $this->id : '';
}
public function hasId()
{
return isset($this->id);
}
public function clearId()
{
unset($this->id);
}
/**
* [Output Only] Unique identifier for the resource; defined by the server.
*
* Generated from protobuf field <code>optional string id = 3355;</code>
* @param string $var
* @return $this
*/
public function setId($var)
{
GPBUtil::checkString($var, True);
$this->id = $var;
return $this;
}
/**
* A list of NodeTypesScopedList resources.
*
* Generated from protobuf field <code>map<string, .google.cloud.compute.v1.NodeTypesScopedList> items = 100526016;</code>
* @return \Google\Protobuf\Internal\MapField
*/
public function getItems()
{
return $this->items;
}
/**
* A list of NodeTypesScopedList resources.
*
* Generated from protobuf field <code>map<string, .google.cloud.compute.v1.NodeTypesScopedList> items = 100526016;</code>
* @param array|\Google\Protobuf\Internal\MapField $var
* @return $this
*/
public function setItems($var)
{
$arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Compute\V1\NodeTypesScopedList::class);
$this->items = $arr;
return $this;
}
/**
* [Output Only] Type of resource.Always compute#nodeTypeAggregatedList for aggregated lists of node types.
*
* Generated from protobuf field <code>optional string kind = 3292052;</code>
* @return string
*/
public function getKind()
{
return isset($this->kind) ? $this->kind : '';
}
public function hasKind()
{
return isset($this->kind);
}
public function clearKind()
{
unset($this->kind);
}
/**
* [Output Only] Type of resource.Always compute#nodeTypeAggregatedList for aggregated lists of node types.
*
* Generated from protobuf field <code>optional string kind = 3292052;</code>
* @param string $var
* @return $this
*/
public function setKind($var)
{
GPBUtil::checkString($var, True);
$this->kind = $var;
return $this;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
*
* Generated from protobuf field <code>optional string next_page_token = 79797525;</code>
* @return string
*/
public function getNextPageToken()
{
return isset($this->next_page_token) ? $this->next_page_token : '';
}
public function hasNextPageToken()
{
return isset($this->next_page_token);
}
public function clearNextPageToken()
{
unset($this->next_page_token);
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
*
* Generated from protobuf field <code>optional string next_page_token = 79797525;</code>
* @param string $var
* @return $this
*/
public function setNextPageToken($var)
{
GPBUtil::checkString($var, True);
$this->next_page_token = $var;
return $this;
}
/**
* [Output Only] Server-defined URL for this resource.
*
* Generated from protobuf field <code>optional string self_link = 456214797;</code>
* @return string
*/
public function getSelfLink()
{
return isset($this->self_link) ? $this->self_link : '';
}
public function hasSelfLink()
{
return isset($this->self_link);
}
public function clearSelfLink()
{
unset($this->self_link);
}
/**
* [Output Only] Server-defined URL for this resource.
*
* Generated from protobuf field <code>optional string self_link = 456214797;</code>
* @param string $var
* @return $this
*/
public function setSelfLink($var)
{
GPBUtil::checkString($var, True);
$this->self_link = $var;
return $this;
}
/**
* [Output Only] Unreachable resources.
*
* Generated from protobuf field <code>repeated string unreachables = 243372063;</code>
* @return \Google\Protobuf\Internal\RepeatedField
*/
public function getUnreachables()
{
return $this->unreachables;
}
/**
* [Output Only] Unreachable resources.
*
* Generated from protobuf field <code>repeated string unreachables = 243372063;</code>
* @param string[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setUnreachables($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING);
$this->unreachables = $arr;
return $this;
}
/**
* [Output Only] Informational warning message.
*
* Generated from protobuf field <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
* @return \Google\Cloud\Compute\V1\Warning|null
*/
public function getWarning()
{
return $this->warning;
}
public function hasWarning()
{
return isset($this->warning);
}
public function clearWarning()
{
unset($this->warning);
}
/**
* [Output Only] Informational warning message.
*
* Generated from protobuf field <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
* @param \Google\Cloud\Compute\V1\Warning $var
* @return $this
*/
public function setWarning($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Compute\V1\Warning::class);
$this->warning = $var;
return $this;
}
}
| googleapis/google-cloud-php-compute | src/V1/NodeTypeAggregatedList.php | PHP | apache-2.0 | 10,212 |
package com.shata.migration.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateUtils {
private final static Logger log = LoggerFactory.getLogger(DateUtils.class);
public static String currentDateStr() {
Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(currentDate);
}
public static Date currentDate() {
return Calendar.getInstance().getTime();
}
public static long currentLong() {
return Calendar.getInstance().getTimeInMillis();
}
public static boolean isTimeout(long time, int min) {
return (Calendar.getInstance().getTimeInMillis() - time) > min * 60 * 1000;
}
public static boolean isTimeout(String time, int min) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
log.error("日期解析错误," + time, e);
}
if(null == date) {
return false;
}
return (Calendar.getInstance().getTimeInMillis() - date.getTime()) > min * 60 * 1000;
}
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -2);
long old = cal.getTimeInMillis();
System.out.println(isTimeout(old, 1));
System.out.println(isTimeout(old, 2));
System.out.println(isTimeout(old, 3));
}
}
| sdgdsffdsfff/migration-tool | src/main/java/com/shata/migration/utils/DateUtils.java | Java | apache-2.0 | 1,518 |
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <array>
#include <memory>
#include <utility>
#include "api/audio_codecs/opus/audio_encoder_opus.h"
#include "common_audio/mocks/mock_smoothing_filter.h"
#include "common_types.h" // NOLINT(build/include)
#include "modules/audio_coding/audio_network_adaptor/mock/mock_audio_network_adaptor.h"
#include "modules/audio_coding/codecs/opus/audio_encoder_opus.h"
#include "modules/audio_coding/codecs/opus/opus_interface.h"
#include "modules/audio_coding/neteq/tools/audio_loop.h"
#include "rtc_base/checks.h"
#include "rtc_base/fakeclock.h"
#include "test/field_trial.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "test/testsupport/fileutils.h"
namespace webrtc {
using ::testing::NiceMock;
using ::testing::Return;
namespace {
const CodecInst kDefaultOpusSettings = {105, "opus", 48000, 960, 1, 32000};
constexpr int64_t kInitialTimeUs = 12345678;
AudioEncoderOpusConfig CreateConfig(const CodecInst& codec_inst) {
AudioEncoderOpusConfig config;
config.frame_size_ms = rtc::CheckedDivExact(codec_inst.pacsize, 48);
config.num_channels = codec_inst.channels;
config.bitrate_bps = codec_inst.rate;
config.application = config.num_channels == 1
? AudioEncoderOpusConfig::ApplicationMode::kVoip
: AudioEncoderOpusConfig::ApplicationMode::kAudio;
config.supported_frame_lengths_ms.push_back(config.frame_size_ms);
return config;
}
AudioEncoderOpusConfig CreateConfigWithParameters(
const SdpAudioFormat::Parameters& params) {
const SdpAudioFormat format("opus", 48000, 2, params);
return *AudioEncoderOpus::SdpToConfig(format);
}
struct AudioEncoderOpusStates {
std::shared_ptr<MockAudioNetworkAdaptor*> mock_audio_network_adaptor;
MockSmoothingFilter* mock_bitrate_smoother;
std::unique_ptr<AudioEncoderOpusImpl> encoder;
std::unique_ptr<rtc::ScopedFakeClock> fake_clock;
AudioEncoderOpusConfig config;
};
AudioEncoderOpusStates CreateCodec(size_t num_channels) {
AudioEncoderOpusStates states;
states.mock_audio_network_adaptor =
std::make_shared<MockAudioNetworkAdaptor*>(nullptr);
states.fake_clock.reset(new rtc::ScopedFakeClock());
states.fake_clock->SetTimeMicros(kInitialTimeUs);
std::weak_ptr<MockAudioNetworkAdaptor*> mock_ptr(
states.mock_audio_network_adaptor);
AudioEncoderOpusImpl::AudioNetworkAdaptorCreator creator =
[mock_ptr](const std::string&, RtcEventLog* event_log) {
std::unique_ptr<MockAudioNetworkAdaptor> adaptor(
new NiceMock<MockAudioNetworkAdaptor>());
EXPECT_CALL(*adaptor, Die());
if (auto sp = mock_ptr.lock()) {
*sp = adaptor.get();
} else {
RTC_NOTREACHED();
}
return adaptor;
};
CodecInst codec_inst = kDefaultOpusSettings;
codec_inst.channels = num_channels;
states.config = CreateConfig(codec_inst);
std::unique_ptr<MockSmoothingFilter> bitrate_smoother(
new MockSmoothingFilter());
states.mock_bitrate_smoother = bitrate_smoother.get();
states.encoder.reset(new AudioEncoderOpusImpl(
states.config, codec_inst.pltype, std::move(creator),
std::move(bitrate_smoother)));
return states;
}
AudioEncoderRuntimeConfig CreateEncoderRuntimeConfig() {
constexpr int kBitrate = 40000;
constexpr int kFrameLength = 60;
constexpr bool kEnableFec = true;
constexpr bool kEnableDtx = false;
constexpr size_t kNumChannels = 1;
constexpr float kPacketLossFraction = 0.1f;
AudioEncoderRuntimeConfig config;
config.bitrate_bps = kBitrate;
config.frame_length_ms = kFrameLength;
config.enable_fec = kEnableFec;
config.enable_dtx = kEnableDtx;
config.num_channels = kNumChannels;
config.uplink_packet_loss_fraction = kPacketLossFraction;
return config;
}
void CheckEncoderRuntimeConfig(const AudioEncoderOpusImpl* encoder,
const AudioEncoderRuntimeConfig& config) {
EXPECT_EQ(*config.bitrate_bps, encoder->GetTargetBitrate());
EXPECT_EQ(*config.frame_length_ms, encoder->next_frame_length_ms());
EXPECT_EQ(*config.enable_fec, encoder->fec_enabled());
EXPECT_EQ(*config.enable_dtx, encoder->GetDtx());
EXPECT_EQ(*config.num_channels, encoder->num_channels_to_encode());
}
// Create 10ms audio data blocks for a total packet size of "packet_size_ms".
std::unique_ptr<test::AudioLoop> Create10msAudioBlocks(
const std::unique_ptr<AudioEncoderOpusImpl>& encoder,
int packet_size_ms) {
const std::string file_name =
test::ResourcePath("audio_coding/testfile32kHz", "pcm");
std::unique_ptr<test::AudioLoop> speech_data(new test::AudioLoop());
int audio_samples_per_ms =
rtc::CheckedDivExact(encoder->SampleRateHz(), 1000);
if (!speech_data->Init(
file_name,
packet_size_ms * audio_samples_per_ms *
encoder->num_channels_to_encode(),
10 * audio_samples_per_ms * encoder->num_channels_to_encode()))
return nullptr;
return speech_data;
}
} // namespace
TEST(AudioEncoderOpusTest, DefaultApplicationModeMono) {
auto states = CreateCodec(1);
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kVoip,
states.encoder->application());
}
TEST(AudioEncoderOpusTest, DefaultApplicationModeStereo) {
auto states = CreateCodec(2);
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kAudio,
states.encoder->application());
}
TEST(AudioEncoderOpusTest, ChangeApplicationMode) {
auto states = CreateCodec(2);
EXPECT_TRUE(
states.encoder->SetApplication(AudioEncoder::Application::kSpeech));
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kVoip,
states.encoder->application());
}
TEST(AudioEncoderOpusTest, ResetWontChangeApplicationMode) {
auto states = CreateCodec(2);
// Trigger a reset.
states.encoder->Reset();
// Verify that the mode is still kAudio.
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kAudio,
states.encoder->application());
// Now change to kVoip.
EXPECT_TRUE(
states.encoder->SetApplication(AudioEncoder::Application::kSpeech));
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kVoip,
states.encoder->application());
// Trigger a reset again.
states.encoder->Reset();
// Verify that the mode is still kVoip.
EXPECT_EQ(AudioEncoderOpusConfig::ApplicationMode::kVoip,
states.encoder->application());
}
TEST(AudioEncoderOpusTest, ToggleDtx) {
auto states = CreateCodec(2);
// Enable DTX
EXPECT_TRUE(states.encoder->SetDtx(true));
EXPECT_TRUE(states.encoder->GetDtx());
// Turn off DTX.
EXPECT_TRUE(states.encoder->SetDtx(false));
EXPECT_FALSE(states.encoder->GetDtx());
}
TEST(AudioEncoderOpusTest,
OnReceivedUplinkBandwidthWithoutAudioNetworkAdaptor) {
auto states = CreateCodec(1);
// Constants are replicated from audio_states.encoderopus.cc.
const int kMinBitrateBps = 6000;
const int kMaxBitrateBps = 510000;
// Set a too low bitrate.
states.encoder->OnReceivedUplinkBandwidth(kMinBitrateBps - 1, rtc::nullopt);
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set a too high bitrate.
states.encoder->OnReceivedUplinkBandwidth(kMaxBitrateBps + 1, rtc::nullopt);
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
// Set the minimum rate.
states.encoder->OnReceivedUplinkBandwidth(kMinBitrateBps, rtc::nullopt);
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set the maximum rate.
states.encoder->OnReceivedUplinkBandwidth(kMaxBitrateBps, rtc::nullopt);
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
// Set rates from kMaxBitrateBps up to 32000 bps.
for (int rate = kMinBitrateBps; rate <= 32000; rate += 1000) {
states.encoder->OnReceivedUplinkBandwidth(rate, rtc::nullopt);
EXPECT_EQ(rate, states.encoder->GetTargetBitrate());
}
}
namespace {
// Returns a vector with the n evenly-spaced numbers a, a + (b - a)/(n - 1),
// ..., b.
std::vector<float> IntervalSteps(float a, float b, size_t n) {
RTC_DCHECK_GT(n, 1u);
const float step = (b - a) / (n - 1);
std::vector<float> points;
points.push_back(a);
for (size_t i = 1; i < n - 1; ++i)
points.push_back(a + i * step);
points.push_back(b);
return points;
}
// Sets the packet loss rate to each number in the vector in turn, and verifies
// that the loss rate as reported by the encoder is |expected_return| for all
// of them.
void TestSetPacketLossRate(AudioEncoderOpusStates* states,
const std::vector<float>& losses,
float expected_return) {
// |kSampleIntervalMs| is chosen to ease the calculation since
// 0.9999 ^ 184198 = 1e-8. Which minimizes the effect of
// PacketLossFractionSmoother used in AudioEncoderOpus.
constexpr int64_t kSampleIntervalMs = 184198;
for (float loss : losses) {
states->encoder->OnReceivedUplinkPacketLossFraction(loss);
states->fake_clock->AdvanceTime(
rtc::TimeDelta::FromMilliseconds(kSampleIntervalMs));
EXPECT_FLOAT_EQ(expected_return, states->encoder->packet_loss_rate());
}
}
} // namespace
TEST(AudioEncoderOpusTest, PacketLossRateOptimized) {
auto states = CreateCodec(1);
auto I = [](float a, float b) { return IntervalSteps(a, b, 10); };
constexpr float eps = 1e-8f;
// Note that the order of the following calls is critical.
// clang-format off
TestSetPacketLossRate(&states, I(0.00f , 0.01f - eps), 0.00f);
TestSetPacketLossRate(&states, I(0.01f + eps, 0.06f - eps), 0.01f);
TestSetPacketLossRate(&states, I(0.06f + eps, 0.11f - eps), 0.05f);
TestSetPacketLossRate(&states, I(0.11f + eps, 0.22f - eps), 0.10f);
TestSetPacketLossRate(&states, I(0.22f + eps, 1.00f ), 0.20f);
TestSetPacketLossRate(&states, I(1.00f , 0.18f + eps), 0.20f);
TestSetPacketLossRate(&states, I(0.18f - eps, 0.09f + eps), 0.10f);
TestSetPacketLossRate(&states, I(0.09f - eps, 0.04f + eps), 0.05f);
TestSetPacketLossRate(&states, I(0.04f - eps, 0.01f + eps), 0.01f);
TestSetPacketLossRate(&states, I(0.01f - eps, 0.00f ), 0.00f);
// clang-format on
}
TEST(AudioEncoderOpusTest, SetReceiverFrameLengthRange) {
auto states = CreateCodec(2);
// Before calling to |SetReceiverFrameLengthRange|,
// |supported_frame_lengths_ms| should contain only the frame length being
// used.
using ::testing::ElementsAre;
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(),
ElementsAre(states.encoder->next_frame_length_ms()));
states.encoder->SetReceiverFrameLengthRange(0, 12345);
states.encoder->SetReceiverFrameLengthRange(21, 60);
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(), ElementsAre(60));
states.encoder->SetReceiverFrameLengthRange(20, 59);
EXPECT_THAT(states.encoder->supported_frame_lengths_ms(), ElementsAre(20));
}
TEST(AudioEncoderOpusTest,
InvokeAudioNetworkAdaptorOnReceivedUplinkPacketLossFraction) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any packet loss fraction is fine.
constexpr float kUplinkPacketLoss = 0.1f;
EXPECT_CALL(**states.mock_audio_network_adaptor,
SetUplinkPacketLossFraction(kUplinkPacketLoss));
states.encoder->OnReceivedUplinkPacketLossFraction(kUplinkPacketLoss);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedUplinkBandwidth) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any target audio bitrate is fine.
constexpr int kTargetAudioBitrate = 30000;
constexpr int64_t kProbingIntervalMs = 3000;
EXPECT_CALL(**states.mock_audio_network_adaptor,
SetTargetAudioBitrate(kTargetAudioBitrate));
EXPECT_CALL(*states.mock_bitrate_smoother,
SetTimeConstantMs(kProbingIntervalMs * 4));
EXPECT_CALL(*states.mock_bitrate_smoother, AddSample(kTargetAudioBitrate));
states.encoder->OnReceivedUplinkBandwidth(kTargetAudioBitrate,
kProbingIntervalMs);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedRtt) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any rtt is fine.
constexpr int kRtt = 30;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetRtt(kRtt));
states.encoder->OnReceivedRtt(kRtt);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, InvokeAudioNetworkAdaptorOnReceivedOverhead) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
auto config = CreateEncoderRuntimeConfig();
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config));
// Since using mock audio network adaptor, any overhead is fine.
constexpr size_t kOverhead = 64;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetOverhead(kOverhead));
states.encoder->OnReceivedOverhead(kOverhead);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest,
PacketLossFractionSmoothedOnSetUplinkPacketLossFraction) {
auto states = CreateCodec(2);
// The values are carefully chosen so that if no smoothing is made, the test
// will fail.
constexpr float kPacketLossFraction_1 = 0.02f;
constexpr float kPacketLossFraction_2 = 0.198f;
// |kSecondSampleTimeMs| is chosen to ease the calculation since
// 0.9999 ^ 6931 = 0.5.
constexpr int64_t kSecondSampleTimeMs = 6931;
// First time, no filtering.
states.encoder->OnReceivedUplinkPacketLossFraction(kPacketLossFraction_1);
EXPECT_FLOAT_EQ(0.01f, states.encoder->packet_loss_rate());
states.fake_clock->AdvanceTime(
rtc::TimeDelta::FromMilliseconds(kSecondSampleTimeMs));
states.encoder->OnReceivedUplinkPacketLossFraction(kPacketLossFraction_2);
// Now the output of packet loss fraction smoother should be
// (0.02 + 0.198) / 2 = 0.109, which reach the threshold for the optimized
// packet loss rate to increase to 0.05. If no smoothing has been made, the
// optimized packet loss rate should have been increase to 0.1.
EXPECT_FLOAT_EQ(0.05f, states.encoder->packet_loss_rate());
}
TEST(AudioEncoderOpusTest, DoNotInvokeSetTargetBitrateIfOverheadUnknown) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
auto states = CreateCodec(2);
states.encoder->OnReceivedUplinkBandwidth(kDefaultOpusSettings.rate * 2,
rtc::nullopt);
// Since |OnReceivedOverhead| has not been called, the codec bitrate should
// not change.
EXPECT_EQ(kDefaultOpusSettings.rate, states.encoder->GetTargetBitrate());
}
TEST(AudioEncoderOpusTest, OverheadRemovedFromTargetAudioBitrate) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
auto states = CreateCodec(2);
constexpr size_t kOverheadBytesPerPacket = 64;
states.encoder->OnReceivedOverhead(kOverheadBytesPerPacket);
constexpr int kTargetBitrateBps = 40000;
states.encoder->OnReceivedUplinkBandwidth(kTargetBitrateBps, rtc::nullopt);
int packet_rate = rtc::CheckedDivExact(48000, kDefaultOpusSettings.pacsize);
EXPECT_EQ(kTargetBitrateBps -
8 * static_cast<int>(kOverheadBytesPerPacket) * packet_rate,
states.encoder->GetTargetBitrate());
}
TEST(AudioEncoderOpusTest, BitrateBounded) {
test::ScopedFieldTrials override_field_trials(
"WebRTC-SendSideBwe-WithOverhead/Enabled/");
constexpr int kMinBitrateBps = 6000;
constexpr int kMaxBitrateBps = 510000;
auto states = CreateCodec(2);
constexpr size_t kOverheadBytesPerPacket = 64;
states.encoder->OnReceivedOverhead(kOverheadBytesPerPacket);
int packet_rate = rtc::CheckedDivExact(48000, kDefaultOpusSettings.pacsize);
// Set a target rate that is smaller than |kMinBitrateBps| when overhead is
// subtracted. The eventual codec rate should be bounded by |kMinBitrateBps|.
int target_bitrate =
kOverheadBytesPerPacket * 8 * packet_rate + kMinBitrateBps - 1;
states.encoder->OnReceivedUplinkBandwidth(target_bitrate, rtc::nullopt);
EXPECT_EQ(kMinBitrateBps, states.encoder->GetTargetBitrate());
// Set a target rate that is greater than |kMaxBitrateBps| when overhead is
// subtracted. The eventual codec rate should be bounded by |kMaxBitrateBps|.
target_bitrate =
kOverheadBytesPerPacket * 8 * packet_rate + kMaxBitrateBps + 1;
states.encoder->OnReceivedUplinkBandwidth(target_bitrate, rtc::nullopt);
EXPECT_EQ(kMaxBitrateBps, states.encoder->GetTargetBitrate());
}
// Verifies that the complexity adaptation in the config works as intended.
TEST(AudioEncoderOpusTest, ConfigComplexityAdaptation) {
AudioEncoderOpusConfig config;
config.low_rate_complexity = 8;
config.complexity = 6;
// Bitrate within hysteresis window. Expect empty output.
config.bitrate_bps = 12500;
EXPECT_EQ(rtc::nullopt, AudioEncoderOpusImpl::GetNewComplexity(config));
// Bitrate below hysteresis window. Expect higher complexity.
config.bitrate_bps = 10999;
EXPECT_EQ(8, AudioEncoderOpusImpl::GetNewComplexity(config));
// Bitrate within hysteresis window. Expect empty output.
config.bitrate_bps = 12500;
EXPECT_EQ(rtc::nullopt, AudioEncoderOpusImpl::GetNewComplexity(config));
// Bitrate above hysteresis window. Expect lower complexity.
config.bitrate_bps = 14001;
EXPECT_EQ(6, AudioEncoderOpusImpl::GetNewComplexity(config));
}
// Verifies that the bandwidth adaptation in the config works as intended.
TEST(AudioEncoderOpusTest, ConfigBandwidthAdaptation) {
AudioEncoderOpusConfig config;
// Sample rate of Opus.
constexpr size_t kOpusRateKhz = 48;
std::vector<int16_t> silence(
kOpusRateKhz * config.frame_size_ms * config.num_channels, 0);
constexpr size_t kMaxBytes = 1000;
uint8_t bitstream[kMaxBytes];
OpusEncInst* inst;
EXPECT_EQ(0, WebRtcOpus_EncoderCreate(
&inst, config.num_channels,
config.application ==
AudioEncoderOpusConfig::ApplicationMode::kVoip
? 0
: 1));
// Bitrate below minmum wideband. Expect narrowband.
config.bitrate_bps = rtc::Optional<int>(7999);
auto bandwidth = AudioEncoderOpusImpl::GetNewBandwidth(config, inst);
EXPECT_EQ(rtc::Optional<int>(OPUS_BANDWIDTH_NARROWBAND), bandwidth);
WebRtcOpus_SetBandwidth(inst, *bandwidth);
// It is necessary to encode here because Opus has some logic in the encoder
// that goes from the user-set bandwidth to the used and returned one.
WebRtcOpus_Encode(inst, silence.data(),
rtc::CheckedDivExact(silence.size(), config.num_channels),
kMaxBytes, bitstream);
// Bitrate not yet above maximum narrowband. Expect empty.
config.bitrate_bps = rtc::Optional<int>(9000);
bandwidth = AudioEncoderOpusImpl::GetNewBandwidth(config, inst);
EXPECT_EQ(rtc::Optional<int>(), bandwidth);
// Bitrate above maximum narrowband. Expect wideband.
config.bitrate_bps = rtc::Optional<int>(9001);
bandwidth = AudioEncoderOpusImpl::GetNewBandwidth(config, inst);
EXPECT_EQ(rtc::Optional<int>(OPUS_BANDWIDTH_WIDEBAND), bandwidth);
WebRtcOpus_SetBandwidth(inst, *bandwidth);
// It is necessary to encode here because Opus has some logic in the encoder
// that goes from the user-set bandwidth to the used and returned one.
WebRtcOpus_Encode(inst, silence.data(),
rtc::CheckedDivExact(silence.size(), config.num_channels),
kMaxBytes, bitstream);
// Bitrate not yet below minimum wideband. Expect empty.
config.bitrate_bps = rtc::Optional<int>(8000);
bandwidth = AudioEncoderOpusImpl::GetNewBandwidth(config, inst);
EXPECT_EQ(rtc::Optional<int>(), bandwidth);
// Bitrate above automatic threshold. Expect automatic.
config.bitrate_bps = rtc::Optional<int>(12001);
bandwidth = AudioEncoderOpusImpl::GetNewBandwidth(config, inst);
EXPECT_EQ(rtc::Optional<int>(OPUS_AUTO), bandwidth);
EXPECT_EQ(0, WebRtcOpus_EncoderFree(inst));
}
TEST(AudioEncoderOpusTest, EmptyConfigDoesNotAffectEncoderSettings) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
auto config = CreateEncoderRuntimeConfig();
AudioEncoderRuntimeConfig empty_config;
EXPECT_CALL(**states.mock_audio_network_adaptor, GetEncoderRuntimeConfig())
.WillOnce(Return(config))
.WillOnce(Return(empty_config));
constexpr size_t kOverhead = 64;
EXPECT_CALL(**states.mock_audio_network_adaptor, SetOverhead(kOverhead))
.Times(2);
states.encoder->OnReceivedOverhead(kOverhead);
states.encoder->OnReceivedOverhead(kOverhead);
CheckEncoderRuntimeConfig(states.encoder.get(), config);
}
TEST(AudioEncoderOpusTest, UpdateUplinkBandwidthInAudioNetworkAdaptor) {
auto states = CreateCodec(2);
states.encoder->EnableAudioNetworkAdaptor("", nullptr);
std::array<int16_t, 480 * 2> audio;
audio.fill(0);
rtc::Buffer encoded;
EXPECT_CALL(*states.mock_bitrate_smoother, GetAverage())
.WillOnce(Return(50000));
EXPECT_CALL(**states.mock_audio_network_adaptor, SetUplinkBandwidth(50000));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
// Repeat update uplink bandwidth tests.
for (int i = 0; i < 5; i++) {
// Don't update till it is time to update again.
states.fake_clock->AdvanceTime(rtc::TimeDelta::FromMilliseconds(
states.config.uplink_bandwidth_update_interval_ms - 1));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
// Update when it is time to update.
EXPECT_CALL(*states.mock_bitrate_smoother, GetAverage())
.WillOnce(Return(40000));
EXPECT_CALL(**states.mock_audio_network_adaptor, SetUplinkBandwidth(40000));
states.fake_clock->AdvanceTime(rtc::TimeDelta::FromMilliseconds(1));
states.encoder->Encode(
0, rtc::ArrayView<const int16_t>(audio.data(), audio.size()), &encoded);
}
}
TEST(AudioEncoderOpusTest, EncodeAtMinBitrate) {
auto states = CreateCodec(1);
constexpr int kNumPacketsToEncode = 2;
auto audio_frames =
Create10msAudioBlocks(states.encoder, kNumPacketsToEncode * 20);
ASSERT_TRUE(audio_frames) << "Create10msAudioBlocks failed";
rtc::Buffer encoded;
uint32_t rtp_timestamp = 12345; // Just a number not important to this test.
states.encoder->OnReceivedUplinkBandwidth(0, rtc::nullopt);
for (int packet_index = 0; packet_index < kNumPacketsToEncode;
packet_index++) {
// Make sure we are not encoding before we have enough data for
// a 20ms packet.
for (int index = 0; index < 1; index++) {
states.encoder->Encode(rtp_timestamp, audio_frames->GetNextBlock(),
&encoded);
EXPECT_EQ(0u, encoded.size());
}
// Should encode now.
states.encoder->Encode(rtp_timestamp, audio_frames->GetNextBlock(),
&encoded);
EXPECT_GT(encoded.size(), 0u);
encoded.Clear();
}
}
TEST(AudioEncoderOpusTest, TestConfigDefaults) {
const auto config_opt = AudioEncoderOpus::SdpToConfig({"opus", 48000, 2});
ASSERT_TRUE(config_opt);
EXPECT_EQ(48000, config_opt->max_playback_rate_hz);
EXPECT_EQ(1u, config_opt->num_channels);
EXPECT_FALSE(config_opt->fec_enabled);
EXPECT_FALSE(config_opt->dtx_enabled);
EXPECT_EQ(20, config_opt->frame_size_ms);
}
TEST(AudioEncoderOpusTest, TestConfigFromParams) {
const auto config1 = CreateConfigWithParameters({{"stereo", "0"}});
EXPECT_EQ(1U, config1.num_channels);
const auto config2 = CreateConfigWithParameters({{"stereo", "1"}});
EXPECT_EQ(2U, config2.num_channels);
const auto config3 = CreateConfigWithParameters({{"useinbandfec", "0"}});
EXPECT_FALSE(config3.fec_enabled);
const auto config4 = CreateConfigWithParameters({{"useinbandfec", "1"}});
EXPECT_TRUE(config4.fec_enabled);
const auto config5 = CreateConfigWithParameters({{"usedtx", "0"}});
EXPECT_FALSE(config5.dtx_enabled);
const auto config6 = CreateConfigWithParameters({{"usedtx", "1"}});
EXPECT_TRUE(config6.dtx_enabled);
const auto config7 = CreateConfigWithParameters({{"cbr", "0"}});
EXPECT_FALSE(config7.cbr_enabled);
const auto config8 = CreateConfigWithParameters({{"cbr", "1"}});
EXPECT_TRUE(config8.cbr_enabled);
const auto config9 =
CreateConfigWithParameters({{"maxplaybackrate", "12345"}});
EXPECT_EQ(12345, config9.max_playback_rate_hz);
const auto config10 =
CreateConfigWithParameters({{"maxaveragebitrate", "96000"}});
EXPECT_EQ(96000, config10.bitrate_bps);
const auto config11 = CreateConfigWithParameters({{"maxptime", "40"}});
for (int frame_length : config11.supported_frame_lengths_ms) {
EXPECT_LE(frame_length, 40);
}
const auto config12 = CreateConfigWithParameters({{"minptime", "40"}});
for (int frame_length : config12.supported_frame_lengths_ms) {
EXPECT_GE(frame_length, 40);
}
const auto config13 = CreateConfigWithParameters({{"ptime", "40"}});
EXPECT_EQ(40, config13.frame_size_ms);
constexpr int kMinSupportedFrameLength = 10;
constexpr int kMaxSupportedFrameLength =
WEBRTC_OPUS_SUPPORT_120MS_PTIME ? 120 : 60;
const auto config14 = CreateConfigWithParameters({{"ptime", "1"}});
EXPECT_EQ(kMinSupportedFrameLength, config14.frame_size_ms);
const auto config15 = CreateConfigWithParameters({{"ptime", "2000"}});
EXPECT_EQ(kMaxSupportedFrameLength, config15.frame_size_ms);
}
TEST(AudioEncoderOpusTest, TestConfigFromInvalidParams) {
const webrtc::SdpAudioFormat format("opus", 48000, 2);
const auto default_config = *AudioEncoderOpus::SdpToConfig(format);
#if WEBRTC_OPUS_SUPPORT_120MS_PTIME
const std::vector<int> default_supported_frame_lengths_ms({20, 60, 120});
#else
const std::vector<int> default_supported_frame_lengths_ms({20, 60});
#endif
AudioEncoderOpusConfig config;
config = CreateConfigWithParameters({{"stereo", "invalid"}});
EXPECT_EQ(default_config.num_channels, config.num_channels);
config = CreateConfigWithParameters({{"useinbandfec", "invalid"}});
EXPECT_EQ(default_config.fec_enabled, config.fec_enabled);
config = CreateConfigWithParameters({{"usedtx", "invalid"}});
EXPECT_EQ(default_config.dtx_enabled, config.dtx_enabled);
config = CreateConfigWithParameters({{"cbr", "invalid"}});
EXPECT_EQ(default_config.dtx_enabled, config.dtx_enabled);
config = CreateConfigWithParameters({{"maxplaybackrate", "0"}});
EXPECT_EQ(default_config.max_playback_rate_hz, config.max_playback_rate_hz);
config = CreateConfigWithParameters({{"maxplaybackrate", "-23"}});
EXPECT_EQ(default_config.max_playback_rate_hz, config.max_playback_rate_hz);
config = CreateConfigWithParameters({{"maxplaybackrate", "not a number!"}});
EXPECT_EQ(default_config.max_playback_rate_hz, config.max_playback_rate_hz);
config = CreateConfigWithParameters({{"maxaveragebitrate", "0"}});
EXPECT_EQ(6000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxaveragebitrate", "-1000"}});
EXPECT_EQ(6000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxaveragebitrate", "1024000"}});
EXPECT_EQ(510000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxaveragebitrate", "not a number!"}});
EXPECT_EQ(default_config.bitrate_bps, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxptime", "invalid"}});
EXPECT_EQ(default_supported_frame_lengths_ms,
config.supported_frame_lengths_ms);
config = CreateConfigWithParameters({{"minptime", "invalid"}});
EXPECT_EQ(default_supported_frame_lengths_ms,
config.supported_frame_lengths_ms);
config = CreateConfigWithParameters({{"ptime", "invalid"}});
EXPECT_EQ(default_supported_frame_lengths_ms,
config.supported_frame_lengths_ms);
}
// Test that bitrate will be overridden by the "maxaveragebitrate" parameter.
// Also test that the "maxaveragebitrate" can't be set to values outside the
// range of 6000 and 510000
TEST(AudioEncoderOpusTest, SetSendCodecOpusMaxAverageBitrate) {
// Ignore if less than 6000.
const auto config1 = AudioEncoderOpus::SdpToConfig(
{"opus", 48000, 2, {{"maxaveragebitrate", "5999"}}});
EXPECT_EQ(6000, config1->bitrate_bps);
// Ignore if larger than 510000.
const auto config2 = AudioEncoderOpus::SdpToConfig(
{"opus", 48000, 2, {{"maxaveragebitrate", "510001"}}});
EXPECT_EQ(510000, config2->bitrate_bps);
const auto config3 = AudioEncoderOpus::SdpToConfig(
{"opus", 48000, 2, {{"maxaveragebitrate", "200000"}}});
EXPECT_EQ(200000, config3->bitrate_bps);
}
// Test maxplaybackrate <= 8000 triggers Opus narrow band mode.
TEST(AudioEncoderOpusTest, SetMaxPlaybackRateNb) {
auto config = CreateConfigWithParameters({{"maxplaybackrate", "8000"}});
EXPECT_EQ(8000, config.max_playback_rate_hz);
EXPECT_EQ(12000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxplaybackrate", "8000"},
{"stereo", "1"}});
EXPECT_EQ(8000, config.max_playback_rate_hz);
EXPECT_EQ(24000, config.bitrate_bps);
}
// Test 8000 < maxplaybackrate <= 12000 triggers Opus medium band mode.
TEST(AudioEncoderOpusTest, SetMaxPlaybackRateMb) {
auto config = CreateConfigWithParameters({{"maxplaybackrate", "8001"}});
EXPECT_EQ(8001, config.max_playback_rate_hz);
EXPECT_EQ(20000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxplaybackrate", "8001"},
{"stereo", "1"}});
EXPECT_EQ(8001, config.max_playback_rate_hz);
EXPECT_EQ(40000, config.bitrate_bps);
}
// Test 12000 < maxplaybackrate <= 16000 triggers Opus wide band mode.
TEST(AudioEncoderOpusTest, SetMaxPlaybackRateWb) {
auto config = CreateConfigWithParameters({{"maxplaybackrate", "12001"}});
EXPECT_EQ(12001, config.max_playback_rate_hz);
EXPECT_EQ(20000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxplaybackrate", "12001"},
{"stereo", "1"}});
EXPECT_EQ(12001, config.max_playback_rate_hz);
EXPECT_EQ(40000, config.bitrate_bps);
}
// Test 16000 < maxplaybackrate <= 24000 triggers Opus super wide band mode.
TEST(AudioEncoderOpusTest, SetMaxPlaybackRateSwb) {
auto config = CreateConfigWithParameters({{"maxplaybackrate", "16001"}});
EXPECT_EQ(16001, config.max_playback_rate_hz);
EXPECT_EQ(32000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxplaybackrate", "16001"},
{"stereo", "1"}});
EXPECT_EQ(16001, config.max_playback_rate_hz);
EXPECT_EQ(64000, config.bitrate_bps);
}
// Test 24000 < maxplaybackrate triggers Opus full band mode.
TEST(AudioEncoderOpusTest, SetMaxPlaybackRateFb) {
auto config = CreateConfigWithParameters({{"maxplaybackrate", "24001"}});
EXPECT_EQ(24001, config.max_playback_rate_hz);
EXPECT_EQ(32000, config.bitrate_bps);
config = CreateConfigWithParameters({{"maxplaybackrate", "24001"},
{"stereo", "1"}});
EXPECT_EQ(24001, config.max_playback_rate_hz);
EXPECT_EQ(64000, config.bitrate_bps);
}
TEST(AudioEncoderOpusTest, OpusFlagDtxAsNonSpeech) {
// Create encoder with DTX enabled.
AudioEncoderOpusConfig config;
config.dtx_enabled = true;
constexpr int payload_type = 17;
const auto encoder = AudioEncoderOpus::MakeAudioEncoder(config, payload_type);
// Open file containing speech and silence.
const std::string kInputFileName =
webrtc::test::ResourcePath("audio_coding/testfile32kHz", "pcm");
test::AudioLoop audio_loop;
// Use the file as if it were sampled at 48 kHz.
constexpr int kSampleRateHz = 48000;
EXPECT_EQ(kSampleRateHz, encoder->SampleRateHz());
constexpr size_t kMaxLoopLengthSamples =
kSampleRateHz * 10; // Max 10 second loop.
constexpr size_t kInputBlockSizeSamples =
10 * kSampleRateHz / 1000; // 10 ms.
EXPECT_TRUE(audio_loop.Init(kInputFileName, kMaxLoopLengthSamples,
kInputBlockSizeSamples));
// Encode.
AudioEncoder::EncodedInfo info;
rtc::Buffer encoded(500);
int nonspeech_frames = 0;
int max_nonspeech_frames = 0;
int dtx_frames = 0;
int max_dtx_frames = 0;
uint32_t rtp_timestamp = 0u;
for (size_t i = 0; i < 500; ++i) {
encoded.Clear();
// Every second call to the encoder will generate an Opus packet.
for (int j = 0; j < 2; j++) {
info =
encoder->Encode(rtp_timestamp, audio_loop.GetNextBlock(), &encoded);
rtp_timestamp += kInputBlockSizeSamples;
}
// Bookkeeping of number of DTX frames.
if (info.encoded_bytes <= 2) {
++dtx_frames;
} else {
if (dtx_frames > max_dtx_frames)
max_dtx_frames = dtx_frames;
dtx_frames = 0;
}
// Bookkeeping of number of non-speech frames.
if (info.speech == 0) {
++nonspeech_frames;
} else {
if (nonspeech_frames > max_nonspeech_frames)
max_nonspeech_frames = nonspeech_frames;
nonspeech_frames = 0;
}
}
// Maximum number of consecutive non-speech packets should exceed 20.
EXPECT_GT(max_nonspeech_frames, 20);
}
} // namespace webrtc
| wangcy6/storm_app | frame/c++/webrtc-master/modules/audio_coding/codecs/opus/audio_encoder_opus_unittest.cc | C++ | apache-2.0 | 34,355 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: grafeas/v1/grafeas.proto
namespace Grafeas\V1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Response for creating notes in batch.
*
* Generated from protobuf message <code>grafeas.v1.BatchCreateNotesResponse</code>
*/
class BatchCreateNotesResponse extends \Google\Protobuf\Internal\Message
{
/**
* The notes that were created.
*
* Generated from protobuf field <code>repeated .grafeas.v1.Note notes = 1;</code>
*/
private $notes;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type \Grafeas\V1\Note[]|\Google\Protobuf\Internal\RepeatedField $notes
* The notes that were created.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Grafeas\V1\Grafeas::initOnce();
parent::__construct($data);
}
/**
* The notes that were created.
*
* Generated from protobuf field <code>repeated .grafeas.v1.Note notes = 1;</code>
* @return \Google\Protobuf\Internal\RepeatedField
*/
public function getNotes()
{
return $this->notes;
}
/**
* The notes that were created.
*
* Generated from protobuf field <code>repeated .grafeas.v1.Note notes = 1;</code>
* @param \Grafeas\V1\Note[]|\Google\Protobuf\Internal\RepeatedField $var
* @return $this
*/
public function setNotes($var)
{
$arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Grafeas\V1\Note::class);
$this->notes = $arr;
return $this;
}
}
| googleapis/php-grafeas | src/V1/BatchCreateNotesResponse.php | PHP | apache-2.0 | 1,785 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.beam.sdk.transforms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.beam.sdk.coders.IterableCoder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.testing.TestStream;
import org.apache.beam.sdk.testing.TestStream.ElementEvent;
import org.apache.beam.sdk.testing.TestStream.Event;
import org.apache.beam.sdk.testing.TestStream.ProcessingTimeEvent;
import org.apache.beam.sdk.testing.TestStream.WatermarkEvent;
import org.apache.beam.sdk.testing.UsesStatefulParDo;
import org.apache.beam.sdk.testing.UsesTestStream;
import org.apache.beam.sdk.testing.UsesTimersInParDo;
import org.apache.beam.sdk.transforms.windowing.AfterPane;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.GlobalWindows;
import org.apache.beam.sdk.transforms.windowing.Repeatedly;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.util.ShardedKey;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Test Class for {@link GroupIntoBatches}. */
@RunWith(JUnit4.class)
public class GroupIntoBatchesTest implements Serializable {
private static final int BATCH_SIZE = 5;
private static final long BATCH_SIZE_BYTES = 25;
private static final long EVEN_NUM_ELEMENTS = 10;
private static final long ODD_NUM_ELEMENTS = 11;
private static final int ALLOWED_LATENESS = 0;
private static final Logger LOG = LoggerFactory.getLogger(GroupIntoBatchesTest.class);
@Rule public transient TestPipeline pipeline = TestPipeline.create();
private transient ArrayList<KV<String, String>> data = createTestData(EVEN_NUM_ELEMENTS);
private static ArrayList<KV<String, String>> createTestData(long numElements) {
String[] scientists = {
"Einstein",
"Darwin",
"Copernicus",
"Pasteur",
"Curie",
"Faraday",
"Newton",
"Bohr",
"Galilei",
"Maxwell"
};
ArrayList<KV<String, String>> data = new ArrayList<>();
for (int i = 0; i < numElements; i++) {
int index = i % scientists.length;
KV<String, String> element = KV.of("key", scientists[index]);
data.add(element);
}
return data;
}
@Test
@Category({NeedsRunner.class, UsesTimersInParDo.class, UsesStatefulParDo.class})
public void testInGlobalWindowBatchSizeCount() {
PCollection<KV<String, Iterable<String>>> collection =
pipeline
.apply("Input data", Create.of(data))
.apply(GroupIntoBatches.ofSize(BATCH_SIZE))
// set output coder
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
PAssert.that("Incorrect batch size in one or more elements", collection)
.satisfies(
new SerializableFunction<Iterable<KV<String, Iterable<String>>>, Void>() {
private boolean checkBatchSizes(Iterable<KV<String, Iterable<String>>> listToCheck) {
for (KV<String, Iterable<String>> element : listToCheck) {
if (Iterables.size(element.getValue()) != BATCH_SIZE) {
return false;
}
}
return true;
}
@Override
public Void apply(Iterable<KV<String, Iterable<String>>> input) {
assertTrue(checkBatchSizes(input));
return null;
}
});
PAssert.thatSingleton("Incorrect collection size", collection.apply("Count", Count.globally()))
.isEqualTo(EVEN_NUM_ELEMENTS / BATCH_SIZE);
pipeline.run();
}
@Test
@Category({NeedsRunner.class, UsesTimersInParDo.class, UsesStatefulParDo.class})
public void testInGlobalWindowBatchSizeByteSize() {
PCollection<KV<String, Iterable<String>>> collection =
pipeline
.apply("Input data", Create.of(data))
.apply(GroupIntoBatches.ofByteSize(BATCH_SIZE_BYTES))
// set output coder
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
PAssert.that("Incorrect batch size in one or more elements", collection)
.satisfies(
new SerializableFunction<Iterable<KV<String, Iterable<String>>>, Void>() {
private boolean checkBatchSizes(Iterable<KV<String, Iterable<String>>> listToCheck) {
for (KV<String, Iterable<String>> element : listToCheck) {
long byteSize = 0;
for (String str : element.getValue()) {
if (byteSize >= BATCH_SIZE_BYTES) {
// We already reached the batch size, so extra elements are not expected.
return false;
}
try {
byteSize += StringUtf8Coder.of().getEncodedElementByteSize(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return true;
}
@Override
public Void apply(Iterable<KV<String, Iterable<String>>> input) {
assertTrue(checkBatchSizes(input));
return null;
}
});
PAssert.thatSingleton("Incorrect collection size", collection.apply("Count", Count.globally()))
.isEqualTo(3L);
pipeline.run();
}
@Test
@Category({NeedsRunner.class, UsesTimersInParDo.class, UsesStatefulParDo.class})
public void testInGlobalWindowBatchSizeByteSizeFn() {
PCollection<KV<String, Iterable<String>>> collection =
pipeline
.apply("Input data", Create.of(data))
.apply(
GroupIntoBatches.ofByteSize(
BATCH_SIZE_BYTES,
s -> {
try {
return 2 * StringUtf8Coder.of().getEncodedElementByteSize(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
}))
// set output coder
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
PAssert.that("Incorrect batch size in one or more elements", collection)
.satisfies(
new SerializableFunction<Iterable<KV<String, Iterable<String>>>, Void>() {
private boolean checkBatchSizes(Iterable<KV<String, Iterable<String>>> listToCheck) {
for (KV<String, Iterable<String>> element : listToCheck) {
long byteSize = 0;
for (String str : element.getValue()) {
if (byteSize >= BATCH_SIZE_BYTES) {
// We already reached the batch size, so extra elements are not expected.
return false;
}
try {
byteSize += 2 * StringUtf8Coder.of().getEncodedElementByteSize(str);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return true;
}
@Override
public Void apply(Iterable<KV<String, Iterable<String>>> input) {
assertTrue(checkBatchSizes(input));
return null;
}
});
PAssert.thatSingleton("Incorrect collection size", collection.apply("Count", Count.globally()))
.isEqualTo(5L);
pipeline.run();
}
@Test
@Category({NeedsRunner.class, UsesTimersInParDo.class, UsesStatefulParDo.class})
public void testWithShardedKeyInGlobalWindow() {
// Since with default sharding, the number of subshards of of a key is nondeterministic, create
// a large number of input elements and a small batch size and check there is no batch larger
// than the specified size.
int numElements = 10000;
int batchSize = 5;
PCollection<KV<ShardedKey<String>, Iterable<String>>> collection =
pipeline
.apply("Input data", Create.of(createTestData(numElements)))
.apply(GroupIntoBatches.<String, String>ofSize(batchSize).withShardedKey())
.setCoder(
KvCoder.of(
ShardedKey.Coder.of(StringUtf8Coder.of()),
IterableCoder.of(StringUtf8Coder.of())));
PAssert.that("Incorrect batch size in one or more elements", collection)
.satisfies(
new SerializableFunction<Iterable<KV<ShardedKey<String>, Iterable<String>>>, Void>() {
private boolean checkBatchSizes(
Iterable<KV<ShardedKey<String>, Iterable<String>>> listToCheck) {
for (KV<ShardedKey<String>, Iterable<String>> element : listToCheck) {
if (Iterables.size(element.getValue()) > batchSize) {
return false;
}
}
return true;
}
@Override
public Void apply(Iterable<KV<ShardedKey<String>, Iterable<String>>> input) {
assertTrue(checkBatchSizes(input));
return null;
}
});
PCollection<KV<Integer, Long>> numBatchesbyBatchSize =
collection
.apply(
"KeyByBatchSize",
MapElements.via(
new SimpleFunction<
KV<ShardedKey<String>, Iterable<String>>, KV<Integer, Integer>>() {
@Override
public KV<Integer, Integer> apply(
KV<ShardedKey<String>, Iterable<String>> input) {
int batchSize = 0;
for (String ignored : input.getValue()) {
batchSize++;
}
return KV.of(batchSize, 1);
}
}))
.apply("CountBatchesBySize", Count.perKey());
PAssert.that("Expecting majority of the batches are full", numBatchesbyBatchSize)
.satisfies(
(SerializableFunction<Iterable<KV<Integer, Long>>, Void>)
listOfBatchSize -> {
Long numFullBatches = 0L;
Long totalNumBatches = 0L;
for (KV<Integer, Long> batchSizeAndCount : listOfBatchSize) {
if (batchSizeAndCount.getKey() == batchSize) {
numFullBatches += batchSizeAndCount.getValue();
}
totalNumBatches += batchSizeAndCount.getValue();
}
assertTrue(
String.format(
"total number of batches should be in the range [%d, %d] but got %d",
numElements, numElements / batchSize, numFullBatches),
numFullBatches <= numElements && numFullBatches >= numElements / batchSize);
assertTrue(
String.format(
"number of full batches vs. total number of batches in total: %d vs. %d",
numFullBatches, totalNumBatches),
numFullBatches > totalNumBatches / 2);
return null;
});
pipeline
.runWithAdditionalOptionArgs(ImmutableList.of("--targetParallelism=1"))
.waitUntilFinish();
}
/** test behavior when the number of input elements is not evenly divisible by batch size. */
@Test
@Category({NeedsRunner.class, UsesTimersInParDo.class, UsesStatefulParDo.class})
public void testWithUnevenBatches() {
PCollection<KV<String, Iterable<String>>> collection =
pipeline
.apply("Input data", Create.of(createTestData(ODD_NUM_ELEMENTS)))
.apply(GroupIntoBatches.ofSize(BATCH_SIZE))
// set output coder
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
PAssert.that("Incorrect batch size in one or more elements", collection)
.satisfies(
new SerializableFunction<Iterable<KV<String, Iterable<String>>>, Void>() {
private boolean checkBatchSizes(Iterable<KV<String, Iterable<String>>> listToCheck) {
for (KV<String, Iterable<String>> element : listToCheck) {
// number of elements should be less than or equal to BATCH_SIZE
if (Iterables.size(element.getValue()) > BATCH_SIZE) {
return false;
}
}
return true;
}
@Override
public Void apply(Iterable<KV<String, Iterable<String>>> input) {
assertTrue(checkBatchSizes(input));
return null;
}
});
PAssert.thatSingleton("Incorrect collection size", collection.apply("Count", Count.globally()))
.isEqualTo(
// round up division for positive numbers
// https://math.stackexchange.com/questions/2591316/proof-for-integer-division-algorithm-that-rounds-up.
(ODD_NUM_ELEMENTS + BATCH_SIZE - 1) / BATCH_SIZE);
pipeline.run();
}
@Test
@Category({
NeedsRunner.class,
UsesTimersInParDo.class,
UsesTestStream.class,
UsesStatefulParDo.class
})
public void testInStreamingMode() {
int timestampInterval = 1;
Instant startInstant = new Instant(0L);
TestStream.Builder<KV<String, String>> streamBuilder =
TestStream.create(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()))
.advanceWatermarkTo(startInstant);
long offset = 0L;
for (KV<String, String> element : data) {
streamBuilder =
streamBuilder.addElements(
TimestampedValue.of(
element,
startInstant.plus(Duration.standardSeconds(offset * timestampInterval))));
offset++;
}
final long windowDuration = 6;
TestStream<KV<String, String>> stream =
streamBuilder
.advanceWatermarkTo(startInstant.plus(Duration.standardSeconds(windowDuration - 1)))
.advanceWatermarkTo(startInstant.plus(Duration.standardSeconds(windowDuration + 1)))
.advanceWatermarkTo(startInstant.plus(Duration.standardSeconds(EVEN_NUM_ELEMENTS)))
.advanceWatermarkToInfinity();
PCollection<KV<String, String>> inputCollection =
pipeline
.apply(stream)
.apply(
Window.<KV<String, String>>into(
FixedWindows.of(Duration.standardSeconds(windowDuration)))
.withAllowedLateness(Duration.millis(ALLOWED_LATENESS)));
inputCollection.apply(
ParDo.of(
new DoFn<KV<String, String>, Void>() {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
LOG.debug(
"*** ELEMENT: ({},{}) *** with timestamp {} in window {}",
c.element().getKey(),
c.element().getValue(),
c.timestamp(),
window);
}
}));
PCollection<KV<String, Iterable<String>>> outputCollection =
inputCollection
.apply(GroupIntoBatches.ofSize(BATCH_SIZE))
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
// elements have the same key and collection is divided into windows,
// so Count.perKey values are the number of elements in windows
PCollection<KV<String, Long>> countOutput =
outputCollection.apply(
"Count elements in windows after applying GroupIntoBatches", Count.perKey());
PAssert.that("Wrong number of elements in windows after GroupIntoBatches", countOutput)
.satisfies(
input -> {
Iterator<KV<String, Long>> inputIterator = input.iterator();
// first element
long count0 = inputIterator.next().getValue();
// window duration is 6 and batch size is 5, so there should be 2 elements in the
// window (flush because batchSize reached and for end of window reached)
assertEquals("Wrong number of elements in first window", 2, count0);
// second element
long count1 = inputIterator.next().getValue();
// collection is 10 elements, there is only 4 elements left, so there should be only
// one element in the window (flush because end of window/collection reached)
assertEquals("Wrong number of elements in second window", 1, count1);
// third element
return null;
});
PAssert.that("Incorrect output collection after GroupIntoBatches", outputCollection)
.satisfies(
input -> {
Iterator<KV<String, Iterable<String>>> inputIterator = input.iterator();
// first element
int size0 = Iterables.size(inputIterator.next().getValue());
// window duration is 6 and batch size is 5, so output batch size should de 5
// (flush because of batchSize reached)
assertEquals("Wrong first element batch Size", 5, size0);
// second element
int size1 = Iterables.size(inputIterator.next().getValue());
// there is only one element left in the window so batch size should be 1
// (flush because of end of window reached)
assertEquals("Wrong second element batch Size", 1, size1);
// third element
int size2 = Iterables.size(inputIterator.next().getValue());
// collection is 10 elements, there is only 4 left, so batch size should be 4
// (flush because end of collection reached)
assertEquals("Wrong third element batch Size", 4, size2);
return null;
});
pipeline.run().waitUntilFinish();
}
@Test
@Category({
NeedsRunner.class,
UsesTimersInParDo.class,
UsesTestStream.class,
UsesStatefulParDo.class
})
public void testBufferingTimerInFixedWindow() {
final Duration windowDuration = Duration.standardSeconds(4);
final Duration maxBufferingDuration = Duration.standardSeconds(5);
Instant startInstant = new Instant(0L);
TestStream.Builder<KV<String, String>> streamBuilder =
TestStream.create(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()))
.advanceWatermarkTo(startInstant);
long offset = 0L;
int timestampInterval = 1;
for (KV<String, String> element : data) {
streamBuilder =
streamBuilder
.addElements(
TimestampedValue.of(
element,
startInstant.plus(Duration.standardSeconds(offset * timestampInterval))))
// Advance the processing time by 2 secs every time an element is processed. The max
// buffering duration allowed is 5 secs, so the timer should be fired after receiving
// three elements, i.e., the batch size will not exceed 3.
.advanceProcessingTime(Duration.standardSeconds(2));
offset++;
}
TestStream<KV<String, String>> stream =
streamBuilder
.advanceWatermarkTo(startInstant.plus(Duration.standardSeconds(EVEN_NUM_ELEMENTS)))
.advanceWatermarkToInfinity();
PCollection<KV<String, String>> inputCollection =
pipeline
.apply(stream)
.apply(
Window.<KV<String, String>>into(FixedWindows.of(windowDuration))
.withAllowedLateness(Duration.millis(ALLOWED_LATENESS)));
inputCollection.apply(
ParDo.of(
new DoFn<KV<String, String>, Void>() {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
LOG.debug(
"*** ELEMENT: ({},{}) *** with timestamp {} in window {}",
c.element().getKey(),
c.element().getValue(),
c.timestamp(),
window);
}
}));
PCollection<KV<String, Iterable<String>>> outputCollection =
inputCollection
.apply(
GroupIntoBatches.<String, String>ofSize(BATCH_SIZE)
.withMaxBufferingDuration(maxBufferingDuration))
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
// Elements have the same key and collection is divided into windows,
// so Count.perKey values are the number of elements in windows
PCollection<KV<String, Long>> countOutput =
outputCollection.apply(
"Count elements in windows after applying GroupIntoBatches", Count.perKey());
PAssert.that("Wrong number of elements in windows after GroupIntoBatches", countOutput)
.satisfies(
input -> {
Iterator<KV<String, Long>> inputIterator = input.iterator();
// first element
long count0 = inputIterator.next().getValue();
// window duration is 4 , so there should be 2 elements in the window (flush because
// maxBufferingDuration reached and the end of window reached)
assertEquals("Wrong number of elements in first window", 2, count0);
// second element
long count1 = inputIterator.next().getValue();
// same as the first window
assertEquals("Wrong number of elements in second window", 2, count1);
long count2 = inputIterator.next().getValue();
// collection has 10 elements, there is only 2 elements left, so there should be only
// one element in the window (flush because end of window reached)
assertEquals("Wrong number of elements in third window", 1, count2);
return null;
});
PAssert.that("Incorrect output collection after GroupIntoBatches", outputCollection)
.satisfies(
input -> {
Iterator<KV<String, Iterable<String>>> inputIterator = input.iterator();
// first element
int size0 = Iterables.size(inputIterator.next().getValue());
// max buffering duration is 2 and the buffering deadline is set when processing the
// first element in this window, so output batch size should de 3
// (flush because of maxBufferingDuration reached)
assertEquals("Wrong first element batch Size", 3, size0);
// second element
int size1 = Iterables.size(inputIterator.next().getValue());
// there is only one element left in the first window so batch size should be 1
// (flush because of end of window reached)
assertEquals("Wrong second element batch Size", 1, size1);
// third element
int size2 = Iterables.size(inputIterator.next().getValue());
// same as the first window
assertEquals("Wrong third element batch Size", 3, size2);
// forth element
int size3 = Iterables.size(inputIterator.next().getValue());
// same as the first window
assertEquals("Wrong third element batch Size", 1, size3);
// fifth element
int size4 = Iterables.size(inputIterator.next().getValue());
// collection is 10 elements, there is only 2 left, so batch size should be 2
// (flush because end of window reached)
assertEquals("Wrong forth element batch Size", 2, size4);
return null;
});
pipeline.run().waitUntilFinish();
}
@Test
@Category({
NeedsRunner.class,
UsesTimersInParDo.class,
UsesTestStream.class,
UsesStatefulParDo.class
})
public void testBufferingTimerInGlobalWindow() {
final Duration maxBufferingDuration = Duration.standardSeconds(5);
Instant startInstant = new Instant(0L);
long offset = 0L;
int timestampInterval = 1;
List<Event<KV<String, String>>> events = new ArrayList<>();
List<TimestampedValue<KV<String, String>>> elements1 = new ArrayList<>();
for (KV<String, String> element : createTestData(EVEN_NUM_ELEMENTS / 2)) {
elements1.add(
TimestampedValue.of(
element, startInstant.plus(Duration.standardSeconds(offset * timestampInterval))));
offset++;
}
events.add(ElementEvent.add(elements1));
events.add(ProcessingTimeEvent.advanceBy(Duration.standardSeconds(100)));
List<TimestampedValue<KV<String, String>>> elements2 = new ArrayList<>();
for (KV<String, String> element : createTestData(EVEN_NUM_ELEMENTS / 2)) {
elements2.add(
TimestampedValue.of(
element, startInstant.plus(Duration.standardSeconds(offset * timestampInterval))));
offset++;
}
events.add(ElementEvent.add(elements2));
events.add(ProcessingTimeEvent.advanceBy(Duration.standardSeconds(100)));
events.add(
WatermarkEvent.advanceTo(startInstant.plus(Duration.standardSeconds(EVEN_NUM_ELEMENTS))));
TestStream<KV<String, String>> stream =
TestStream.fromRawEvents(KvCoder.of(StringUtf8Coder.of(), StringUtf8Coder.of()), events);
PCollection<KV<String, String>> inputCollection =
pipeline
.apply(stream)
.apply(
Window.<KV<String, String>>into(new GlobalWindows())
.triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(2)))
.discardingFiredPanes());
inputCollection.apply(
ParDo.of(
new DoFn<KV<String, String>, Void>() {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
LOG.debug(
"*** ELEMENT: ({},{}) *** with timestamp {} in window {}",
c.element().getKey(),
c.element().getValue(),
c.timestamp(),
window);
}
}));
// Set a batch size larger than the total number of elements. Since we're in a global window, we
// would have been waiting for all the elements without the buffering time limit.
PCollection<KV<String, Iterable<String>>> outputCollection =
inputCollection
.apply(
GroupIntoBatches.<String, String>ofSize(EVEN_NUM_ELEMENTS + 5)
.withMaxBufferingDuration(maxBufferingDuration))
.setCoder(KvCoder.of(StringUtf8Coder.of(), IterableCoder.of(StringUtf8Coder.of())));
// Elements have the same key and collection is divided into windows,
// so Count.perKey values are the number of elements in windows
PCollection<KV<String, Long>> countOutput =
outputCollection.apply(
"Count elements in windows after applying GroupIntoBatches", Count.perKey());
PAssert.that("Wrong number of elements in windows after GroupIntoBatches", countOutput)
.satisfies(
input -> {
Iterator<KV<String, Long>> inputIterator = input.iterator();
long count = inputIterator.next().getValue();
assertEquals("Wrong number of elements in global window", 2, count);
return null;
});
PAssert.that("Incorrect output collection after GroupIntoBatches", outputCollection)
.satisfies(
input -> {
Iterator<KV<String, Iterable<String>>> inputIterator = input.iterator();
int size1 = Iterables.size(inputIterator.next().getValue());
assertEquals("Wrong first element batch Size", EVEN_NUM_ELEMENTS / 2, size1);
int size2 = Iterables.size(inputIterator.next().getValue());
assertEquals("Wrong second element batch Size", EVEN_NUM_ELEMENTS / 2, size2);
return null;
});
pipeline.run().waitUntilFinish();
}
}
| lukecwik/incubator-beam | sdks/java/core/src/test/java/org/apache/beam/sdk/transforms/GroupIntoBatchesTest.java | Java | apache-2.0 | 30,031 |
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "uv.h"
#include "internal.h"
#include <stddef.h> /* NULL */
#include <stdio.h> /* printf */
#include <stdlib.h>
#include <string.h> /* strerror */
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <limits.h> /* INT_MAX, PATH_MAX */
#include <sys/uio.h> /* writev */
#ifdef __linux__
# include <sys/ioctl.h>
#endif
#ifdef __sun
# include <sys/types.h>
# include <sys/wait.h>
#endif
#ifdef __APPLE__
# include <mach-o/dyld.h> /* _NSGetExecutablePath */
# include <sys/filio.h>
# include <sys/ioctl.h>
#endif
#ifdef __FreeBSD__
# include <sys/sysctl.h>
# include <sys/filio.h>
# include <sys/ioctl.h>
# include <sys/wait.h>
#endif
static void uv__run_pending(uv_loop_t* loop);
static uv_loop_t default_loop_struct;
static uv_loop_t* default_loop_ptr;
uint64_t uv_hrtime(void) {
return uv__hrtime();
}
void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));
handle->flags |= UV_CLOSING;
handle->close_cb = close_cb;
switch (handle->type) {
case UV_NAMED_PIPE:
uv__pipe_close((uv_pipe_t*)handle);
break;
case UV_TTY:
uv__stream_close((uv_stream_t*)handle);
break;
case UV_TCP:
uv__tcp_close((uv_tcp_t*)handle);
break;
case UV_UDP:
uv__udp_close((uv_udp_t*)handle);
break;
case UV_PREPARE:
uv__prepare_close((uv_prepare_t*)handle);
break;
case UV_CHECK:
uv__check_close((uv_check_t*)handle);
break;
case UV_IDLE:
uv__idle_close((uv_idle_t*)handle);
break;
case UV_ASYNC:
uv__async_close((uv_async_t*)handle);
break;
case UV_TIMER:
uv__timer_close((uv_timer_t*)handle);
break;
case UV_PROCESS:
uv__process_close((uv_process_t*)handle);
break;
case UV_FS_EVENT:
uv__fs_event_close((uv_fs_event_t*)handle);
break;
case UV_POLL:
uv__poll_close((uv_poll_t*)handle);
break;
case UV_FS_POLL:
uv__fs_poll_close((uv_fs_poll_t*)handle);
break;
case UV_SIGNAL:
uv__signal_close((uv_signal_t*) handle);
/* Signal handles may not be closed immediately. The signal code will */
/* itself close uv__make_close_pending whenever appropriate. */
return;
default:
assert(0);
}
uv__make_close_pending(handle);
}
void uv__make_close_pending(uv_handle_t* handle) {
assert(handle->flags & UV_CLOSING);
assert(!(handle->flags & UV_CLOSED));
handle->next_closing = handle->loop->closing_handles;
handle->loop->closing_handles = handle;
}
static void uv__finish_close(uv_handle_t* handle) {
assert(!uv__is_active(handle));
assert(handle->flags & UV_CLOSING);
assert(!(handle->flags & UV_CLOSED));
handle->flags |= UV_CLOSED;
switch (handle->type) {
case UV_PREPARE:
case UV_CHECK:
case UV_IDLE:
case UV_ASYNC:
case UV_TIMER:
case UV_PROCESS:
case UV_FS_EVENT:
case UV_FS_POLL:
case UV_POLL:
case UV_SIGNAL:
break;
case UV_NAMED_PIPE:
case UV_TCP:
case UV_TTY:
uv__stream_destroy((uv_stream_t*)handle);
break;
case UV_UDP:
uv__udp_finish_close((uv_udp_t*)handle);
break;
default:
assert(0);
break;
}
uv__handle_unref(handle);
ngx_queue_remove(&handle->handle_queue);
if (handle->close_cb) {
handle->close_cb(handle);
}
}
static void uv__run_closing_handles(uv_loop_t* loop) {
uv_handle_t* p;
uv_handle_t* q;
p = loop->closing_handles;
loop->closing_handles = NULL;
while (p) {
q = p->next_closing;
uv__finish_close(p);
p = q;
}
}
int uv_is_closing(const uv_handle_t* handle) {
return handle->flags & (UV_CLOSING | UV_CLOSED);
}
uv_loop_t* uv_default_loop(void) {
if (default_loop_ptr)
return default_loop_ptr;
if (uv__loop_init(&default_loop_struct, /* default_loop? */ 1))
return NULL;
return (default_loop_ptr = &default_loop_struct);
}
uv_loop_t* uv_loop_new(void) {
uv_loop_t* loop;
if ((loop = malloc(sizeof(*loop))) == NULL)
return NULL;
if (uv__loop_init(loop, /* default_loop? */ 0)) {
free(loop);
return NULL;
}
return loop;
}
void uv_loop_delete(uv_loop_t* loop) {
uv__loop_delete(loop);
#ifndef NDEBUG
memset(loop, -1, sizeof *loop);
#endif
if (loop == default_loop_ptr)
default_loop_ptr = NULL;
else
free(loop);
}
int uv_backend_fd(const uv_loop_t* loop) {
return loop->backend_fd;
}
int uv_backend_timeout(const uv_loop_t* loop) {
if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
return 0;
if (!ngx_queue_empty(&loop->idle_handles))
return 0;
if (loop->closing_handles)
return 0;
return uv__next_timeout(loop);
}
static int uv__loop_alive(uv_loop_t* loop) {
return uv__has_active_handles(loop) ||
uv__has_active_reqs(loop) ||
loop->closing_handles != NULL;
}
int uv_run(uv_loop_t* loop, uv_run_mode mode) {
int r;
if (!uv__loop_alive(loop))
return 0;
do {
uv__update_time(loop);
uv__run_timers(loop);
uv__run_idle(loop);
uv__run_prepare(loop);
uv__run_pending(loop);
uv__io_poll(loop, (mode & UV_RUN_NOWAIT ? 0 : uv_backend_timeout(loop)));
uv__run_check(loop);
uv__run_closing_handles(loop);
r = uv__loop_alive(loop);
} while (r && !(mode & (UV_RUN_ONCE | UV_RUN_NOWAIT)));
return r;
}
void uv_update_time(uv_loop_t* loop) {
uv__update_time(loop);
}
int64_t uv_now(uv_loop_t* loop) {
return loop->time;
}
int uv_is_active(const uv_handle_t* handle) {
return uv__is_active(handle);
}
/* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
int uv__socket(int domain, int type, int protocol) {
int sockfd;
#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
if (sockfd != -1)
goto out;
if (errno != EINVAL)
goto out;
#endif
sockfd = socket(domain, type, protocol);
if (sockfd == -1)
goto out;
if (uv__nonblock(sockfd, 1) || uv__cloexec(sockfd, 1)) {
close(sockfd);
sockfd = -1;
}
#if defined(SO_NOSIGPIPE)
{
int on = 1;
setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
}
#endif
out:
return sockfd;
}
int uv__accept(int sockfd) {
int peerfd;
assert(sockfd >= 0);
while (1) {
#if defined(__linux__)
static int no_accept4;
if (no_accept4)
goto skip;
peerfd = uv__accept4(sockfd,
NULL,
NULL,
UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
if (peerfd != -1)
break;
if (errno == EINTR)
continue;
if (errno != ENOSYS)
break;
no_accept4 = 1;
skip:
#endif
peerfd = accept(sockfd, NULL, NULL);
if (peerfd == -1) {
if (errno == EINTR)
continue;
else
break;
}
if (uv__cloexec(peerfd, 1) || uv__nonblock(peerfd, 1)) {
close(peerfd);
peerfd = -1;
}
break;
}
return peerfd;
}
#if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
int uv__nonblock(int fd, int set) {
int r;
do
r = ioctl(fd, FIONBIO, &set);
while (r == -1 && errno == EINTR);
return r;
}
int uv__cloexec(int fd, int set) {
int r;
do
r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
while (r == -1 && errno == EINTR);
return r;
}
#else /* !(defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) */
int uv__nonblock(int fd, int set) {
int flags;
int r;
do
r = fcntl(fd, F_GETFL);
while (r == -1 && errno == EINTR);
if (r == -1)
return -1;
/* Bail out now if already set/clear. */
if (!!(r & O_NONBLOCK) == !!set)
return 0;
if (set)
flags = r | O_NONBLOCK;
else
flags = r & ~O_NONBLOCK;
do
r = fcntl(fd, F_SETFL, flags);
while (r == -1 && errno == EINTR);
return r;
}
int uv__cloexec(int fd, int set) {
int flags;
int r;
do
r = fcntl(fd, F_GETFD);
while (r == -1 && errno == EINTR);
if (r == -1)
return -1;
/* Bail out now if already set/clear. */
if (!!(r & FD_CLOEXEC) == !!set)
return 0;
if (set)
flags = r | FD_CLOEXEC;
else
flags = r & ~FD_CLOEXEC;
do
r = fcntl(fd, F_SETFD, flags);
while (r == -1 && errno == EINTR);
return r;
}
#endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) */
/* This function is not execve-safe, there is a race window
* between the call to dup() and fcntl(FD_CLOEXEC).
*/
int uv__dup(int fd) {
fd = dup(fd);
if (fd == -1)
return -1;
if (uv__cloexec(fd, 1)) {
SAVE_ERRNO(close(fd));
return -1;
}
return fd;
}
uv_err_t uv_cwd(char* buffer, size_t size) {
if (!buffer || !size) {
return uv__new_artificial_error(UV_EINVAL);
}
if (getcwd(buffer, size)) {
return uv_ok_;
} else {
return uv__new_sys_error(errno);
}
}
uv_err_t uv_chdir(const char* dir) {
if (chdir(dir) == 0) {
return uv_ok_;
} else {
return uv__new_sys_error(errno);
}
}
void uv_disable_stdio_inheritance(void) {
int fd;
/* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
* first 16 file descriptors. After that, bail out after the first error.
*/
for (fd = 0; ; fd++)
if (uv__cloexec(fd, 1) && fd > 15)
break;
}
static void uv__run_pending(uv_loop_t* loop) {
ngx_queue_t* q;
uv__io_t* w;
while (!ngx_queue_empty(&loop->pending_queue)) {
q = ngx_queue_head(&loop->pending_queue);
ngx_queue_remove(q);
ngx_queue_init(q);
w = ngx_queue_data(q, uv__io_t, pending_queue);
w->cb(loop, w, UV__POLLOUT);
}
}
static unsigned int next_power_of_two(unsigned int val) {
val -= 1;
val |= val >> 1;
val |= val >> 2;
val |= val >> 4;
val |= val >> 8;
val |= val >> 16;
val += 1;
return val;
}
static void maybe_resize(uv_loop_t* loop, unsigned int len) {
uv__io_t** watchers;
unsigned int nwatchers;
unsigned int i;
if (len <= loop->nwatchers)
return;
nwatchers = next_power_of_two(len);
watchers = realloc(loop->watchers, nwatchers * sizeof(loop->watchers[0]));
if (watchers == NULL)
abort();
for (i = loop->nwatchers; i < nwatchers; i++)
watchers[i] = NULL;
loop->watchers = watchers;
loop->nwatchers = nwatchers;
}
void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
assert(cb != NULL);
assert(fd >= -1);
ngx_queue_init(&w->pending_queue);
ngx_queue_init(&w->watcher_queue);
w->cb = cb;
w->fd = fd;
w->events = 0;
w->pevents = 0;
}
/* Note that uv__io_start() and uv__io_stop() can't simply remove the watcher
* from the queue when the new event mask equals the old one. The event ports
* backend operates exclusively in single-shot mode and needs to rearm all fds
* before each call to port_getn(). It's up to the individual backends to
* filter out superfluous event mask modifications.
*/
void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
assert(0 != events);
assert(w->fd >= 0);
assert(w->fd < INT_MAX);
w->pevents |= events;
maybe_resize(loop, w->fd + 1);
if (ngx_queue_empty(&w->watcher_queue))
ngx_queue_insert_tail(&loop->watcher_queue, &w->watcher_queue);
if (loop->watchers[w->fd] == NULL) {
loop->watchers[w->fd] = w;
loop->nfds++;
}
}
void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
assert(0 != events);
if (w->fd == -1)
return;
assert(w->fd >= 0);
/* Happens when uv__io_stop() is called on a handle that was never started. */
if ((unsigned) w->fd >= loop->nwatchers)
return;
w->pevents &= ~events;
if (w->pevents == 0) {
ngx_queue_remove(&w->watcher_queue);
ngx_queue_init(&w->watcher_queue);
if (loop->watchers[w->fd] != NULL) {
assert(loop->watchers[w->fd] == w);
assert(loop->nfds > 0);
loop->watchers[w->fd] = NULL;
loop->nfds--;
w->events = 0;
}
}
else if (ngx_queue_empty(&w->watcher_queue))
ngx_queue_insert_tail(&loop->watcher_queue, &w->watcher_queue);
}
void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
uv__io_stop(loop, w, UV__POLLIN | UV__POLLOUT);
ngx_queue_remove(&w->pending_queue);
}
void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
if (ngx_queue_empty(&w->pending_queue))
ngx_queue_insert_tail(&loop->pending_queue, &w->pending_queue);
}
int uv__io_active(const uv__io_t* w, unsigned int events) {
assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
assert(0 != events);
return 0 != (w->pevents & events);
}
| jeltz/rust-debian-package | src/libuv/src/unix/core.c | C | apache-2.0 | 13,898 |
package ioutil
import (
"bufio"
"encoding/json"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func ReadFile(path string) (string, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(content), nil
}
func ReadFileAs(path string, obj interface{}) error {
d, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = json.Unmarshal(d, obj)
if err != nil {
return err
}
return nil
}
/*
ReadINIConfig loads a ini config file without any sections. Example:
--- --- ---
a=b
c=d
--- --- ---
*/
func ReadINIConfig(path string) (map[string]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
mp := make(map[string]string)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
result := strings.Split(scanner.Text(), "=")
if len(result) != 2 {
continue
}
mp[string(result[0])] = result[1]
}
if err := scanner.Err(); err != nil {
return nil, err
}
return mp, nil
}
func WriteJson(path string, obj interface{}) error {
d, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return err
}
EnsureDirectory(path)
err = ioutil.WriteFile(path, d, os.ModePerm)
if err != nil {
return err
}
return nil
}
func WriteString(path string, data string) bool {
EnsureDirectory(path)
err := ioutil.WriteFile(path, []byte(data), os.ModePerm)
if err != nil {
return false
}
return true
}
func AppendToFile(path string, values string) error {
EnsureDirectory(path)
if _, err := os.Stat(path); err != nil {
ioutil.WriteFile(path, []byte(""), os.ModePerm)
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer f.Close()
f.WriteString("\n")
_, err = f.WriteString(values)
if err != nil {
return err
}
return nil
}
func EnsureDirectory(path string) error {
parent := filepath.Dir(path)
if _, err := os.Stat(parent); err != nil {
return os.MkdirAll(parent, os.ModePerm)
}
return nil
}
func IsFileExists(path string) bool {
EnsureDirectory(path)
if _, err := os.Stat(path); err != nil {
return false
}
return true
}
// WriteFile writes the contents from src to dst using io.Copy.
// If dst does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing.
func WriteFile(dst string, src io.Reader, perm os.FileMode) (err error) {
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return
}
defer func() {
if e := out.Close(); e != nil {
err = e
}
}()
_, err = io.Copy(out, src)
return
}
| k8sdb/apimachinery | vendor/gomodules.xyz/x/ioutil/helpers.go | GO | apache-2.0 | 2,603 |
/*
* Copyright 2002-2014 the original author or authors.
*
* 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 org.springframework.orm.hibernate3;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* This interceptor binds a new Hibernate Session to the thread before a method
* call, closing and removing it afterwards in case of any method outcome.
* If there already is a pre-bound Session (e.g. from HibernateTransactionManager,
* or from a surrounding Hibernate-intercepted method), the interceptor simply
* participates in it.
*
* <p>Application code must retrieve a Hibernate Session via the
* {@code SessionFactoryUtils.getSession} method or - preferably -
* Hibernate's own {@code SessionFactory.getCurrentSession()} method, to be
* able to detect a thread-bound Session. Typically, the code will look like as follows:
*
* <pre class="code">
* public void doSomeDataAccessAction() {
* Session session = this.sessionFactory.getCurrentSession();
* ...
* // No need to close the Session or translate exceptions!
* }</pre>
*
* Note that this interceptor automatically translates HibernateExceptions,
* via delegating to the {@code SessionFactoryUtils.convertHibernateAccessException}
* method that converts them to exceptions that are compatible with the
* {@code org.springframework.dao} exception hierarchy (like HibernateTemplate does).
* This can be turned off if the raw exceptions are preferred.
*
* <p>This class can be considered a declarative alternative to HibernateTemplate's
* callback approach. The advantages are:
* <ul>
* <li>no anonymous classes necessary for callback implementations;
* <li>the possibility to throw any application exceptions from within data access code.
* </ul>
*
* <p>The drawback is the dependency on interceptor configuration. However, note
* that this interceptor is usually <i>not</i> necessary in scenarios where the
* data access code always executes within transactions. A transaction will always
* have a thread-bound Session in the first place, so adding this interceptor to the
* configuration just adds value when fine-tuning Session settings like the flush mode
* - or when relying on exception translation.
*
* @author Juergen Hoeller
* @since 1.2
* @see org.hibernate.SessionFactory#getCurrentSession()
* @see HibernateTransactionManager
* @see HibernateTemplate
* @deprecated as of Spring 3.2.7, in favor of either HibernateTemplate usage or
* native Hibernate API usage within transactions, in combination with a general
* {@link org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor}.
* Note: This class does not have an equivalent replacement in {@code orm.hibernate4}.
* If you desperately need a scoped Session bound through AOP, consider the newly
* introduced {@link org.springframework.orm.hibernate3.support.OpenSessionInterceptor}.
*/
@Deprecated
public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor {
private boolean exceptionConversionEnabled = true;
/**
* Set whether to convert any HibernateException raised to a Spring DataAccessException,
* compatible with the {@code org.springframework.dao} exception hierarchy.
* <p>Default is "true". Turn this flag off to let the caller receive raw exceptions
* as-is, without any wrapping.
* @see org.springframework.dao.DataAccessException
*/
public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
this.exceptionConversionEnabled = exceptionConversionEnabled;
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Session session = getSession();
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateInterceptor");
}
else {
if (sessionHolder != null) {
sessionHolder.addSession(session);
}
else {
TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
}
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
Object retVal = methodInvocation.proceed();
flushIfNecessary(session, existingTransaction);
return retVal;
}
catch (HibernateException ex) {
if (this.exceptionConversionEnabled) {
throw convertHibernateAccessException(ex);
}
else {
throw ex;
}
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
}
}
}
/**
* Return a Session for use by this interceptor.
* @see SessionFactoryUtils#getSession
*/
protected Session getSession() {
return SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
}
}
| leogoing/spring_jeesite | spring-orm-4.0/org/springframework/orm/hibernate3/HibernateInterceptor.java | Java | apache-2.0 | 6,170 |
package mil.nga.giat.geowave.core.index.lexicoder;
import com.google.common.primitives.SignedBytes;
public class DoubleLexicoderTest extends
AbstractLexicoderTest<Double>
{
public DoubleLexicoderTest() {
super(
Lexicoders.DOUBLE,
Double.MIN_VALUE,
Double.MAX_VALUE,
new Double[] {
-10d,
Double.MIN_VALUE,
11d,
-14.2,
14.2,
-100.002,
100.002,
-11d,
Double.MAX_VALUE,
0d
},
SignedBytes.lexicographicalComparator());
}
}
| chizou/geowave | core/index/src/test/java/mil/nga/giat/geowave/core/index/lexicoder/DoubleLexicoderTest.java | Java | apache-2.0 | 500 |
# Packet Flow between Pods on the same node
## Request
Request sent from a "client" pod with the source address `clientIP:clientPort`
destined to `serverIP:serverPort` of another "server" pod on the same node:
1. Inside the client pod, destination `serverIP` matches the default route
configured for the pod by `remoteCNIserver.podDefaultRouteFromRequest()`.
* default gateway IP address is the same for all pods on the same node -
returned by `IPAM.PodGatewayIP()` as the first unicast IP address from
the *subset* of `PodSubnetCIDR` allocated for the node. **Pod default GW
IP is kept virtual** and never assigned to any pod or interface inside VPP.
Do not confuse pod's TAP interface IP address on the VPP side with the
default gateway. The IP address assigned on the VPP-side of the pod-VPP
interconnection actually plays no role in the packet traversal, it serves
merely as a marker for VPP to put the TAP interface into the L3 mode.
2. Link-local route installed by `remoteCNIserver.podLinkRouteFromRequest()`
informs the host stack that `PodGatewayIP` is on the same L2 network as the
pod's `eth0` interface, even though the pod IP address is prefixed with `/32`.
3. Static ARP entry configured by `remoteCNIserver.podArpEntry()` maps
`PodGatewayIP` to the MAC address of the VPP side of the pod's TAP interface,
i.e. every pod translates `PodGatewayIP` to a different hardware address.
4. Packet arrives to VPP either through the `virtio-input`, if TAP version 2 is
used, or through `tapcli-rx` for TAPv1.
5. If the client pod is referenced by ingress or egress policies, the (ingress)
`Reflective ACL` will be traversed (node `acl-plugin-in-ip4-fa`), **allowing
and reflecting the connection** (study [Policy dev guide][policy-dev-guide]
to learn why).
6. `nat44-out2in` node checks if the destination address should be translated
as an external IP into a local IP using any of the static mappings installed
by the [service plugin][services-dev-guide] - in this case the destination
is a real pod IP address, thus **no translation occurs** (`session index -1`
in the packet trace).
7. Destination IP address matches static route installed for the server pod
by `remoteCNIserver.vppRouteFromRequest()`. The server pod's TAP interface
is selected for the output.
8. If the server pod is referenced by ingress or egress policies, the **combined
ingress & egress policy rules installed as a single egress ACL** will be
checked by the node `acl-plugin-out-ip4-fa`.
The following two conditions must be true for the connection to be allowed:
* the client pod allows connections destined to `serverIP:serverPort`
* the server pod allows connections from `clientIP` to port `serverPort`
9. Static ARP entry configured by `remoteCNIserver.vppArpEntry()` maps `serverIP`
to the hardware address of the server pod's `eth0` interface. It is required
by the STN plugin that all pods use the same MAC address `00:00:00:00:00:02`.
10. Request arrives to the server pod's host stack.
Example SYN packet sent from client `10.1.1.12:39820` to server `10.1.1.9:8080`:
```
SYN:
----
01:48:51:256986: virtio-input
virtio: hw_if_index 7 next-index 4 vring 0 len 74
hdr: flags 0x00 gso_type 0x00 hdr_len 0 gso_size 0 csum_start 0 csum_offset 0 num_buffers 1
01:48:51:256990: ethernet-input
IP4: 00:00:00:00:00:02 -> 02:fe:69:99:eb:9d
01:48:51:256993: ip4-input
TCP: 10.1.1.12 -> 10.1.1.9
tos 0x00, ttl 64, length 60, checksum 0xf087
fragment id 0x341e, flags DONT_FRAGMENT
TCP: 39820 -> 8080
seq. 0x8c66e434 ack 0x00000000
flags 0x02 SYN, tcp header: 40 bytes
window 29200, checksum 0xc3de
01:48:51:256995: acl-plugin-in-ip4-fa
acl-plugin: sw_if_index 7, next index 1, action: 2, match: acl 1 rule 0 trace_bits 00000000
pkt info 0000000000000000 0c01010a00000000 0000000000000000 0901010a00000000 000700061f909b8c 0702ffff00000007
input sw_if_index 7 (lsb16 7) l3 ip4 10.1.1.12 -> 10.1.1.9 l4 proto 6 l4_valid 1 port 39820 -> 8080 tcp flags (valid) 02 rsvd 0
01:48:51:257002: nat44-out2in
NAT44_OUT2IN: sw_if_index 7, next index 1, session index -1
01:48:51:257008: ip4-lookup
fib 0 dpo-idx 12 flow hash: 0x00000000
TCP: 10.1.1.12 -> 10.1.1.9
tos 0x00, ttl 64, length 60, checksum 0xf087
fragment id 0x341e, flags DONT_FRAGMENT
TCP: 39820 -> 8080
seq. 0x8c66e434 ack 0x00000000
flags 0x02 SYN, tcp header: 40 bytes
window 29200, checksum 0xc3de
01:48:51:257011: ip4-rewrite
tx_sw_if_index 11 dpo-idx 12 : ipv4 via 10.1.1.9 tap8: 00000000000202fe167939cb0800 flow hash: 0x00000000
00000000: 00000000000202fe167939cb08004500003c341e40003f06f1870a01010c0a01
00000020: 01099b8c1f908c66e43400000000a0027210c3de0000020405b40402
01:48:51:257013: acl-plugin-out-ip4-fa
acl-plugin: sw_if_index 11, next index 1, action: 1, match: acl 0 rule 0 trace_bits 00000000
pkt info 0000000000000000 0c01010a00000000 0000000000000000 0901010a00000000 000b00061f909b8c 0502ffff0000000b
output sw_if_index 11 (lsb16 11) l3 ip4 10.1.1.12 -> 10.1.1.9 l4 proto 6 l4_valid 1 port 39820 -> 8080 tcp flags (valid) 02 rsvd 0
01:48:51:257016: tap8-output
tap8
IP4: 02:fe:16:79:39:cb -> 00:00:00:00:00:02
TCP: 10.1.1.12 -> 10.1.1.9
tos 0x00, ttl 63, length 60, checksum 0xf187
fragment id 0x341e, flags DONT_FRAGMENT
TCP: 39820 -> 8080
seq. 0x8c66e434 ack 0x00000000
flags 0x02 SYN, tcp header: 40 bytes
window 29200, checksum 0xc3de
```
## Response
Response sent from the pod with the server application `serverIP:serverPort`
back to the client `clientIP:clientPort` on the same node:
1. Default route + Link-local route + static ARP entry are used to sent
the response to VPP via pod's `eth0` TAP interface (see the request flow,
steps 1.-4., to learn the details)
2. If the server pod is referenced by ingress or egress policies, the (ingress)
`Reflective ACL` will be traversed (node `acl-plugin-in-ip4-fa`), **allowing
and reflecting the connection**. The reflection has no effect in this case,
since the connection was already allowed in the direction of the request.
3. `nat44-in2out` node checks if the source address should be translated as
a local IP into an external IP using any of the static mappings installed
by the [service plugin][services-dev-guide] - in this case the server is being
accessed directly, not via service VIP, thus **no translation occurs**
(`session -1` in the packet trace).
4. Destination IP address matches static route installed for the client pod
by `remoteCNIserver.vppRouteFromRequest()`. The client pod's TAP interface
is selected for the output.
5. If the client pod is referenced by ingress or egress policies, the combined
ingress & egress policy rules installed as a single egress ACL will be
checked by the node `acl-plugin-out-ip4-fa`.
The desired behaviour is, however, to always allow connection if it has got
this far - the **policies should be only checked in the direction of the
request**. The `Reflective ACL` has already created a free pass for all
responses in the connection, thus the client's egress ACL is ignored.
6. Static ARP entry configured by `remoteCNIserver.vppArpEntry()` maps `clientIP`
to the hardware address of the client pod's `eth0` interface. It is required
by the STN plugin that all pods use the same MAC address `00:00:00:00:00:02`.
7. Request arrives to the client pod's host stack.
Example SYN-ACK packet sent from server `10.1.1.9:8080` back to client
`10.1.1.12:39820`:
```
SYN-ACK:
--------
01:48:51:257049: virtio-input
virtio: hw_if_index 11 next-index 4 vring 0 len 74
hdr: flags 0x00 gso_type 0x00 hdr_len 0 gso_size 0 csum_start 0 csum_offset 0 num_buffers 1
01:48:51:257049: ethernet-input
IP4: 00:00:00:00:00:02 -> 02:fe:16:79:39:cb
01:48:51:257051: ip4-input
TCP: 10.1.1.9 -> 10.1.1.12
tos 0x00, ttl 64, length 60, checksum 0x24a6
fragment id 0x0000, flags DONT_FRAGMENT
TCP: 8080 -> 39820
seq. 0x0db7e410 ack 0x8c66e435
flags 0x12 SYN ACK, tcp header: 40 bytes
window 28960, checksum 0x02b3
01:48:51:257051: acl-plugin-in-ip4-fa
acl-plugin: sw_if_index 11, next index 2, action: 2, match: acl 1 rule 0 trace_bits 00000000
pkt info 0000000000000000 0901010a00000000 0000000000000000 0c01010a00000000 000b00069b8c1f90 0712ffff0000000b
input sw_if_index 11 (lsb16 11) l3 ip4 10.1.1.9 -> 10.1.1.12 l4 proto 6 l4_valid 1 port 8080 -> 39820 tcp flags (valid) 12 rsvd 0
01:48:51:257056: nat44-in2out
NAT44_IN2OUT_FAST_PATH: sw_if_index 11, next index 3, session -1
01:48:51:257057: nat44-in2out-slowpath
NAT44_IN2OUT_SLOW_PATH: sw_if_index 11, next index 0, session -1
01:48:51:257059: ip4-lookup
fib 0 dpo-idx 9 flow hash: 0x00000000
TCP: 10.1.1.9 -> 10.1.1.12
tos 0x00, ttl 64, length 60, checksum 0x24a6
fragment id 0x0000, flags DONT_FRAGMENT
TCP: 8080 -> 39820
seq. 0x0db7e410 ack 0x8c66e435
flags 0x12 SYN ACK, tcp header: 40 bytes
window 28960, checksum 0x02b3
01:48:51:257060: ip4-rewrite
tx_sw_if_index 7 dpo-idx 9 : ipv4 via 10.1.1.12 tap11: 00000000000202fe6999eb9d0800 flow hash: 0x00000000
00000000: 00000000000202fe6999eb9d08004500003c000040003f0625a60a0101090a01
00000020: 010c1f909b8c0db7e4108c66e435a012712002b30000020405b40402
01:48:51:257060: acl-plugin-out-ip4-fa
acl-plugin: sw_if_index 7, next index 1, action: 3, match: acl -1 rule 170 trace_bits 80000000
pkt info 0000000000000000 0901010a00000000 0000000000000000 0c01010a00000000 000700069b8c1f90 0512ffff00000007
output sw_if_index 7 (lsb16 7) l3 ip4 10.1.1.9 -> 10.1.1.12 l4 proto 6 l4_valid 1 port 8080 -> 39820 tcp flags (valid) 12 rsvd 0
01:48:51:257061: tap11-output
tap11
IP4: 02:fe:69:99:eb:9d -> 00:00:00:00:00:02
TCP: 10.1.1.9 -> 10.1.1.12
tos 0x00, ttl 63, length 60, checksum 0x25a6
fragment id 0x0000, flags DONT_FRAGMENT
TCP: 8080 -> 39820
seq. 0x0db7e410 ack 0x8c66e435
flags 0x12 SYN ACK, tcp header: 40 bytes
window 28960, checksum 0x02b3
```
## Diagram
![Pod connecting to pod on the same node][pod-to-pod-on-the-same-node-diagram]
[pod-to-pod-on-the-same-node-diagram]: pod-to-pod-same-node.png
[policies-dev-guide]: ../POLICIES.md
[services-dev-guide]: ../SERVICES.md | rastislavszabo/vpp | docs/dev-guide/packet-flow/POD_TO_POD_SAME_NODE.md | Markdown | apache-2.0 | 10,310 |
/*
* Copyright (c) 2014-2015 University of Ulm
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 dtos;
import dtos.generic.ValidatableDto;
/**
* Created by daniel on 14.04.15.
*/
public class FrontendUserToDto extends ValidatableDto {
@Override public void validation() {
//todo implement
}
}
| cha87de/colosseum | app/dtos/FrontendUserToDto.java | Java | apache-2.0 | 945 |
/***************************************************************
*
* Copyright (C) 1990-2010, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
#ifndef _STARTD_CRON_JOB_PARAMS_H
#define _STARTD_CRON_JOB_PARAMS_H
#include "classad_cron_job.h"
#include <list>
using namespace std;
// Define a "ClassAd" cron job parameter object
class StartdCronJobParams : public ClassAdCronJobParams
{
public:
StartdCronJobParams( const char *job_name,
const CronJobMgr &mgr );
~StartdCronJobParams( void ) { };
// Finish initialization
bool Initialize( void );
bool InSlotList( unsigned slot ) const;
private:
list<unsigned> m_slots;
};
#endif /* _STARTD_CRON_JOB_PARAMS_H */
| clalancette/condor-dcloud | src/condor_startd.V6/startd_cron_job_params.h | C | apache-2.0 | 1,350 |
/* $begin signal4 */
#include "csapp.h"
void handler2(int sig) {
pid_t pid;
while ((pid = waitpid(-1, NULL, 0)) > 0)
printf("Handler reaped child %d\n", (int) pid);
if (errno != ECHILD)
unix_error("waitpid error");
Sleep(2);
return;
}
int main() {
int i, n;
char buf[MAXBUF];
pid_t pid;
Signal(SIGCHLD, handler2); /* sigaction error-handling wrapper */
/* Parent creates children */
for (i = 0; i < 3; i++) {
pid = Fork();
if (pid == 0) {
printf("Hello from child %d\n", (int) getpid());
Sleep(1);
exit(0);
}
}
/* Parent waits for terminal input and then processes it */
if ((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0)
unix_error("read error");
printf("Parent processing input\n");
while (1);
exit(0);
}
/* $end signal4 */
| zhangrxiang/learn-c | books/csapp/ch08/signal4.c | C | apache-2.0 | 886 |
+++
Title = "Jeff McKenzie"
Twitter = "jeffreymckenzie"
image = "jeff-mckenzie.png"
type = "speaker"
website = "https://github.com/mcknz"
+++
Jeff McKenzie has worked in software development for nearly twenty years, in both freelance and full-time capacities, as a developer and team leader. He enjoys helping others solve problems through technology, whether it’s the small business getting on the web for the first time, or a Fortune 500 company expanding its enterprise. Although he started his career using BASIC on an Atari 800, he took a big detour, getting Biology and English degrees before rediscovering programming, with a new thing called the World Wide Web. He is currently a Practice Manager for Applications and Infrastructure at Insight Digital Innovation (formerly Cardinal Solutions) in Columbus Ohio.
| gomex/devopsdays-web | content/events/2019-columbus/speakers/jeff-mckenzie.md | Markdown | apache-2.0 | 822 |
element = S(input).attr(attributeName).remove();
| camunda/camunda-spin | dataformat-xml-dom/src/test/resources/org/camunda/spin/javascript/xml/dom/XmlDomAttributeScriptTest.removeAttribute.js | JavaScript | apache-2.0 | 49 |
using NServiceBus;
#region ObjectResponseMessageHandler
public class ObjectResponseMessageHandler : IHandleMessages<ObjectResponseMessage>
{
public void Handle(ObjectResponseMessage message)
{
}
}
#endregion | pedroreys/docs.particular.net | samples/callbacks/Version_3/Sender/ObjectResponseMessageHandler.cs | C# | apache-2.0 | 223 |
"""Zookeeper Partitioner Implementation
:Maintainer: None
:Status: Unknown
:class:`SetPartitioner` implements a partitioning scheme using
Zookeeper for dividing up resources amongst members of a party.
This is useful when there is a set of resources that should only be
accessed by a single process at a time that multiple processes
across a cluster might want to divide up.
Example Use-Case
----------------
- Multiple workers across a cluster need to divide up a list of queues
so that no two workers own the same queue.
"""
from functools import partial
import logging
import os
import socket
from kazoo.exceptions import KazooException, LockTimeout
from kazoo.protocol.states import KazooState
from kazoo.recipe.watchers import PatientChildrenWatch
log = logging.getLogger(__name__)
class PartitionState(object):
"""High level partition state values
.. attribute:: ALLOCATING
The set needs to be partitioned, and may require an existing
partition set to be released before acquiring a new partition
of the set.
.. attribute:: ACQUIRED
The set has been partitioned and acquired.
.. attribute:: RELEASE
The set needs to be repartitioned, and the current partitions
must be released before a new allocation can be made.
.. attribute:: FAILURE
The set partition has failed. This occurs when the maximum
time to partition the set is exceeded or the Zookeeper session
is lost. The partitioner is unusable after this state and must
be recreated.
"""
ALLOCATING = "ALLOCATING"
ACQUIRED = "ACQUIRED"
RELEASE = "RELEASE"
FAILURE = "FAILURE"
class SetPartitioner(object):
"""Partitions a set amongst members of a party
This class will partition a set amongst members of a party such
that each member will be given zero or more items of the set and
each set item will be given to a single member. When new members
enter or leave the party, the set will be re-partitioned amongst
the members.
When the :class:`SetPartitioner` enters the
:attr:`~PartitionState.FAILURE` state, it is unrecoverable
and a new :class:`SetPartitioner` should be created.
Example:
.. code-block:: python
from kazoo.client import KazooClient
client = KazooClient()
client.start()
qp = client.SetPartitioner(
path='/work_queues', set=('queue-1', 'queue-2', 'queue-3'))
while 1:
if qp.failed:
raise Exception("Lost or unable to acquire partition")
elif qp.release:
qp.release_set()
elif qp.acquired:
for partition in qp:
# Do something with each partition
elif qp.allocating:
qp.wait_for_acquire()
**State Transitions**
When created, the :class:`SetPartitioner` enters the
:attr:`PartitionState.ALLOCATING` state.
:attr:`~PartitionState.ALLOCATING` ->
:attr:`~PartitionState.ACQUIRED`
Set was partitioned successfully, the partition list assigned
is accessible via list/iter methods or calling list() on the
:class:`SetPartitioner` instance.
:attr:`~PartitionState.ALLOCATING` ->
:attr:`~PartitionState.FAILURE`
Allocating the set failed either due to a Zookeeper session
expiration, or failure to acquire the items of the set within
the timeout period.
:attr:`~PartitionState.ACQUIRED` ->
:attr:`~PartitionState.RELEASE`
The members of the party have changed, and the set needs to be
repartitioned. :meth:`SetPartitioner.release` should be called
as soon as possible.
:attr:`~PartitionState.ACQUIRED` ->
:attr:`~PartitionState.FAILURE`
The current partition was lost due to a Zookeeper session
expiration.
:attr:`~PartitionState.RELEASE` ->
:attr:`~PartitionState.ALLOCATING`
The current partition was released and is being re-allocated.
"""
def __init__(self, client, path, set, partition_func=None,
identifier=None, time_boundary=30, max_reaction_time=1,
state_change_event=None):
"""Create a :class:`~SetPartitioner` instance
:param client: A :class:`~kazoo.client.KazooClient` instance.
:param path: The partition path to use.
:param set: The set of items to partition.
:param partition_func: A function to use to decide how to
partition the set.
:param identifier: An identifier to use for this member of the
party when participating. Defaults to the
hostname + process id.
:param time_boundary: How long the party members must be stable
before allocation can complete.
:param max_reaction_time: Maximum reaction time for party members
change.
:param state_change_event: An optional Event object that will be set
on every state change.
"""
# Used to differentiate two states with the same names in time
self.state_id = 0
self.state = PartitionState.ALLOCATING
self.state_change_event = state_change_event or \
client.handler.event_object()
self._client = client
self._path = path
self._set = set
self._partition_set = []
self._partition_func = partition_func or self._partitioner
self._identifier = identifier or '%s-%s' % (
socket.getfqdn(), os.getpid())
self._locks = []
self._lock_path = '/'.join([path, 'locks'])
self._party_path = '/'.join([path, 'party'])
self._time_boundary = time_boundary
self._max_reaction_time = max_reaction_time
self._acquire_event = client.handler.event_object()
# Create basic path nodes
client.ensure_path(path)
client.ensure_path(self._lock_path)
client.ensure_path(self._party_path)
# Join the party
self._party = client.ShallowParty(self._party_path,
identifier=self._identifier)
self._party.join()
self._state_change = client.handler.rlock_object()
client.add_listener(self._establish_sessionwatch)
# Now watch the party and set the callback on the async result
# so we know when we're ready
self._child_watching(self._allocate_transition, client_handler=True)
def __iter__(self):
"""Return the partitions in this partition set"""
for partition in self._partition_set:
yield partition
@property
def failed(self):
"""Corresponds to the :attr:`PartitionState.FAILURE` state"""
return self.state == PartitionState.FAILURE
@property
def release(self):
"""Corresponds to the :attr:`PartitionState.RELEASE` state"""
return self.state == PartitionState.RELEASE
@property
def allocating(self):
"""Corresponds to the :attr:`PartitionState.ALLOCATING`
state"""
return self.state == PartitionState.ALLOCATING
@property
def acquired(self):
"""Corresponds to the :attr:`PartitionState.ACQUIRED` state"""
return self.state == PartitionState.ACQUIRED
def wait_for_acquire(self, timeout=30):
"""Wait for the set to be partitioned and acquired
:param timeout: How long to wait before returning.
:type timeout: int
"""
self._acquire_event.wait(timeout)
def release_set(self):
"""Call to release the set
This method begins the step of allocating once the set has
been released.
"""
self._release_locks()
if self._locks: # pragma: nocover
# This shouldn't happen, it means we couldn't release our
# locks, abort
self._fail_out()
return
else:
with self._state_change:
if self.failed:
return
self._set_state(PartitionState.ALLOCATING)
self._child_watching(self._allocate_transition, client_handler=True)
def finish(self):
"""Call to release the set and leave the party"""
self._release_locks()
self._fail_out()
def _fail_out(self):
with self._state_change:
self._set_state(PartitionState.FAILURE)
if self._party.participating:
try:
self._party.leave()
except KazooException: # pragma: nocover
pass
def _allocate_transition(self, result):
"""Called when in allocating mode, and the children settled"""
# Did we get an exception waiting for children to settle?
if result.exception: # pragma: nocover
self._fail_out()
return
children, async_result = result.get()
children_changed = self._client.handler.event_object()
def updated(result):
with self._state_change:
children_changed.set()
if self.acquired:
self._set_state(PartitionState.RELEASE)
with self._state_change:
# We can lose connection during processing the event
if not self.allocating:
return
# Remember the state ID to check later for race conditions
state_id = self.state_id
# updated() will be called when children change
async_result.rawlink(updated)
# Check whether the state has changed during the lock acquisition
# and abort the process if so.
def abort_if_needed():
if self.state_id == state_id:
if children_changed.is_set():
# The party has changed. Repartitioning...
self._abort_lock_acquisition()
return True
else:
return False
else:
if self.allocating or self.acquired:
# The connection was lost and user initiated a new
# allocation process. Abort it to eliminate race
# conditions with locks.
with self._state_change:
self._set_state(PartitionState.RELEASE)
return True
# Split up the set
partition_set = self._partition_func(
self._identifier, list(self._party), self._set)
# Proceed to acquire locks for the working set as needed
for member in partition_set:
lock = self._client.Lock(self._lock_path + '/' + str(member))
while True:
try:
# We mustn't lock without timeout because in that case we
# can get a deadlock if the party state will change during
# lock acquisition.
lock.acquire(timeout=self._max_reaction_time)
except LockTimeout:
if abort_if_needed():
return
except KazooException:
return self.finish()
else:
break
self._locks.append(lock)
if abort_if_needed():
return
# All locks acquired. Time for state transition.
with self._state_change:
if self.state_id == state_id and not children_changed.is_set():
self._partition_set = partition_set
self._set_state(PartitionState.ACQUIRED)
self._acquire_event.set()
return
if not abort_if_needed():
# This mustn't happen. Means a logical error.
self._fail_out()
def _release_locks(self):
"""Attempt to completely remove all the locks"""
self._acquire_event.clear()
for lock in self._locks[:]:
try:
lock.release()
except KazooException: # pragma: nocover
# We proceed to remove as many as possible, and leave
# the ones we couldn't remove
pass
else:
self._locks.remove(lock)
def _abort_lock_acquisition(self):
"""Called during lock acquisition if a party change occurs"""
self._release_locks()
if self._locks:
# This shouldn't happen, it means we couldn't release our
# locks, abort
self._fail_out()
return
self._child_watching(self._allocate_transition, client_handler=True)
def _child_watching(self, func=None, client_handler=False):
"""Called when children are being watched to stabilize
This actually returns immediately, child watcher spins up a
new thread/greenlet and waits for it to stabilize before
any callbacks might run.
:param client_handler: If True, deliver the result using the
client's event handler.
"""
watcher = PatientChildrenWatch(self._client, self._party_path,
self._time_boundary)
asy = watcher.start()
if func is not None:
# We spin up the function in a separate thread/greenlet
# to ensure that the rawlink's it might use won't be
# blocked
if client_handler:
func = partial(self._client.handler.spawn, func)
asy.rawlink(func)
return asy
def _establish_sessionwatch(self, state):
"""Register ourself to listen for session events, we shut down
if we become lost"""
with self._state_change:
if self.failed:
pass
elif state == KazooState.LOST:
self._client.handler.spawn(self._fail_out)
elif not self.release:
self._set_state(PartitionState.RELEASE)
return state == KazooState.LOST
def _partitioner(self, identifier, members, partitions):
# Ensure consistent order of partitions/members
all_partitions = sorted(partitions)
workers = sorted(members)
i = workers.index(identifier)
# Now return the partition list starting at our location and
# skipping the other workers
return all_partitions[i::len(workers)]
def _set_state(self, state):
self.state = state
self.state_id += 1
self.state_change_event.set()
| python-zk/kazoo | kazoo/recipe/partitioner.py | Python | apache-2.0 | 14,668 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Class EvaluatorBuilderImpl
* @author Jeka
*/
package com.intellij.debugger.engine.evaluation.expression;
import com.intellij.codeInsight.daemon.JavaErrorBundle;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.debugger.JavaDebuggerBundle;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.DebuggerUtils;
import com.intellij.debugger.engine.JVMName;
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.lang.java.parser.ExpressionParser;
import com.intellij.lang.jvm.JvmModifier;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.refactoring.extractMethodObject.ExtractLightMethodObjectHandler;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.sun.jdi.Value;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public final class EvaluatorBuilderImpl implements EvaluatorBuilder {
private static final EvaluatorBuilderImpl ourInstance = new EvaluatorBuilderImpl();
private EvaluatorBuilderImpl() {
}
public static EvaluatorBuilder getInstance() {
return ourInstance;
}
@NotNull
public static ExpressionEvaluator build(final TextWithImports text,
@Nullable PsiElement contextElement,
@Nullable final SourcePosition position,
@NotNull Project project) throws EvaluateException {
CodeFragmentFactory factory = DebuggerUtilsEx.findAppropriateCodeFragmentFactory(text, contextElement);
PsiCodeFragment codeFragment = factory.createCodeFragment(text, contextElement, project);
if (codeFragment == null) {
throw EvaluateExceptionUtil.createEvaluateException(JavaDebuggerBundle.message("evaluation.error.invalid.expression", text.getText()));
}
DebuggerUtils.checkSyntax(codeFragment);
return factory.getEvaluatorBuilder().build(codeFragment, position);
}
@Override
public @NotNull ExpressionEvaluator build(final PsiElement codeFragment, final SourcePosition position) throws EvaluateException {
return new Builder(position).buildElement(codeFragment);
}
private static final class Builder extends JavaElementVisitor {
private static final Logger LOG = Logger.getInstance(EvaluatorBuilderImpl.class);
private Evaluator myResult = null;
private PsiClass myContextPsiClass;
private CodeFragmentEvaluator myCurrentFragmentEvaluator;
private final Set<JavaCodeFragment> myVisitedFragments = new HashSet<>();
@Nullable private final SourcePosition myPosition;
@Nullable private final PsiClass myPositionPsiClass;
private Builder(@Nullable SourcePosition position) {
myPosition = position;
myPositionPsiClass = JVMNameUtil.getClassAt(myPosition);
}
@Override
public void visitCodeFragment(JavaCodeFragment codeFragment) {
myVisitedFragments.add(codeFragment);
ArrayList<Evaluator> evaluators = new ArrayList<>();
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
for (PsiElement child = codeFragment.getFirstChild(); child != null; child = child.getNextSibling()) {
child.accept(this);
if (myResult != null) {
evaluators.add(myResult);
}
myResult = null;
}
myCurrentFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[0]));
myResult = myCurrentFragmentEvaluator;
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Override
public void visitErrorElement(@NotNull PsiErrorElement element) {
throwExpressionInvalid(element);
}
@Override
public void visitAssignmentExpression(PsiAssignmentExpression expression) {
final PsiExpression rExpression = expression.getRExpression();
if(rExpression == null) {
throwExpressionInvalid(expression);
}
rExpression.accept(this);
Evaluator rEvaluator = myResult;
final PsiExpression lExpression = expression.getLExpression();
final PsiType lType = lExpression.getType();
if(lType == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", lExpression.getText()));
}
IElementType assignmentType = expression.getOperationTokenType();
PsiType rType = rExpression.getType();
if(!TypeConversionUtil.areTypesAssignmentCompatible(lType, rExpression) && rType != null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.incompatible.types", expression.getOperationSign().getText()));
}
lExpression.accept(this);
Evaluator lEvaluator = myResult;
rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(lType, rType, rEvaluator, expression.getProject());
if (assignmentType != JavaTokenType.EQ) {
IElementType opType = TypeConversionUtil.convertEQtoOperation(assignmentType);
final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true);
if (typeForBinOp == null || rType == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
rEvaluator = createBinaryEvaluator(lEvaluator, lType, rEvaluator, rType, opType, typeForBinOp);
}
myResult = new AssignmentEvaluator(lEvaluator, rEvaluator);
}
// returns rEvaluator possibly wrapped with boxing/unboxing and casting evaluators
private static Evaluator handleAssignmentBoxingAndPrimitiveTypeConversions(PsiType lType,
PsiType rType,
Evaluator rEvaluator,
Project project) {
final PsiType unboxedLType = PsiPrimitiveType.getUnboxedType(lType);
if (unboxedLType != null) {
if (rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) {
if (!rType.equals(unboxedLType)) {
rEvaluator = createTypeCastEvaluator(rEvaluator, unboxedLType);
}
rEvaluator = new BoxingEvaluator(rEvaluator);
}
}
else {
// either primitive type or not unboxable type
if (lType instanceof PsiPrimitiveType) {
if (rType instanceof PsiClassType) {
rEvaluator = new UnBoxingEvaluator(rEvaluator);
}
final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType);
final PsiType _rType = unboxedRType != null? unboxedRType : rType;
if (_rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(_rType)) {
if (!lType.equals(_rType)) {
rEvaluator = createTypeCastEvaluator(rEvaluator, lType);
}
}
}
else if (lType instanceof PsiClassType && rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) {
final PsiClassType rightBoxed =
((PsiPrimitiveType)rType).getBoxedType(PsiManager.getInstance(project), ((PsiClassType)lType).getResolveScope());
if (rightBoxed != null && TypeConversionUtil.isAssignable(lType, rightBoxed)) {
rEvaluator = new BoxingEvaluator(rEvaluator);
}
}
}
return rEvaluator;
}
@Override
public void visitTryStatement(PsiTryStatement statement) {
if (statement.getResourceList() != null) {
throw new EvaluateRuntimeException(new UnsupportedExpressionException("Try with resources is not yet supported"));
}
Evaluator bodyEvaluator = accept(statement.getTryBlock());
if (bodyEvaluator != null) {
PsiCatchSection[] catchSections = statement.getCatchSections();
List<CatchEvaluator> evaluators = new ArrayList<>();
for (PsiCatchSection catchSection : catchSections) {
PsiParameter parameter = catchSection.getParameter();
PsiCodeBlock catchBlock = catchSection.getCatchBlock();
if (parameter != null && catchBlock != null) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
myCurrentFragmentEvaluator.setInitialValue(parameter.getName(), null);
myCurrentFragmentEvaluator.setStatements(visitStatements(catchBlock.getStatements()));
PsiType type = parameter.getType();
List<PsiType> types =
type instanceof PsiDisjunctionType ? ((PsiDisjunctionType)type).getDisjunctions() : Collections.singletonList(type);
for (PsiType psiType : types) {
evaluators.add(new CatchEvaluator(psiType.getCanonicalText(), parameter.getName(), myCurrentFragmentEvaluator));
}
}
finally{
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
}
myResult = new TryEvaluator(bodyEvaluator, evaluators, accept(statement.getFinallyBlock()));
}
}
@Override
public void visitThrowStatement(PsiThrowStatement statement) {
Evaluator accept = accept(statement.getException());
if (accept != null) {
myResult = new ThrowEvaluator(accept);
}
}
@Override
public void visitReturnStatement(PsiReturnStatement statement) {
myResult = new ReturnEvaluator(accept(statement.getReturnValue()));
}
@Override
public void visitYieldStatement(PsiYieldStatement statement) {
myResult = new SwitchEvaluator.YieldEvaluator(accept(statement.getExpression()));
}
@Override
public void visitSynchronizedStatement(PsiSynchronizedStatement statement) {
throw new EvaluateRuntimeException(new UnsupportedExpressionException("Synchronized is not yet supported"));
}
@Override
public void visitStatement(PsiStatement statement) {
LOG.error(JavaDebuggerBundle.message("evaluation.error.statement.not.supported", statement.getText()));
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.statement.not.supported", statement.getText()));
}
private CodeFragmentEvaluator setNewCodeFragmentEvaluator() {
CodeFragmentEvaluator old = myCurrentFragmentEvaluator;
myCurrentFragmentEvaluator = new CodeFragmentEvaluator(myCurrentFragmentEvaluator);
return old;
}
private Evaluator[] visitStatements(PsiStatement[] statements) {
List<Evaluator> evaluators = new ArrayList<>();
for (PsiStatement psiStatement : statements) {
psiStatement.accept(this);
if (myResult != null) { // for example declaration w/o initializer produces empty evaluator now
evaluators.add(DisableGC.create(myResult));
}
myResult = null;
}
return evaluators.toArray(new Evaluator[0]);
}
@Override
public void visitCodeBlock(PsiCodeBlock block) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
myResult = new BlockStatementEvaluator(visitStatements(block.getStatements()));
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Override
public void visitBlockStatement(PsiBlockStatement statement) {
visitCodeBlock(statement.getCodeBlock());
}
@Override
public void visitLabeledStatement(PsiLabeledStatement labeledStatement) {
PsiStatement statement = labeledStatement.getStatement();
if (statement != null) {
statement.accept(this);
}
}
private static String getLabel(PsiElement element) {
String label = null;
if(element.getParent() instanceof PsiLabeledStatement) {
label = ((PsiLabeledStatement)element.getParent()).getName();
}
return label;
}
@Override
public void visitDoWhileStatement(PsiDoWhileStatement statement) {
Evaluator bodyEvaluator = accept(statement.getBody());
Evaluator conditionEvaluator = accept(statement.getCondition());
if (conditionEvaluator != null) {
myResult = new DoWhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement));
}
}
@Override
public void visitWhileStatement(PsiWhileStatement statement) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
Evaluator bodyEvaluator = accept(statement.getBody());
Evaluator conditionEvaluator = accept(statement.getCondition());
if (conditionEvaluator != null) {
myResult = new WhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement));
}
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Override
public void visitForStatement(PsiForStatement statement) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
Evaluator initializerEvaluator = accept(statement.getInitialization());
Evaluator conditionEvaluator = accept(statement.getCondition());
if (conditionEvaluator != null) {
conditionEvaluator = new UnBoxingEvaluator(conditionEvaluator);
}
Evaluator updateEvaluator = accept(statement.getUpdate());
Evaluator bodyEvaluator = accept(statement.getBody());
if (bodyEvaluator != null) {
myResult =
new ForStatementEvaluator(initializerEvaluator, conditionEvaluator, updateEvaluator, bodyEvaluator, getLabel(statement));
}
} finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Override
public void visitForeachStatement(PsiForeachStatement statement) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
PsiParameter parameter = statement.getIterationParameter();
String iterationParameterName = parameter.getName();
myCurrentFragmentEvaluator.setInitialValue(iterationParameterName, null);
SyntheticVariableEvaluator iterationParameterEvaluator =
new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, iterationParameterName, null);
Evaluator iteratedValueEvaluator = accept(statement.getIteratedValue());
Evaluator bodyEvaluator = accept(statement.getBody());
if (bodyEvaluator != null) {
myResult = new ForeachStatementEvaluator(iterationParameterEvaluator, iteratedValueEvaluator, bodyEvaluator, getLabel(statement));
}
} finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Nullable
private Evaluator accept(@Nullable PsiElement element) {
if (element == null || element instanceof PsiEmptyStatement) {
return null;
}
element.accept(this);
return myResult;
}
@Override
public void visitIfStatement(PsiIfStatement statement) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
PsiStatement thenBranch = statement.getThenBranch();
if(thenBranch == null) return;
thenBranch.accept(this);
Evaluator thenEvaluator = myResult;
PsiStatement elseBranch = statement.getElseBranch();
Evaluator elseEvaluator = null;
if(elseBranch != null){
elseBranch.accept(this);
elseEvaluator = myResult;
}
PsiExpression condition = statement.getCondition();
if(condition == null) return;
condition.accept(this);
myResult = new IfStatementEvaluator(new UnBoxingEvaluator(myResult), thenEvaluator, elseEvaluator);
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
private void visitSwitchBlock(PsiSwitchBlock statement) {
PsiCodeBlock body = statement.getBody();
if (body != null) {
Evaluator expressionEvaluator = accept(statement.getExpression());
if (expressionEvaluator != null) {
myResult = new SwitchEvaluator(expressionEvaluator, visitStatements(body.getStatements()), getLabel(statement));
}
}
}
@Override
public void visitSwitchStatement(PsiSwitchStatement statement) {
visitSwitchBlock(statement);
}
@Override
public void visitSwitchExpression(PsiSwitchExpression expression) {
visitSwitchBlock(expression);
}
private void visitSwitchLabelStatementBase(PsiSwitchLabelStatementBase statement) {
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
List<Evaluator> evaluators = new SmartList<>();
PsiCaseLabelElementList labelElementList = statement.getCaseLabelElementList();
boolean defaultCase = statement.isDefaultCase();
if (labelElementList != null) {
for (PsiCaseLabelElement labelElement : labelElementList.getElements()) {
if (labelElement instanceof PsiDefaultCaseLabelElement) {
defaultCase = true;
continue;
} else if (labelElement instanceof PsiPattern) {
PatternLabelEvaluator evaluator = getPatternLabelEvaluator((PsiPattern)labelElement);
if (evaluator != null) {
evaluators.add(evaluator);
}
continue;
}
Evaluator evaluator = accept(labelElement);
if (evaluator != null) {
evaluators.add(evaluator);
}
}
}
if (statement instanceof PsiSwitchLabeledRuleStatement) {
myResult = new SwitchEvaluator.SwitchCaseRuleEvaluator(evaluators, defaultCase,
accept(((PsiSwitchLabeledRuleStatement)statement).getBody()));
}
else {
myResult = new SwitchEvaluator.SwitchCaseEvaluator(evaluators, defaultCase);
}
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Nullable
private PatternLabelEvaluator getPatternLabelEvaluator(@NotNull PsiPattern pattern) {
PsiSwitchBlock switchBlock = PsiTreeUtil.getParentOfType(pattern, PsiSwitchBlock.class);
if (switchBlock == null) return null;
PsiExpression selector = switchBlock.getExpression();
if (selector == null) return null;
selector.accept(this);
Evaluator selectorEvaluator = myResult;
PsiPatternVariable patternVariable = JavaPsiPatternUtil.getPatternVariable(pattern);
if (patternVariable == null) return null;
PsiPattern naked = JavaPsiPatternUtil.skipParenthesizedPatternDown(pattern);
Evaluator guardingEvaluator = null;
if (naked instanceof PsiGuardedPattern) {
PsiExpression guardingExpression = ((PsiGuardedPattern)naked).getGuardingExpression();
if (guardingExpression != null) {
guardingExpression.accept(this);
guardingEvaluator = myResult != null ? new UnBoxingEvaluator(myResult) : null;
}
}
String patternVariableName = patternVariable.getName();
myCurrentFragmentEvaluator.setInitialValue(patternVariableName, null);
Evaluator patternVariableEvaluator = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, patternVariableName, null);
PsiType type = JavaPsiPatternUtil.getPatternType(pattern);
if (type == null) return null;
return new PatternLabelEvaluator(selectorEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)),
patternVariableEvaluator, guardingEvaluator);
}
@Override
public void visitSwitchLabelStatement(PsiSwitchLabelStatement statement) {
visitSwitchLabelStatementBase(statement);
}
@Override
public void visitSwitchLabeledRuleStatement(PsiSwitchLabeledRuleStatement statement) {
visitSwitchLabelStatementBase(statement);
}
@Override
public void visitBreakStatement(PsiBreakStatement statement) {
PsiIdentifier labelIdentifier = statement.getLabelIdentifier();
myResult = BreakContinueStatementEvaluator.createBreakEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null);
}
@Override
public void visitContinueStatement(PsiContinueStatement statement) {
PsiIdentifier labelIdentifier = statement.getLabelIdentifier();
myResult = BreakContinueStatementEvaluator.createContinueEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null);
}
@Override
public void visitExpressionListStatement(PsiExpressionListStatement statement) {
myResult = new ExpressionListEvaluator(ContainerUtil.mapNotNull(statement.getExpressionList().getExpressions(), this::accept));
}
@Override
public void visitEmptyStatement(PsiEmptyStatement statement) {
// do nothing
}
@Override
public void visitExpressionStatement(PsiExpressionStatement statement) {
statement.getExpression().accept(this);
}
@Override
public void visitExpression(PsiExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitExpression " + expression);
}
}
@Override
public void visitPolyadicExpression(PsiPolyadicExpression wideExpression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitPolyadicExpression " + wideExpression);
}
CodeFragmentEvaluator oldFragmentEvaluator = setNewCodeFragmentEvaluator();
try {
PsiExpression[] operands = wideExpression.getOperands();
operands[0].accept(this);
Evaluator result = myResult;
PsiType lType = operands[0].getType();
for (int i = 1; i < operands.length; i++) {
PsiExpression expression = operands[i];
if (expression == null) {
throwExpressionInvalid(wideExpression);
}
expression.accept(this);
Evaluator rResult = myResult;
IElementType opType = wideExpression.getOperationTokenType();
PsiType rType = expression.getType();
if (rType == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true);
if (typeForBinOp == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", wideExpression.getText()));
}
myResult = createBinaryEvaluator(result, lType, rResult, rType, opType, typeForBinOp);
lType = typeForBinOp;
result = myResult;
}
}
finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
// constructs binary evaluator handling unboxing and numeric promotion issues
private static Evaluator createBinaryEvaluator(Evaluator lResult,
PsiType lType,
Evaluator rResult,
@NotNull PsiType rType,
@NotNull IElementType operation,
@NotNull PsiType expressionExpectedType) {
// handle unboxing if necessary
if (isUnboxingInBinaryExpressionApplicable(lType, rType, operation)) {
if (rType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(rType.getCanonicalText())) {
rResult = new UnBoxingEvaluator(rResult);
}
if (lType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(lType.getCanonicalText())) {
lResult = new UnBoxingEvaluator(lResult);
}
}
if (isBinaryNumericPromotionApplicable(lType, rType, operation)) {
PsiType _lType = lType;
final PsiPrimitiveType unboxedLType = PsiPrimitiveType.getUnboxedType(lType);
if (unboxedLType != null) {
_lType = unboxedLType;
}
PsiType _rType = rType;
final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType);
if (unboxedRType != null) {
_rType = unboxedRType;
}
// handle numeric promotion
if (PsiType.DOUBLE.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.DOUBLE)) {
rResult = createTypeCastEvaluator(rResult, PsiType.DOUBLE);
}
}
else if (PsiType.DOUBLE.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.DOUBLE)) {
lResult = createTypeCastEvaluator(lResult, PsiType.DOUBLE);
}
}
else if (PsiType.FLOAT.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.FLOAT)) {
rResult = createTypeCastEvaluator(rResult, PsiType.FLOAT);
}
}
else if (PsiType.FLOAT.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.FLOAT)) {
lResult = createTypeCastEvaluator(lResult, PsiType.FLOAT);
}
}
else if (PsiType.LONG.equals(_lType)) {
if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.LONG)) {
rResult = createTypeCastEvaluator(rResult, PsiType.LONG);
}
}
else if (PsiType.LONG.equals(_rType)) {
if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.LONG)) {
lResult = createTypeCastEvaluator(lResult, PsiType.LONG);
}
}
else {
if (!PsiType.INT.equals(_lType) && TypeConversionUtil.areTypesConvertible(_lType, PsiType.INT)) {
lResult = createTypeCastEvaluator(lResult, PsiType.INT);
}
if (!PsiType.INT.equals(_rType) && TypeConversionUtil.areTypesConvertible(_rType, PsiType.INT)) {
rResult = createTypeCastEvaluator(rResult, PsiType.INT);
}
}
}
// unary numeric promotion if applicable
else if (ExpressionParser.SHIFT_OPS.contains(operation)) {
lResult = handleUnaryNumericPromotion(lType, lResult);
rResult = handleUnaryNumericPromotion(rType, rResult);
}
return DisableGC.create(new BinaryExpressionEvaluator(lResult, rResult, operation, expressionExpectedType.getCanonicalText()));
}
private static boolean isBinaryNumericPromotionApplicable(PsiType lType, PsiType rType, IElementType opType) {
if (lType == null || rType == null) {
return false;
}
if (!TypeConversionUtil.isNumericType(lType) || !TypeConversionUtil.isNumericType(rType)) {
return false;
}
if (opType == JavaTokenType.EQEQ || opType == JavaTokenType.NE) {
if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) {
return false;
}
if (lType instanceof PsiClassType && rType instanceof PsiClassType) {
return false;
}
if (lType instanceof PsiClassType) {
return PsiPrimitiveType.getUnboxedType(lType) != null; // should be unboxable
}
if (rType instanceof PsiClassType) {
return PsiPrimitiveType.getUnboxedType(rType) != null; // should be unboxable
}
return true;
}
return opType == JavaTokenType.ASTERISK ||
opType == JavaTokenType.DIV ||
opType == JavaTokenType.PERC ||
opType == JavaTokenType.PLUS ||
opType == JavaTokenType.MINUS ||
opType == JavaTokenType.LT ||
opType == JavaTokenType.LE ||
opType == JavaTokenType.GT ||
opType == JavaTokenType.GE ||
opType == JavaTokenType.AND ||
opType == JavaTokenType.XOR ||
opType == JavaTokenType.OR;
}
private static boolean isUnboxingInBinaryExpressionApplicable(PsiType lType, PsiType rType, IElementType opCode) {
if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) {
return false;
}
// handle '==' and '!=' separately
if (opCode == JavaTokenType.EQEQ || opCode == JavaTokenType.NE) {
return lType instanceof PsiPrimitiveType && rType instanceof PsiClassType ||
lType instanceof PsiClassType && rType instanceof PsiPrimitiveType;
}
// concat with a String
if (opCode == JavaTokenType.PLUS) {
if ((lType instanceof PsiClassType && lType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) ||
(rType instanceof PsiClassType && rType.equalsToText(CommonClassNames.JAVA_LANG_STRING))){
return false;
}
}
// all other operations at least one should be of class type
return lType instanceof PsiClassType || rType instanceof PsiClassType;
}
/**
* @param type
* @return promotion type to cast to or null if no casting needed
*/
@Nullable
private static PsiType calcUnaryNumericPromotionType(PsiPrimitiveType type) {
if (PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type) || PsiType.CHAR.equals(type) || PsiType.INT.equals(type)) {
return PsiType.INT;
}
return null;
}
@Override
public void visitDeclarationStatement(PsiDeclarationStatement statement) {
List<Evaluator> evaluators = new ArrayList<>();
PsiElement[] declaredElements = statement.getDeclaredElements();
for (PsiElement declaredElement : declaredElements) {
if (declaredElement instanceof PsiLocalVariable) {
if (myCurrentFragmentEvaluator != null) {
final PsiLocalVariable localVariable = (PsiLocalVariable)declaredElement;
final PsiType lType = localVariable.getType();
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(localVariable.getProject());
try {
PsiExpression initialValue = elementFactory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(lType), null);
Object value = JavaConstantExpressionEvaluator.computeConstantExpression(initialValue, true);
myCurrentFragmentEvaluator.setInitialValue(localVariable.getName(), value);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
PsiExpression initializer = localVariable.getInitializer();
if (initializer != null) {
try {
if (!TypeConversionUtil.areTypesAssignmentCompatible(lType, initializer)) {
throwEvaluateException(
JavaDebuggerBundle.message("evaluation.error.incompatible.variable.initializer.type", localVariable.getName()));
}
final PsiType rType = initializer.getType();
initializer.accept(this);
Evaluator rEvaluator = myResult;
PsiExpression localVarReference = elementFactory.createExpressionFromText(localVariable.getName(), initializer);
localVarReference.accept(this);
Evaluator lEvaluator = myResult;
rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(localVarReference.getType(), rType, rEvaluator,
statement.getProject());
Evaluator assignment = new AssignmentEvaluator(lEvaluator, rEvaluator);
evaluators.add(assignment);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
else {
throw new EvaluateRuntimeException(new EvaluateException(
JavaDebuggerBundle.message("evaluation.error.local.variable.declarations.not.supported"), null));
}
}
else {
throw new EvaluateRuntimeException(new EvaluateException(
JavaDebuggerBundle.message("evaluation.error.unsupported.declaration", declaredElement.getText()), null));
}
}
if(!evaluators.isEmpty()) {
CodeFragmentEvaluator codeFragmentEvaluator = new CodeFragmentEvaluator(myCurrentFragmentEvaluator);
codeFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[0]));
myResult = codeFragmentEvaluator;
} else {
myResult = null;
}
}
@Override
public void visitConditionalExpression(PsiConditionalExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitConditionalExpression " + expression);
}
final PsiExpression thenExpression = expression.getThenExpression();
final PsiExpression elseExpression = expression.getElseExpression();
if (thenExpression == null || elseExpression == null){
throwExpressionInvalid(expression);
}
PsiExpression condition = expression.getCondition();
condition.accept(this);
if (myResult == null) {
throwExpressionInvalid(condition);
}
Evaluator conditionEvaluator = new UnBoxingEvaluator(myResult);
thenExpression.accept(this);
if (myResult == null) {
throwExpressionInvalid(thenExpression);
}
Evaluator thenEvaluator = myResult;
elseExpression.accept(this);
if (myResult == null) {
throwExpressionInvalid(elseExpression);
}
Evaluator elseEvaluator = myResult;
myResult = new ConditionalExpressionEvaluator(conditionEvaluator, thenEvaluator, elseEvaluator);
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitReferenceExpression " + expression);
}
PsiExpression qualifier = expression.getQualifierExpression();
JavaResolveResult resolveResult = expression.advancedResolve(true);
PsiElement element = resolveResult.getElement();
if (element instanceof PsiLocalVariable || element instanceof PsiParameter) {
final Value labeledValue = element.getUserData(CodeFragmentFactoryContextWrapper.LABEL_VARIABLE_VALUE_KEY);
if (labeledValue != null) {
myResult = new IdentityEvaluator(labeledValue);
return;
}
final PsiVariable psiVar = (PsiVariable)element;
String localName = psiVar.getName();
//synthetic variable
final PsiFile containingFile = element.getContainingFile();
if (myCurrentFragmentEvaluator != null &&
((containingFile instanceof PsiCodeFragment && myVisitedFragments.contains(containingFile)) ||
myCurrentFragmentEvaluator.hasValue(localName))) {
// psiVariable may live in PsiCodeFragment not only in debugger editors, for example Fabrique has such variables.
// So treat it as synthetic var only when this code fragment is located in DebuggerEditor,
// that's why we need to check that containing code fragment is the one we visited
JVMName jvmName = JVMNameUtil.getJVMQualifiedName(CompilingEvaluatorTypesUtil.getVariableType((PsiVariable)element));
myResult = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, localName, jvmName);
return;
}
// local variable
PsiClass variableClass = getContainingClass(psiVar);
final PsiClass positionClass = getPositionClass();
if (Objects.equals(positionClass, variableClass)) {
PsiElement method = DebuggerUtilsEx.getContainingMethod(expression);
boolean canScanFrames = method instanceof PsiLambdaExpression || ContextUtil.isJspImplicit(element);
myResult = new LocalVariableEvaluator(localName, canScanFrames);
return;
}
// the expression references final var outside the context's class (in some of the outer classes)
// oneLevelLess() because val$ are located in the same class
CaptureTraverser traverser = createTraverser(variableClass, "Base class not found for " + psiVar.getName(), false).oneLevelLess();
if (traverser.isValid()) {
PsiExpression initializer = psiVar.getInitializer();
if(initializer != null) {
Object value = JavaPsiFacade.getInstance(psiVar.getProject()).getConstantEvaluationHelper().computeConstantExpression(initializer);
if(value != null) {
PsiType type = resolveResult.getSubstitutor().substitute(psiVar.getType());
myResult = new LiteralEvaluator(value, type.getCanonicalText());
return;
}
}
Evaluator objectEvaluator = new ThisEvaluator(traverser);
myResult = createFallbackEvaluator(
new FieldEvaluator(objectEvaluator, FieldEvaluator.createClassFilter(positionClass), "val$" + localName),
new LocalVariableEvaluator(localName, true));
return;
}
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.local.variable.missing.from.class.closure", localName));
}
else if (element instanceof PsiField) {
final PsiField psiField = (PsiField)element;
final PsiClass fieldClass = psiField.getContainingClass();
if(fieldClass == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.cannot.resolve.field.class", psiField.getName())); return;
}
Evaluator objectEvaluator;
if (psiField.hasModifierProperty(PsiModifier.STATIC)) {
JVMName className = JVMNameUtil.getContextClassJVMQualifiedName(SourcePosition.createFromElement(psiField));
if (className == null) {
className = JVMNameUtil.getJVMQualifiedName(fieldClass);
}
objectEvaluator = new TypeEvaluator(className);
}
else if(qualifier != null) {
qualifier.accept(this);
objectEvaluator = myResult;
}
else {
CaptureTraverser traverser = createTraverser(fieldClass, fieldClass.getName(), true);
if (!traverser.isValid()) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.cannot.sources.for.field.class", psiField.getName()));
}
objectEvaluator = new ThisEvaluator(traverser);
}
myResult = new FieldEvaluator(objectEvaluator, FieldEvaluator.createClassFilter(fieldClass), psiField.getName());
}
else {
//let's guess what this could be
PsiElement nameElement = expression.getReferenceNameElement(); // get "b" part
String name;
if (nameElement instanceof PsiIdentifier) {
name = nameElement.getText();
}
else {
//noinspection HardCodedStringLiteral
final String elementDisplayString = nameElement != null ? nameElement.getText() : "(null)";
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.identifier.expected", elementDisplayString));
return;
}
if(qualifier != null) {
final PsiElement qualifierTarget = qualifier instanceof PsiReferenceExpression
? ((PsiReferenceExpression)qualifier).resolve() : null;
if (qualifierTarget instanceof PsiClass) {
// this is a call to a 'static' field
PsiClass psiClass = (PsiClass)qualifierTarget;
final JVMName typeName = JVMNameUtil.getJVMQualifiedName(psiClass);
myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.createClassFilter(psiClass), name);
}
else {
qualifier.accept(this);
if (myResult == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", qualifier.getText()));
}
myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(qualifier.getType()), name);
}
}
else {
myResult = createFallbackEvaluator(new LocalVariableEvaluator(name, false),
new FieldEvaluator(new ThisEvaluator(), FieldEvaluator.TargetClassFilter.ALL, name));
}
}
}
private static Evaluator createFallbackEvaluator(final Evaluator primary, final Evaluator fallback) {
return new Evaluator() {
private boolean myIsFallback;
@Override
public Object evaluate(EvaluationContextImpl context) throws EvaluateException {
try {
return primary.evaluate(context);
}
catch (EvaluateException e) {
try {
Object res = fallback.evaluate(context);
myIsFallback = true;
return res;
}
catch (EvaluateException e1) {
throw e;
}
}
}
@Override
public Modifier getModifier() {
return myIsFallback ? fallback.getModifier() : primary.getModifier();
}
};
}
private static void throwExpressionInvalid(PsiElement expression) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.invalid.expression", expression.getText()));
}
private static void throwEvaluateException(String message) throws EvaluateRuntimeException {
throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(message));
}
@Override
public void visitSuperExpression(PsiSuperExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitSuperExpression " + expression);
}
myResult = new SuperEvaluator(createTraverser(expression.getQualifier()));
}
@Override
public void visitThisExpression(PsiThisExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitThisExpression " + expression);
}
myResult = new ThisEvaluator(createTraverser(expression.getQualifier()));
}
private CaptureTraverser createTraverser(final PsiJavaCodeReferenceElement qualifier) {
if (qualifier != null) {
return createTraverser(qualifier.resolve(), qualifier.getText(), false);
}
return CaptureTraverser.direct();
}
private CaptureTraverser createTraverser(PsiElement targetClass, String name, boolean checkInheritance) {
PsiClass fromClass = getPositionClass();
if (!(targetClass instanceof PsiClass) || fromClass == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.invalid.expression", name));
}
try {
CaptureTraverser traverser = CaptureTraverser.create((PsiClass)targetClass, fromClass, checkInheritance);
if (!traverser.isValid() && !fromClass.equals(myContextPsiClass)) { // do not check twice
traverser = CaptureTraverser.create((PsiClass)targetClass, myContextPsiClass, checkInheritance);
}
if (!traverser.isValid()) {
LOG.warn("Unable create valid CaptureTraverser to access 'this'.");
traverser = CaptureTraverser.direct();
}
return traverser;
}
catch (Exception e) {
throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(e));
}
}
@Override
public void visitInstanceOfExpression(PsiInstanceOfExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitInstanceOfExpression " + expression);
}
PsiElement parentOfType = PsiTreeUtil.getParentOfType(expression, PsiWhileStatement.class,
PsiIfStatement.class, PsiPolyadicExpression.class);
CodeFragmentEvaluator oldFragmentEvaluator = parentOfType != null ?
myCurrentFragmentEvaluator : setNewCodeFragmentEvaluator();
try {
PsiTypeElement checkType = expression.getCheckType();
if (checkType == null) {
throwExpressionInvalid(expression);
}
PsiType type = checkType.getType();
expression.getOperand().accept(this);
// ClassObjectEvaluator typeEvaluator = new ClassObjectEvaluator(type.getCanonicalText());
Evaluator operandEvaluator = myResult;
Evaluator patternVariable = null;
PsiPattern pattern = expression.getPattern();
if (pattern instanceof PsiTypeTestPattern) {
PsiPatternVariable variable = ((PsiTypeTestPattern)pattern).getPatternVariable();
if (variable != null) {
String variableName = variable.getName();
myCurrentFragmentEvaluator.setInitialValue(variableName, null);
patternVariable = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, variableName, null);
}
}
myResult = new InstanceofEvaluator(operandEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)), patternVariable);
} finally {
myCurrentFragmentEvaluator = oldFragmentEvaluator;
}
}
@Override
public void visitParenthesizedExpression(PsiParenthesizedExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitParenthesizedExpression " + expression);
}
PsiExpression expr = expression.getExpression();
if (expr != null){
expr.accept(this);
}
}
@Override
public void visitPostfixExpression(PsiPostfixExpression expression) {
if(expression.getType() == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiExpression operandExpression = expression.getOperand();
operandExpression.accept(this);
final Evaluator operandEvaluator = myResult;
final IElementType operation = expression.getOperationTokenType();
final PsiType operandType = operandExpression.getType();
@Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType);
Evaluator incrementImpl = createBinaryEvaluator(
operandEvaluator, operandType,
new LiteralEvaluator(1, "int"), PsiType.INT,
operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS,
unboxedOperandType!= null? unboxedOperandType : operandType
);
if (unboxedOperandType != null) {
incrementImpl = new BoxingEvaluator(incrementImpl);
}
myResult = new PostfixOperationEvaluator(operandEvaluator, incrementImpl);
}
@Override
public void visitPrefixExpression(final PsiPrefixExpression expression) {
final PsiType expressionType = expression.getType();
if(expressionType == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText()));
}
final PsiExpression operandExpression = expression.getOperand();
if (operandExpression == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.expression.operand", expression.getText()));
}
operandExpression.accept(this);
Evaluator operandEvaluator = myResult;
// handle unboxing issues
final PsiType operandType = operandExpression.getType();
@Nullable
final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType);
final IElementType operation = expression.getOperationTokenType();
if(operation == JavaTokenType.PLUSPLUS || operation == JavaTokenType.MINUSMINUS) {
try {
final Evaluator rightEval = createBinaryEvaluator(
operandEvaluator, operandType,
new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT,
operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS,
unboxedOperandType!= null? unboxedOperandType : operandType
);
myResult = new AssignmentEvaluator(operandEvaluator, unboxedOperandType != null? new BoxingEvaluator(rightEval) : rightEval);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
else {
if (JavaTokenType.PLUS.equals(operation) || JavaTokenType.MINUS.equals(operation)|| JavaTokenType.TILDE.equals(operation)) {
operandEvaluator = handleUnaryNumericPromotion(operandType, operandEvaluator);
}
else {
if (unboxedOperandType != null) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
}
myResult = new UnaryExpressionEvaluator(operation, expressionType.getCanonicalText(), operandEvaluator, expression.getOperationSign().getText());
}
}
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
if (LOG.isDebugEnabled()) {
LOG.debug("visitMethodCallExpression " + expression);
}
final PsiExpressionList argumentList = expression.getArgumentList();
final PsiExpression[] argExpressions = argumentList.getExpressions();
Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length];
// evaluate arguments
for (int idx = 0; idx < argExpressions.length; idx++) {
final PsiExpression psiExpression = argExpressions[idx];
psiExpression.accept(this);
if (myResult == null) {
// cannot build evaluator
throwExpressionInvalid(psiExpression);
}
argumentEvaluators[idx] = DisableGC.create(myResult);
}
PsiReferenceExpression methodExpr = expression.getMethodExpression();
final JavaResolveResult resolveResult = methodExpr.advancedResolve(false);
final PsiMethod psiMethod = CompilingEvaluatorTypesUtil.getReferencedMethod(resolveResult);
PsiExpression qualifier = methodExpr.getQualifierExpression();
Evaluator objectEvaluator;
JVMName contextClass = null;
if(psiMethod != null) {
PsiClass methodPsiClass = psiMethod.getContainingClass();
contextClass = JVMNameUtil.getJVMQualifiedName(methodPsiClass);
if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
objectEvaluator = new TypeEvaluator(contextClass);
}
else if (qualifier != null ) {
qualifier.accept(this);
objectEvaluator = myResult;
}
else {
CaptureTraverser traverser = CaptureTraverser.direct();
PsiElement currentFileResolveScope = resolveResult.getCurrentFileResolveScope();
if (currentFileResolveScope instanceof PsiClass) {
traverser = createTraverser(currentFileResolveScope, ((PsiClass)currentFileResolveScope).getName(), false);
}
objectEvaluator = new ThisEvaluator(traverser);
}
}
else {
//trying to guess
if (qualifier != null) {
PsiType type = qualifier.getType();
if (type != null) {
contextClass = JVMNameUtil.getJVMQualifiedName(type);
}
if (qualifier instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifier).resolve() instanceof PsiClass) {
// this is a call to a 'static' method but class is not available, try to evaluate by qname
if (contextClass == null) {
contextClass = JVMNameUtil.getJVMRawText(((PsiReferenceExpression)qualifier).getQualifiedName());
}
objectEvaluator = new TypeEvaluator(contextClass);
}
else {
qualifier.accept(this);
objectEvaluator = myResult;
}
}
else {
objectEvaluator = new ThisEvaluator();
PsiClass positionClass = getPositionClass();
if (positionClass != null) {
contextClass = JVMNameUtil.getJVMQualifiedName(positionClass);
}
//else {
// throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(
// JavaDebuggerBundle.message("evaluation.error.method.not.found", methodExpr.getReferenceName()))
// );
//}
}
}
if (objectEvaluator == null) {
throwExpressionInvalid(expression);
}
if (psiMethod != null && !psiMethod.isConstructor()) {
if (psiMethod.getReturnType() == null) {
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.unknown.method.return.type", psiMethod.getText()));
}
}
boolean mustBeVararg = false;
if (psiMethod != null) {
processBoxingConversions(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators);
mustBeVararg = psiMethod.isVarArgs();
}
myResult = new MethodEvaluator(objectEvaluator, contextClass, methodExpr.getReferenceName(),
psiMethod != null ? JVMNameUtil.getJVMSignature(psiMethod) : null, argumentEvaluators,
mustBeVararg);
}
@Override
public void visitLiteralExpression(PsiLiteralExpression expression) {
final HighlightInfo parsingError = HighlightUtil.checkLiteralExpressionParsingError(expression, PsiUtil.getLanguageLevel(expression), null);
if (parsingError != null) {
throwEvaluateException(parsingError.getDescription());
return;
}
final PsiType type = expression.getType();
if (type == null) {
throwEvaluateException(expression + ": null type");
return;
}
myResult = new LiteralEvaluator(expression.getValue(), type.getCanonicalText());
}
@Override
public void visitArrayAccessExpression(PsiArrayAccessExpression expression) {
final PsiExpression indexExpression = expression.getIndexExpression();
if(indexExpression == null) {
throwExpressionInvalid(expression);
}
indexExpression.accept(this);
final Evaluator indexEvaluator = handleUnaryNumericPromotion(indexExpression.getType(), myResult);
expression.getArrayExpression().accept(this);
Evaluator arrayEvaluator = myResult;
myResult = new ArrayAccessEvaluator(arrayEvaluator, indexEvaluator);
}
/**
* Handles unboxing and numeric promotion issues for
* - array dimension expressions
* - array index expression
* - unary +, -, and ~ operations
* @param operandExpressionType
* @param operandEvaluator @return operandEvaluator possibly 'wrapped' with necessary unboxing and type-casting evaluators to make returning value
* suitable for mentioned contexts
*/
private static Evaluator handleUnaryNumericPromotion(final PsiType operandExpressionType, Evaluator operandEvaluator) {
final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(operandExpressionType);
if (unboxedType != null && !PsiType.BOOLEAN.equals(unboxedType)) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
// handle numeric promotion
final PsiType _unboxedIndexType = unboxedType != null? unboxedType : operandExpressionType;
if (_unboxedIndexType instanceof PsiPrimitiveType) {
final PsiType promotionType = calcUnaryNumericPromotionType((PsiPrimitiveType)_unboxedIndexType);
if (promotionType != null) {
operandEvaluator = createTypeCastEvaluator(operandEvaluator, promotionType);
}
}
return operandEvaluator;
}
@Override
public void visitTypeCastExpression(PsiTypeCastExpression expression) {
PsiExpression operandExpr = expression.getOperand();
if (operandExpr == null) {
throwExpressionInvalid(expression);
}
operandExpr.accept(this);
Evaluator operandEvaluator = myResult;
PsiTypeElement castTypeElem = expression.getCastType();
if (castTypeElem == null) {
throwExpressionInvalid(expression);
}
PsiType castType = castTypeElem.getType();
PsiType operandType = operandExpr.getType();
// if operand type can not be resolved in current context - leave it for runtime checks
if (operandType != null &&
!TypeConversionUtil.areTypesConvertible(operandType, castType) &&
PsiUtil.resolveClassInType(operandType) != null) {
throw new EvaluateRuntimeException(
new EvaluateException(
JavaErrorBundle.message("inconvertible.type.cast", JavaHighlightUtil.formatType(operandType), JavaHighlightUtil
.formatType(castType)))
);
}
boolean shouldPerformBoxingConversion = operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType);
final boolean castingToPrimitive = castType instanceof PsiPrimitiveType;
if (shouldPerformBoxingConversion && castingToPrimitive) {
operandEvaluator = new UnBoxingEvaluator(operandEvaluator);
}
final boolean performCastToWrapperClass = shouldPerformBoxingConversion && !castingToPrimitive;
if (!(PsiUtil.resolveClassInClassTypeOnly(castType) instanceof PsiTypeParameter)) {
if (performCastToWrapperClass) {
castType = ObjectUtils.notNull(PsiPrimitiveType.getUnboxedType(castType), operandType);
}
myResult = createTypeCastEvaluator(operandEvaluator, castType);
}
if (performCastToWrapperClass) {
myResult = new BoxingEvaluator(myResult);
}
}
private static TypeCastEvaluator createTypeCastEvaluator(Evaluator operandEvaluator, PsiType castType) {
if (castType instanceof PsiPrimitiveType) {
return new TypeCastEvaluator(operandEvaluator, castType.getCanonicalText());
}
else {
return new TypeCastEvaluator(operandEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(castType)));
}
}
@Override
public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) {
PsiType type = expression.getOperand().getType();
if (type instanceof PsiPrimitiveType) {
final JVMName typeName = JVMNameUtil.getJVMRawText(((PsiPrimitiveType)type).getBoxedTypeName());
myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.TargetClassFilter.ALL, "TYPE");
}
else {
myResult = new ClassObjectEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)));
}
}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {
throw new EvaluateRuntimeException(new UnsupportedExpressionException(
JavaDebuggerBundle.message("evaluation.error.lambda.evaluation.not.supported")));
}
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
PsiElement qualifier = expression.getQualifier();
PsiType interfaceType = expression.getFunctionalInterfaceType();
if (!Registry.is("debugger.compiling.evaluator.method.refs") && interfaceType != null && qualifier != null) {
String code = null;
try {
PsiElement resolved = expression.resolve();
if (resolved instanceof PsiMethod) {
PsiMethod method = (PsiMethod)resolved;
PsiClass containingClass = method.getContainingClass();
if (containingClass != null) {
String find;
boolean bind = false;
if (method.isConstructor()) {
find = "findConstructor(" + containingClass.getQualifiedName() + ".class, mt)";
}
else if (qualifier instanceof PsiSuperExpression) {
find = "in(" + containingClass.getQualifiedName() + ".class).findSpecial(" +
containingClass.getQualifiedName() + ".class, \"" + method.getName() + "\", mt, " +
containingClass.getQualifiedName() + ".class)";
bind = true;
}
else {
find = containingClass.getQualifiedName() + ".class, \"" + method.getName() + "\", mt)";
if (method.hasModifier(JvmModifier.STATIC)) {
find = "findStatic(" + find;
}
else {
find = "findVirtual(" + find;
if (qualifier instanceof PsiReference) {
PsiElement resolve = ((PsiReference)qualifier).resolve();
if (!(resolve instanceof PsiClass)) {
bind = true;
}
}
else {
bind = true;
}
}
}
String bidStr = bind ? "mh = mh.bindTo(" + qualifier.getText() + ");\n" : "";
code =
"MethodType mt = MethodType.fromMethodDescriptorString(\"" + JVMNameUtil.getJVMSignature(method) + "\", null);\n" +
"MethodHandle mh = MethodHandles.lookup()." + find + ";\n" +
bidStr +
"MethodHandleProxies.asInterfaceInstance(" + interfaceType.getCanonicalText() + ".class, mh);";
}
} else if (PsiUtil.isArrayClass(resolved)) {
code =
"MethodType mt = MethodType.methodType(Object.class, Class.class, int.class);\n" +
"MethodHandle mh = MethodHandles.publicLookup().findStatic(Array.class, \"newInstance\", mt);\n" +
"mh = mh.bindTo(" + StringUtil.substringBeforeLast(qualifier.getText(), "[]") + ".class)\n" +
"MethodHandleProxies.asInterfaceInstance(" + interfaceType.getCanonicalText() + ".class, mh);";
}
if (code != null) {
myResult = buildFromJavaCode(code,
"java.lang.invoke.MethodHandle," +
"java.lang.invoke.MethodHandleProxies," +
"java.lang.invoke.MethodHandles," +
"java.lang.invoke.MethodType," +
"java.lang.reflect.Array",
expression);
return;
}
}
catch (Exception e) {
LOG.error(e);
}
}
throw new EvaluateRuntimeException(
new UnsupportedExpressionException(JavaDebuggerBundle.message("evaluation.error.method.reference.evaluation.not.supported")));
}
private Evaluator buildFromJavaCode(String code, String imports, @NotNull PsiElement context) {
TextWithImportsImpl text = new TextWithImportsImpl(CodeFragmentKind.CODE_BLOCK, code, imports, JavaFileType.INSTANCE);
JavaCodeFragment codeFragment = DefaultCodeFragmentFactory.getInstance().createCodeFragment(text, context, context.getProject());
return accept(codeFragment);
}
@Override
public void visitNewExpression(final PsiNewExpression expression) {
PsiType expressionPsiType = expression.getType();
if (expressionPsiType instanceof PsiArrayType) {
Evaluator dimensionEvaluator = null;
PsiExpression[] dimensions = expression.getArrayDimensions();
if (dimensions.length == 1){
PsiExpression dimensionExpression = dimensions[0];
dimensionExpression.accept(this);
if (myResult != null) {
dimensionEvaluator = handleUnaryNumericPromotion(dimensionExpression.getType(), myResult);
}
else {
throwEvaluateException(
JavaDebuggerBundle.message("evaluation.error.invalid.array.dimension.expression", dimensionExpression.getText()));
}
}
else if (dimensions.length > 1){
throwEvaluateException(JavaDebuggerBundle.message("evaluation.error.multi.dimensional.arrays.creation.not.supported"));
}
Evaluator initializerEvaluator = null;
PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer();
if (arrayInitializer != null) {
if (dimensionEvaluator != null) { // initializer already exists
throwExpressionInvalid(expression);
}
arrayInitializer.accept(this);
if (myResult != null) {
initializerEvaluator = handleUnaryNumericPromotion(arrayInitializer.getType(), myResult);
}
else {
throwExpressionInvalid(arrayInitializer);
}
/*
PsiExpression[] initializers = arrayInitializer.getInitializers();
initializerEvaluators = new Evaluator[initializers.length];
for (int idx = 0; idx < initializers.length; idx++) {
PsiExpression initializer = initializers[idx];
initializer.accept(this);
if (myResult instanceof Evaluator) {
initializerEvaluators[idx] = myResult;
}
else {
throw new EvaluateException("Invalid expression for array initializer: " + initializer.getText(), true);
}
}
*/
}
if (dimensionEvaluator == null && initializerEvaluator == null) {
throwExpressionInvalid(expression);
}
myResult = new NewArrayInstanceEvaluator(
new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)),
dimensionEvaluator,
initializerEvaluator
);
}
else if (expressionPsiType instanceof PsiClassType){ // must be a class ref
PsiClass aClass = CompilingEvaluatorTypesUtil.getClass((PsiClassType)expressionPsiType);
if(aClass instanceof PsiAnonymousClass) {
throw new EvaluateRuntimeException(new UnsupportedExpressionException(
JavaDebuggerBundle.message("evaluation.error.anonymous.class.evaluation.not.supported")));
}
PsiExpressionList argumentList = expression.getArgumentList();
if (argumentList == null) {
throwExpressionInvalid(expression);
}
final PsiExpression[] argExpressions = argumentList.getExpressions();
final JavaResolveResult constructorResolveResult = expression.resolveMethodGenerics();
PsiMethod constructor = CompilingEvaluatorTypesUtil.getReferencedConstructor((PsiMethod)constructorResolveResult.getElement());
if (constructor == null && argExpressions.length > 0) {
throw new EvaluateRuntimeException(new EvaluateException(
JavaDebuggerBundle.message("evaluation.error.cannot.resolve.constructor", expression.getText()), null));
}
Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length];
// evaluate arguments
for (int idx = 0; idx < argExpressions.length; idx++) {
PsiExpression argExpression = argExpressions[idx];
argExpression.accept(this);
if (myResult != null) {
argumentEvaluators[idx] = DisableGC.create(myResult);
}
else {
throwExpressionInvalid(argExpression);
}
}
if (constructor != null) {
processBoxingConversions(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators);
}
if (aClass != null) {
PsiClass containingClass = aClass.getContainingClass();
if (containingClass != null && !aClass.hasModifierProperty(PsiModifier.STATIC)) {
PsiExpression qualifier = expression.getQualifier();
if (qualifier != null) {
qualifier.accept(this);
if (myResult != null) {
argumentEvaluators = ArrayUtil.prepend(myResult, argumentEvaluators);
}
}
else {
argumentEvaluators = ArrayUtil.prepend(
new ThisEvaluator(createTraverser(containingClass, "this", false)),
argumentEvaluators);
}
}
}
JVMName signature = JVMNameUtil.getJVMConstructorSignature(constructor, aClass);
PsiType instanceType = CompilingEvaluatorTypesUtil.getClassType((PsiClassType)expressionPsiType);
myResult = new NewClassInstanceEvaluator(
new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(instanceType)),
signature,
argumentEvaluators
);
}
else {
if (expressionPsiType != null) {
throwEvaluateException("Unsupported expression type: " + expressionPsiType.getPresentableText());
}
else {
throwEvaluateException("Unknown type for expression: " + expression.getText());
}
}
}
@Override
public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) {
PsiExpression[] initializers = expression.getInitializers();
Evaluator[] evaluators = new Evaluator[initializers.length];
final PsiType type = expression.getType();
boolean primitive = type instanceof PsiArrayType && ((PsiArrayType)type).getComponentType() instanceof PsiPrimitiveType;
for (int idx = 0; idx < initializers.length; idx++) {
PsiExpression initializer = initializers[idx];
initializer.accept(this);
if (myResult != null) {
final Evaluator coerced =
primitive ? handleUnaryNumericPromotion(initializer.getType(), myResult) : new BoxingEvaluator(myResult);
evaluators[idx] = DisableGC.create(coerced);
}
else {
throwExpressionInvalid(initializer);
}
}
myResult = new ArrayInitializerEvaluator(evaluators);
if (type != null && !(expression.getParent() instanceof PsiNewExpression)) {
myResult = new NewArrayInstanceEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)),
null,
myResult);
}
}
@Override
public void visitAssertStatement(PsiAssertStatement statement) {
PsiExpression condition = statement.getAssertCondition();
if (condition == null) {
throwEvaluateException("Assert condition expected in: " + statement.getText());
}
PsiExpression description = statement.getAssertDescription();
String descriptionText = description != null ? description.getText() : "";
myResult = new AssertStatementEvaluator(buildFromJavaCode("if (!(" + condition.getText() + ")) { " +
"throw new java.lang.AssertionError(" + descriptionText + ");}",
"", statement));
}
@Nullable
private PsiClass getContainingClass(@NotNull PsiVariable variable) {
PsiClass element = PsiTreeUtil.getParentOfType(variable.getParent(), PsiClass.class, false);
return element == null ? myContextPsiClass : element;
}
@Nullable
private PsiClass getPositionClass() {
return myPositionPsiClass != null ? myPositionPsiClass : myContextPsiClass;
}
private ExpressionEvaluator buildElement(final PsiElement element) throws EvaluateException {
LOG.assertTrue(element.isValid());
setNewCodeFragmentEvaluator(); // in case element is not a code fragment
myContextPsiClass = PsiTreeUtil.getContextOfType(element, PsiClass.class, false);
try {
element.accept(this);
}
catch (EvaluateRuntimeException e) {
throw e.getCause();
}
if (myResult == null) {
throw EvaluateExceptionUtil
.createEvaluateException(JavaDebuggerBundle.message("evaluation.error.invalid.expression", element.toString()));
}
return new ExpressionEvaluatorImpl(myResult);
}
}
private static void processBoxingConversions(final PsiParameter[] declaredParams,
final PsiExpression[] actualArgumentExpressions,
final PsiSubstitutor methodResolveSubstitutor,
final Evaluator[] argumentEvaluators) {
if (declaredParams.length > 0) {
final int paramCount = Math.max(declaredParams.length, actualArgumentExpressions.length);
PsiType varargType = null;
for (int idx = 0; idx < paramCount; idx++) {
if (idx >= actualArgumentExpressions.length) {
break; // actual arguments count is less than number of declared params
}
PsiType declaredParamType;
if (idx < declaredParams.length) {
declaredParamType = methodResolveSubstitutor.substitute(declaredParams[idx].getType());
if (declaredParamType instanceof PsiEllipsisType) {
declaredParamType = varargType = ((PsiEllipsisType)declaredParamType).getComponentType();
}
}
else if (varargType != null) {
declaredParamType = varargType;
}
else {
break;
}
final PsiType actualArgType = actualArgumentExpressions[idx].getType();
if (TypeConversionUtil.boxingConversionApplicable(declaredParamType, actualArgType) ||
(declaredParamType != null && actualArgType == null)) {
final Evaluator argEval = argumentEvaluators[idx];
argumentEvaluators[idx] = declaredParamType instanceof PsiPrimitiveType ? new UnBoxingEvaluator(argEval) : new BoxingEvaluator(argEval);
}
}
}
}
/**
* Contains a set of methods to ensure access to extracted generated class in compiling evaluator
*/
private static class CompilingEvaluatorTypesUtil {
@NotNull
private static PsiType getVariableType(@NotNull PsiVariable variable) {
PsiType type = variable.getType();
PsiClass psiClass = PsiTypesUtil.getPsiClass(type);
if (psiClass != null) {
PsiType typeToUse = psiClass.getUserData(ExtractLightMethodObjectHandler.REFERENCED_TYPE);
if (typeToUse != null) {
type = typeToUse;
}
}
return type;
}
@Nullable
private static PsiMethod getReferencedMethod(@NotNull JavaResolveResult resolveResult) {
PsiMethod psiMethod = (PsiMethod)resolveResult.getElement();
PsiMethod methodToUseInstead = psiMethod == null ? null : psiMethod.getUserData(ExtractLightMethodObjectHandler.REFERENCE_METHOD);
if (methodToUseInstead != null) {
psiMethod = methodToUseInstead;
}
return psiMethod;
}
@Nullable
private static PsiClass getClass(@NotNull PsiClassType classType) {
PsiClass aClass = classType.resolve();
PsiType type = aClass == null ? null : aClass.getUserData(ExtractLightMethodObjectHandler.REFERENCED_TYPE);
if (type != null) {
return PsiTypesUtil.getPsiClass(type);
}
return aClass;
}
@Nullable
@Contract("null -> null")
private static PsiMethod getReferencedConstructor(@Nullable PsiMethod originalConstructor) {
if (originalConstructor == null) return null;
PsiMethod methodToUseInstead = originalConstructor.getUserData(ExtractLightMethodObjectHandler.REFERENCE_METHOD);
return methodToUseInstead == null ? originalConstructor : methodToUseInstead;
}
@NotNull
private static PsiType getClassType(@NotNull PsiClassType expressionPsiType) {
PsiClass aClass = expressionPsiType.resolve();
PsiType type = aClass == null ? null : aClass.getUserData(ExtractLightMethodObjectHandler.REFERENCED_TYPE);
return type != null ? type : expressionPsiType;
}
}
}
| smmribeiro/intellij-community | java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java | Java | apache-2.0 | 76,789 |
/* 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 org.activiti5.engine.test.cfg;
import org.activiti5.engine.ActivitiException;
import org.activiti5.engine.ActivitiOptimisticLockingException;
import org.activiti5.engine.impl.interceptor.Command;
import org.activiti5.engine.impl.interceptor.CommandConfig;
import org.activiti5.engine.impl.interceptor.CommandContext;
import org.activiti5.engine.impl.interceptor.CommandInvoker;
import org.activiti5.engine.impl.interceptor.RetryInterceptor;
import junit.framework.TestCase;
/**
*
* @author Daniel Meyer
*/
public class RetryInterceptorTest extends TestCase {
protected class CommandThrowingOptimisticLockingException implements Command<Void> {
public Void execute(CommandContext commandContext) {
throw new ActivitiOptimisticLockingException("");
}
}
public void testRetryInterceptor() {
RetryInterceptor retryInterceptor = new RetryInterceptor();
retryInterceptor.setNext(new CommandInvoker());
try {
retryInterceptor.execute(new CommandConfig(), new CommandThrowingOptimisticLockingException());
fail("ActivitiException expected.");
} catch (ActivitiException e) {
assertTrue(e.getMessage().contains(retryInterceptor.getNumOfRetries()+" retries failed"));
}
}
}
| roberthafner/flowable-engine | modules/flowable5-test/src/test/java/org/activiti5/engine/test/cfg/RetryInterceptorTest.java | Java | apache-2.0 | 1,850 |
package com.alibaba.json.bvt;
import com.alibaba.fastjson.JSON;
import org.junit.Assert;
import junit.framework.TestCase;
public class PublicFieldStringTest extends TestCase {
public static class VO {
public String id;
}
public void test_codec() throws Exception {
VO vo = new VO();
vo.id = "x12345";
String str = JSON.toJSONString(vo);
VO vo1 = JSON.parseObject(str, VO.class);
Assert.assertEquals(vo1.id, vo.id);
}
}
| coraldane/fastjson | src/test/java/com/alibaba/json/bvt/PublicFieldStringTest.java | Java | apache-2.0 | 516 |
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js"></script>
<script type="text/javascript" src="../../../lib/jquery.panzoom.min.js"></script>
<script type="text/javascript" src="../../../lib/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="../../../lib/index.js"></script>
<script type="text/javascript" src="../../../index.js"></script>
<script type="text/javascript" src="../../../lib/scheduler.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
/* this variable can be used by the JS to determine the path to the root document */
var toRoot = '../../../';
</script>
</head>
<body>
<div id="search">
<span id="doc-title"><span id="doc-version"></span></span>
<span class="close-results"><span class="left"><</span> Back</span>
<div id="textfilter">
<span class="input">
<input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
<i class="clear material-icons"></i>
<i id="search-icon" class="material-icons"></i>
</span>
</div>
</div>
<div id="search-results">
<div id="search-progress">
<div id="progress-fill"></div>
</div>
<div id="results-content">
<div id="entity-results"></div>
<div id="member-results"></div>
</div>
</div>
<div id="content-scroll-container" style="-webkit-overflow-scrolling: touch;">
<div id="content-container" style="-webkit-overflow-scrolling: touch;">
<div id="subpackage-spacer">
<div id="packages">
<h1>Packages</h1>
<ul>
<li name="_root_.root" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="_root_"></a><a id="root:_root_"></a>
<span class="permalink">
<a href="index.html#_root_" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="" href="../../../index.html"><span class="name">root</span></a>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="_root_.net" visbl="pub" class="indented1 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="net"></a><a id="net:net"></a>
<span class="permalink">
<a href="index.html#net" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="For a overview, proceed to the starting point for this document => net.liftmodules.fobo" href="../../index.html"><span class="name">net</span></a>
</span>
<p class="shortcomment cmt">For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p><div class="fullcomment"><div class="comment cmt"><p>For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../../index.html" class="extype" name="_root_">root</a></dd></dl></div>
</li><li name="net.liftmodules" visbl="pub" class="indented2 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="liftmodules"></a><a id="liftmodules:liftmodules"></a>
<span class="permalink">
<a href="../net/index.html#liftmodules" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="For a overview, proceed to the starting point for this document => net.liftmodules.fobo" href="../index.html"><span class="name">liftmodules</span></a>
</span>
<p class="shortcomment cmt">For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p><div class="fullcomment"><div class="comment cmt"><p>For a overview, proceed to the starting point for this document => <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a></p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../index.html" class="extype" name="net">net</a></dd></dl></div>
</li><li name="net.liftmodules.fobojq" visbl="pub" class="indented3 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="fobojq"></a><a id="fobojq:fobojq"></a>
<span class="permalink">
<a href="../../net/liftmodules/index.html#fobojq" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">package</span>
</span>
<span class="symbol">
<a title="This FoBo toolkit module provides JQuery API and Resource components to the FoBo / FoBo Module, but can also be used as-is, see below for setup information." href="index.html"><span class="name">fobojq</span></a>
</span>
<p class="shortcomment cmt">This FoBo toolkit module provides JQuery API and Resource components to the
FoBo / FoBo Module, but can also be used as-is, see below for setup information.</p><div class="fullcomment"><div class="comment cmt"><h4>FoBo JQuery Toolkit Module</h4><p>This FoBo toolkit module provides JQuery API and Resource components to the
FoBo / FoBo Module, but can also be used as-is, see below for setup information.</p><p>If you are using this module via the FoBo/FoBo artifact module see also <a href="../fobo/index.html" class="extype" name="net.liftmodules.fobo">net.liftmodules.fobo</a> for setup information.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../index.html" class="extype" name="net.liftmodules">liftmodules</a></dd></dl></div>
</li><li name="net.liftmodules.fobojq.Resource" visbl="pub" class="indented4 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="Resource"></a><a id="Resource:Resource"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/index.html#Resource" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<a title="" href="package$$Resource$.html"><span class="name">Resource</span></a><span class="result"> extends <a href="package$$Resource.html" class="extype" name="net.liftmodules.fobojq.Resource">Resource</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="index.html" class="extype" name="net.liftmodules.fobojq">fobojq</a></dd></dl></div>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery1102$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;10&#8228;2 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery1102$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;10&#8228;2 in your bootstrap liftweb Boot.">JQuery1102</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery1113$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;11&#8228;3 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery1113$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;11&#8228;3 in your bootstrap liftweb Boot.">JQuery1113</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery172$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;7&#8228;2 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery172$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;7&#8228;2 in your bootstrap liftweb Boot.">JQuery172</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery182$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;8&#8228;2 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery182$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;8&#8228;2 in your bootstrap liftweb Boot.">JQuery182</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery191$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;9&#8228;1 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery191$.html" title="Enable usage of FoBo's JQuery resources version 1&#8228;9&#8228;1 in your bootstrap liftweb Boot.">JQuery191</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery211$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;1&#8228;1 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery211$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;1&#8228;1 in your bootstrap liftweb Boot.">JQuery211</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery214$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;1&#8228;4 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery214$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;1&#8228;4 in your bootstrap liftweb Boot.">JQuery214</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery224$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;2&#8228;4 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery224$.html" title="Enable usage of FoBo's JQuery resources version 2&#8228;2&#8228;4 in your bootstrap liftweb Boot.">JQuery224</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery300$.html" title="Enable usage of FoBo's JQuery resources version 3&#8228;0&#8228;0 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery300$.html" title="Enable usage of FoBo's JQuery resources version 3&#8228;0&#8228;0 in your bootstrap liftweb Boot.">JQuery300</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQuery310$.html" title="Enable usage of FoBo's JQuery resources version 3&#8228;1&#8228;0 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQuery310$.html" title="Enable usage of FoBo's JQuery resources version 3&#8228;1&#8228;0 in your bootstrap liftweb Boot.">JQuery310</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="" title="Enable usage of FoBo's JQuery-Migrate resources version 1&#8228;2&#8228;1 in your bootstrap liftweb Boot."></a>
<a href="" title="Enable usage of FoBo's JQuery-Migrate resources version 1&#8228;2&#8228;1 in your bootstrap liftweb Boot.">JQueryMigrate121</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQueryMigrate141$.html" title="Enable usage of FoBo's JQuery-Migrate resources version 1&#8228;4&#8228;1 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQueryMigrate141$.html" title="Enable usage of FoBo's JQuery-Migrate resources version 1&#8228;4&#8228;1 in your bootstrap liftweb Boot.">JQueryMigrate141</a>
</li><li class="current-entities indented4">
<span class="separator"></span>
<a class="object" href="package$$Resource$$JQueryMigrate300$.html" title="Enable usage of FoBo's JQuery-Migrate resources version 3&#8228;0&#8228;0 in your bootstrap liftweb Boot."></a>
<a href="package$$Resource$$JQueryMigrate300$.html" title="Enable usage of FoBo's JQuery-Migrate resources version 3&#8228;0&#8228;0 in your bootstrap liftweb Boot.">JQueryMigrate300</a>
</li>
</ul>
</div>
</div>
<div id="content">
<body class="object value">
<div id="definition">
<div class="big-circle object">o</div>
<p id="owner"><a href="../../index.html" class="extype" name="net">net</a>.<a href="../index.html" class="extype" name="net.liftmodules">liftmodules</a>.<a href="index.html" class="extype" name="net.liftmodules.fobojq">fobojq</a>.<a href="package$$Resource$.html" class="extype" name="net.liftmodules.fobojq.Resource">Resource</a></p>
<h1>JQueryMigrate121<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html" title="Permalink">
<i class="material-icons"></i>
</a>
</span></h1>
<h3><span class="morelinks"></span></h3>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">JQueryMigrate121</span><span class="result"> extends <a href="package$$Resource.html" class="extype" name="net.liftmodules.fobojq.Resource">Resource</a> with <a href="http://www.scala-lang.org/api/2.12.6/scala/Product.html#scala.Product" class="extype" name="scala.Product">Product</a> with <a href="http://www.scala-lang.org/api/2.12.6/scala/Serializable.html#scala.Serializable" class="extype" name="scala.Serializable">Serializable</a></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Enable usage of FoBo's JQuery-Migrate resources version 1․2․1 in your bootstrap liftweb Boot.</p></div><dl class="attributes block"> <div class="block">Example:
<ol><li class="cmt"><p></p><pre><span class="kw">import</span> net.liftmodules.{fobojq <span class="kw">=></span> fobo}
:
fobo.Resource.init=fobo.Resource.JQueryMigrate121</pre></li></ol>
</div><dt>Version</dt><dd><p>1.2.1</p></dd></dl><div class="toggleContainer block">
<span class="toggle">
Linear Supertypes
</span>
<div class="superTypes hiddenContent"><a href="http://www.scala-lang.org/api/2.12.6/scala/Serializable.html#scala.Serializable" class="extype" name="scala.Serializable">Serializable</a>, <span class="extype" name="java.io.Serializable">Serializable</span>, <a href="http://www.scala-lang.org/api/2.12.6/scala/Product.html#scala.Product" class="extype" name="scala.Product">Product</a>, <a href="http://www.scala-lang.org/api/2.12.6/scala/Equals.html#scala.Equals" class="extype" name="scala.Equals">Equals</a>, <a href="package$$Resource.html" class="extype" name="net.liftmodules.fobojq.Resource">Resource</a>, <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a>, <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></div>
</div></div>
<div id="mbrsel">
<div class="toggle"></div>
<div id="memberfilter">
<i class="material-icons arrow"></i>
<span class="input">
<input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />
</span>
<i class="clear material-icons"></i>
</div>
<div id="filterby">
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By Inheritance</span></li>
</ol>
</div>
<div class="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="net.liftmodules.fobojq.Resource.JQueryMigrate121"><span>JQueryMigrate121</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="net.liftmodules.fobojq.Resource"><span>Resource</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div class="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show All</span></li>
</ol>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
</div>
<div id="template">
<div id="allMembers">
<div class="values members">
<h3>Value Members</h3>
<ol>
<li name="scala.AnyRef#!=" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a><a id="!=(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#!=(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html###():Int" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Int.html#scala.Int" class="extype" name="scala.Int">Int</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a><a id="==(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#==(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#asInstanceOf[T0]:T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a><a id="clone():AnyRef"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#clone():Object" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a><a id="eq(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#eq(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a><a id="equals(Any):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#equals(x$1:Any):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#finalize():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java/lang/index.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#getClass():Class[_]" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#isInstanceOf[T0]:Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a><a id="ne(AnyRef):Boolean"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#ne(x$1:AnyRef):Boolean" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Boolean.html#scala.Boolean" class="extype" name="scala.Boolean">Boolean</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#notify():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#notifyAll():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a><a id="synchronized[T0](⇒T0):T0"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#synchronized[T0](x$1:=>T0):T0" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#wait():Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a><a id="wait(Long,Int):Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#wait(x$1:Long,x$2:Int):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Long.html#scala.Long" class="extype" name="scala.Long">Long</a></span>, <span name="arg1">arg1: <a href="http://www.scala-lang.org/api/2.12.6/scala/Int.html#scala.Int" class="extype" name="scala.Int">Int</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" class="indented0 " data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a><a id="wait(Long):Unit"></a>
<span class="permalink">
<a href="../../../net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html#wait(x$1:Long):Unit" title="Permalink">
<i class="material-icons"></i>
</a>
</span>
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <a href="http://www.scala-lang.org/api/2.12.6/scala/Long.html#scala.Long" class="extype" name="scala.Long">Long</a></span>)</span><span class="result">: <a href="http://www.scala-lang.org/api/2.12.6/scala/Unit.html#scala.Unit" class="extype" name="scala.Unit">Unit</a></span>
</span>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@native</span><span class="args">()</span>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li>
</ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Serializable">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/Serializable.html#scala.Serializable" class="extype" name="scala.Serializable">Serializable</a></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.Product">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/Product.html#scala.Product" class="extype" name="scala.Product">Product</a></h3>
</div><div class="parent" name="scala.Equals">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/Equals.html#scala.Equals" class="extype" name="scala.Equals">Equals</a></h3>
</div><div class="parent" name="net.liftmodules.fobojq.Resource">
<h3>Inherited from <a href="package$$Resource.html" class="extype" name="net.liftmodules.fobojq.Resource">Resource</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/AnyRef.html#scala.AnyRef" class="extype" name="scala.AnyRef">AnyRef</a></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <a href="http://www.scala-lang.org/api/2.12.6/scala/Any.html#scala.Any" class="extype" name="scala.Any">Any</a></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</div>
</div>
</div>
</body>
</html>
| karma4u101/FoBo-Demo | fobo-lift-template-demo/src/main/webapp/foboapi/older/v2.1/net/liftmodules/fobojq/package$$Resource$$JQueryMigrate121$.html | HTML | apache-2.0 | 41,547 |
#!/usr/bin/env bash
set -e
name=$1
path=$2
build_dir=$3
docs_dir=$build_dir/docs
html_dir=$build_dir/html_docs
# Checks if docs clone already exists
if [ ! -d $docs_dir ]; then
# Only head is cloned
git clone --depth=1 https://github.com/elastic/docs.git $docs_dir
else
echo "$docs_dir already exists. Not cloning."
fi
index_list="$(find ${GOPATH%%:*}/src/$path -name 'index.asciidoc')"
for index in $index_list
do
echo "Building docs for ${name}..."
echo "Index document: ${index}"
index_path=$(basename $(dirname $index))
echo "Index path: $index_path"
dest_dir="$html_dir/${name}/${index_path}"
mkdir -p "$dest_dir"
params="--chunk=1"
if [ "$PREVIEW" = "1" ]; then
params="--chunk=1 -open chunk=1 -open"
fi
$docs_dir/build_docs.pl $params --doc "$index" -out "$dest_dir"
done
| roncohen/apm-server | _beats/script/build_docs.sh | Shell | apache-2.0 | 821 |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using Google.Protobuf;
using Orleans.Serialization;
namespace Example
{
public class ProtobufSerializer : IExternalSerializer
{
static readonly ConcurrentDictionary<RuntimeTypeHandle, MessageParser> Parsers = new ConcurrentDictionary<RuntimeTypeHandle, MessageParser>();
public bool IsSupportedType(Type itemType)
{
if (!typeof(IMessage).IsAssignableFrom(itemType))
return false;
if (Parsers.ContainsKey(itemType.TypeHandle))
return true;
var prop = itemType.GetProperty("Parser", BindingFlags.Public | BindingFlags.Static);
if (prop == null)
return false;
var parser = prop.GetValue(null, null);
Parsers.TryAdd(itemType.TypeHandle, parser as MessageParser);
return true;
}
public object DeepCopy(object source, ICopyContext context)
{
if (source == null)
return null;
dynamic dynamicSource = source;
return dynamicSource.Clone();
}
public void Serialize(object item, ISerializationContext context, Type expectedType)
{
var writer = context.StreamWriter;
if (item == null)
{
// Special handling for null value.
// Since in this ProtobufSerializer we are usually writing the data lengh as 4 bytes
// we also have to write the Null object as 4 bytes lengh of zero.
writer.Write(0);
return;
}
if (!(item is IMessage iMessage))
throw new ArgumentException("The provided item for serialization in not an instance of " + typeof(IMessage), nameof(item));
var outBytes = iMessage.ToByteArray();
writer.Write(outBytes.Length);
writer.Write(outBytes);
}
public object Deserialize(Type expectedType, IDeserializationContext context)
{
var typeHandle = expectedType.TypeHandle;
if (!Parsers.TryGetValue(typeHandle, out var parser))
throw new ArgumentException("No parser found for the expected type " + expectedType, nameof(expectedType));
var reader = context.StreamReader;
var length = reader.ReadInt();
var data = reader.ReadBytes(length);
return parser.ParseFrom(data);
}
}
} | mhertis/Orleankka | Samples/CSharp/Serialization/ProtoBuf/ProtobufSerializer.cs | C# | apache-2.0 | 2,545 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include "absl/strings/str_cat.h"
#include "cyber/common/macros.h"
#include "cyber/time/time.h"
#if defined(__GNUC__) || defined(__GNUG__)
#define AFUNC __PRETTY_FUNCTION__
#elif defined(__clang__)
#define AFUNC __PRETTY_FUNCTION__
#else
#define AFUNC __func__
#endif
// How to Use:
// 1) Use PERF_FUNCTION to compute time cost of function execution as follows:
// void MyFunc() {
// PERF_FUNCION();
// // do somethings.
// }
// Console log:
// >>>>>>>>>>>>>>>>>>
// I0615 15:49:30.756429 12748 timer.cpp:31] TIMER MyFunc elapsed time: 100 ms
// >>>>>>>>>>>>>>>>>>
//
// 2) Use PERF_BLOCK_START/END to compute time cost of block execution.
// void MyFunc() {
// // xxx1
// PERF_BLOCK_START();
//
// // do xx2
//
// PERF_BLOCK_END("xx2");
//
// // do xx3
//
// PERF_BLOCK_END("xx3");
// }
//
// Console log:
// >>>>>>>>>>>>>>>
// I0615 15:49:30.756429 12748 timer.cpp:31] TIMER xx2 elapsed time: 100 ms
// I0615 15:49:30.756429 12748 timer.cpp:31] TIMER xx3 elapsed time: 200 ms
// >>>>>>>>>>>>>>>
namespace apollo {
namespace common {
namespace util {
std::string function_signature(const std::string& func_name,
const std::string& indicator = "");
class Timer {
public:
Timer() = default;
// no-thread safe.
void Start();
// return the elapsed time,
// also output msg and time in glog.
// automatically start a new timer.
// no-thread safe.
int64_t End(const std::string& msg);
private:
apollo::cyber::Time start_time_;
apollo::cyber::Time end_time_;
DISALLOW_COPY_AND_ASSIGN(Timer);
};
class TimerWrapper {
public:
explicit TimerWrapper(const std::string& msg) : msg_(msg) { timer_.Start(); }
~TimerWrapper() { timer_.End(msg_); }
private:
Timer timer_;
std::string msg_;
DISALLOW_COPY_AND_ASSIGN(TimerWrapper);
};
} // namespace util
} // namespace common
} // namespace apollo
#if defined(ENABLE_PERF)
#define PERF_FUNCTION() \
apollo::common::util::TimerWrapper _timer_wrapper_( \
apollo::common::util::function_signature(AFUNC))
#define PERF_FUNCTION_WITH_NAME(func_name) \
apollo::common::util::TimerWrapper _timer_wrapper_(func_name)
#define PERF_FUNCTION_WITH_INDICATOR(indicator) \
apollo::common::util::TimerWrapper _timer_wrapper_( \
apollo::common::util::function_signature(AFUNC, indicator))
#define PERF_BLOCK_START() \
apollo::common::util::Timer _timer_; \
_timer_.Start()
#define PERF_BLOCK_END(msg) _timer_.End(msg)
#define PERF_BLOCK_END_WITH_INDICATOR(indicator, msg) \
_timer_.End(absl::StrCat(indicator, "_", msg))
#else
#define PERF_FUNCTION()
#define PERF_FUNCTION_WITH_NAME(func_name) UNUSED(func_name);
#define PERF_FUNCTION_WITH_INDICATOR(indicator) UNUSED(indicator);
#define PERF_BLOCK_START()
#define PERF_BLOCK_END(msg) UNUSED(msg);
#define PERF_BLOCK_END_WITH_INDICATOR(indicator, msg) \
{ \
UNUSED(indicator); \
UNUSED(msg); \
}
#endif // ENABLE_PERF
| xiaoxq/apollo | modules/common/util/perf_util.h | C | apache-2.0 | 3,983 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
#ifndef TENSORFLOW_GRAPPLER_OP_TYPES_H_
#define TENSORFLOW_GRAPPLER_OP_TYPES_H_
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
namespace grappler {
bool IsAdd(const NodeDef& node);
bool IsAddN(const NodeDef& node);
bool IsAvgPoolGrad(const NodeDef& node);
bool IsAssert(const NodeDef& node);
bool IsBiasAddGrad(const NodeDef& node);
bool IsConcatOffset(const NodeDef& node);
bool IsConstant(const NodeDef& node);
bool IsConv2D(const NodeDef& node);
bool IsConv2DBackpropFilter(const NodeDef& node);
bool IsConv2DBackpropInput(const NodeDef& node);
bool IsDepthwiseConv2dNative(const NodeDef& node);
bool IsDepthwiseConv2dNativeBackpropFilter(const NodeDef& node);
bool IsDepthwiseConv2dNativeBackpropInput(const NodeDef& node);
bool IsDequeueOp(const NodeDef& node);
bool IsEnter(const NodeDef& node);
bool IsExit(const NodeDef& node);
bool IsFloorMod(const NodeDef& node);
bool IsFusedBatchNormGradV1(const NodeDef& node);
bool IsIdentity(const NodeDef& node);
bool IsMerge(const NodeDef& node);
bool IsMul(const NodeDef& node);
bool IsNextIteration(const NodeDef& node);
bool IsPad(const NodeDef& node);
bool IsNoOp(const NodeDef& node);
bool IsPlaceholder(const NodeDef& node);
bool IsRealDiv(const NodeDef& node);
bool IsReluGrad(const NodeDef& node);
bool IsRecv(const NodeDef& node);
bool IsReduction(const NodeDef& node);
bool IsReshape(const NodeDef& node);
bool IsRestore(const NodeDef& node);
bool IsSend(const NodeDef& node);
bool IsSlice(const NodeDef& node);
bool IsSquaredDifference(const NodeDef& node);
bool IsSqueeze(const NodeDef& node);
bool IsStopGradient(const NodeDef& node);
bool IsSub(const NodeDef& node);
bool IsSum(const NodeDef& node);
bool IsSwitch(const NodeDef& node);
bool IsTranspose(const NodeDef& node);
bool IsVariable(const NodeDef& node);
// Return true if the op is an aggregation (e.g. Add, AddN).
// Returns false if it could not be determined to be so.
bool IsAggregate(const NodeDef& node);
// Return true if the op is commutative (e.g. Mul, Add).
// Returns false if it could not be determined to be so.
bool IsCommutative(const NodeDef& node);
bool IsFreeOfSideEffect(const NodeDef& node);
bool ModifiesFrameInfo(const NodeDef& node);
// Returns true if the op is an element-wise involution, i.e. if it is its
// own inverse such that f(f(x)) == x.
bool IsInvolution(const NodeDef& node);
// Returns true if the op in node only rearranges the order of elements in its
// first input tensor and possible changes its shape. More precisely, this
// function returns true if the op commutes with all element-wise operations.
bool IsValuePreserving(const NodeDef& node);
} // end namespace grappler
} // end namespace tensorflow
#endif // TENSORFLOW_GRAPPLER_OP_TYPES_H_
| laszlocsomor/tensorflow | tensorflow/core/grappler/op_types.h | C | apache-2.0 | 3,466 |
/*
* Copyright 2002-2020 the original author or authors.
*
* 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
*
* https://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 org.springframework.security.oauth2.client.userinfo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DefaultOAuth2UserService}.
*
* @author Joe Grandja
* @author Eddú Meléndez
*/
public class DefaultOAuth2UserServiceTests {
private ClientRegistration.Builder clientRegistrationBuilder;
private OAuth2AccessToken accessToken;
private DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
// @formatter:off
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration()
.userInfoUri(null)
.userNameAttributeName(null);
// @formatter:on
this.accessToken = TestOAuth2AccessTokens.noScopes();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRestOperations(null));
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() {
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_info_uri");
}
@Test
public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() {
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.userInfoUri("https://provider.com/user")
.build();
// @formatter:on
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_name_attribute");
}
@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"[email protected]\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes().size()).isEqualTo(6);
assertThat((String) user.getAttribute("user-name")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("[email protected]");
assertThat(user.getAuthorities().size()).isEqualTo(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("ROLE_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"[email protected]\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenUserInfoErrorResponseWwwAuthenticateHeaderThenThrowOAuth2AuthenticationException() {
String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
response.setResponseCode(400);
this.server.enqueue(response);
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: insufficient_scope, Error Description: The access token expired");
}
@Test
public void loadUserWhenUserInfoErrorResponseThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoErrorResponse = "{\n"
+ " \"error\": \"invalid_token\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoErrorResponse).setResponseCode(400));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: invalid_token");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
// gh-5294
@Test
public void loadUserWhenUserInfoSuccessResponseThenAcceptHeaderJson() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"[email protected]\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(this.server.takeRequest(1, TimeUnit.SECONDS).getHeader(HttpHeaders.ACCEPT))
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"[email protected]\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.GET.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodFormSuccessResponseThenHttpMethodPost() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"[email protected]\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
assertThat(request.getBody().readUtf8()).isEqualTo("access_token=" + this.accessToken.getTokenValue());
}
@Test
public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.scopes("message:read", "message:write"));
OAuth2User user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(3);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:read"));
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:write"));
}
@Test
public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.noScopes());
OAuth2User user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(1);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
}
// gh-8764
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2AuthenticationException() {
String userInfoUri = this.server.url("/user").toString();
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
response.setBody("invalid content type");
this.server.enqueue(response);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource "
+ "from '" + userInfoUri + "': response contains invalid content type 'text/plain'.");
}
private DefaultOAuth2UserService withMockResponse(Map<String, Object> response) {
ResponseEntity<Map<String, Object>> responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = mock(Converter.class);
RestOperations rest = mock(RestOperations.class);
given(rest.exchange(nullable(RequestEntity.class), any(ParameterizedTypeReference.class)))
.willReturn(responseEntity);
DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
userService.setRequestEntityConverter(requestEntityConverter);
userService.setRestOperations(rest);
return userService;
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| djechelon/spring-security | oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java | Java | apache-2.0 | 18,151 |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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 org.keycloak.testsuite.adapter.example.hal;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.Page;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.adapter.AbstractAdapterTest;
import org.keycloak.testsuite.arquillian.AppServerTestEnricher;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.arquillian.annotation.AppServerContainer;
import org.keycloak.testsuite.utils.arquillian.ContainerConstants;
import org.keycloak.testsuite.pages.AccountUpdateProfilePage;
import org.keycloak.testsuite.pages.AppServerWelcomePage;
import org.keycloak.testsuite.util.DroneUtils;
import org.keycloak.testsuite.util.JavascriptBrowser;
import org.keycloak.testsuite.util.WaitUtils;
import org.openqa.selenium.WebDriver;
import org.wildfly.extras.creaper.core.online.CliException;
import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
import org.wildfly.extras.creaper.core.online.operations.Address;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Operations;
import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
/**
*
* @author <a href="mailto:[email protected]">Pedro Igor</a>
*/
@AppServerContainer(ContainerConstants.APP_SERVER_EAP71)
public class ConsoleProtectionTest extends AbstractAdapterTest {
// Javascript browser needed KEYCLOAK-4703
@Drone
@JavascriptBrowser
protected WebDriver jsDriver;
@Page
@JavascriptBrowser
protected AppServerWelcomePage appServerWelcomePage;
@Page
@JavascriptBrowser
protected AccountUpdateProfilePage accountUpdateProfilePage;
@Override
public void addAdapterTestRealms(List<RealmRepresentation> testRealms) {
testRealms.add(loadRealm("/wildfly-integration/wildfly-management-realm.json"));
}
@Before
public void beforeConsoleProtectionTest() throws IOException, OperationException {
Assume.assumeTrue("This testClass doesn't work with phantomjs", !"phantomjs".equals(System.getProperty("js.browser")));
try (OnlineManagementClient clientWorkerNodeClient = AppServerTestEnricher.getManagementClient()) {
Operations operations = new Operations(clientWorkerNodeClient);
Assume.assumeTrue(operations.exists(Address.subsystem("elytron").and("security-domain", "KeycloakDomain")));
// Create a realm for both wildfly console and mgmt interface
clientWorkerNodeClient.execute("/subsystem=keycloak/realm=jboss-infra:add(auth-server-url=" + AuthServerTestEnricher.getAuthServerContextRoot() + "/auth,realm-public-key=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB)");
// Create a secure-deployment in order to protect mgmt interface
clientWorkerNodeClient.execute("/subsystem=keycloak/secure-deployment=wildfly-management:add(realm=jboss-infra,resource=wildfly-management,principal-attribute=preferred_username,bearer-only=true,ssl-required=EXTERNAL)");
// Protect HTTP mgmt interface with Keycloak adapter
clientWorkerNodeClient.execute("/core-service=management/management-interface=http-interface:undefine-attribute(name=security-realm)");
clientWorkerNodeClient.execute("/subsystem=elytron/http-authentication-factory=keycloak-mgmt-http-authentication:add(security-domain=KeycloakDomain,http-server-mechanism-factory=wildfly-management,mechanism-configurations=[{mechanism-name=KEYCLOAK,mechanism-realm-configurations=[{realm-name=KeycloakOIDCRealm,realm-mapper=keycloak-oidc-realm-mapper}]}])");
clientWorkerNodeClient.execute("/core-service=management/management-interface=http-interface:write-attribute(name=http-authentication-factory,value=keycloak-mgmt-http-authentication)");
clientWorkerNodeClient.execute("/core-service=management/management-interface=http-interface:write-attribute(name=http-upgrade, value={enabled=true, sasl-authentication-factory=management-sasl-authentication})");
// Enable RBAC where roles are obtained from the identity
clientWorkerNodeClient.execute("/core-service=management/access=authorization:write-attribute(name=provider,value=rbac)");
clientWorkerNodeClient.execute("/core-service=management/access=authorization:write-attribute(name=use-identity-roles,value=true)");
// Create a secure-server in order to publish the wildfly console configuration via mgmt interface
clientWorkerNodeClient.execute("/subsystem=keycloak/secure-server=wildfly-console:add(realm=jboss-infra,resource=wildfly-console,public-client=true)");
log.debug("Reloading the server");
new Administration(clientWorkerNodeClient).reload();
log.debug("Reloaded");
} catch (CliException | IOException | InterruptedException | TimeoutException cause) {
throw new RuntimeException("Failed to configure app server", cause);
}
DroneUtils.addWebDriver(jsDriver);
log.debug("Added jsDriver");
}
private void testLogin() throws InterruptedException {
appServerWelcomePage.navigateToConsole();
appServerWelcomePage.login("admin", "admin");
WaitUtils.pause(2000);
assertTrue(appServerWelcomePage.isCurrent());
}
@Test
public void testUserCanAccessAccountService() throws InterruptedException {
testLogin();
appServerWelcomePage.navigateToAccessControl();
appServerWelcomePage.navigateManageProfile();
assertTrue(accountUpdateProfilePage.isCurrent());
}
}
| brat000012001/keycloak | testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/adapter/example/hal/ConsoleProtectionTest.java | Java | apache-2.0 | 6,836 |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-08-29 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/es5-shim/es5-shim.js',
'bower_components/angular/angular.js',
'bower_components/json3/lib/json3.js',
'bower_components/bootstrap/dist/js/bootstrap.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-websocket/angular-websocket.min.js',
'bower_components/ace-builds/src-noconflict/ace.js',
'bower_components/ace-builds/src-noconflict/mode-scala.js',
'bower_components/ace-builds/src-noconflict/mode-sql.js',
'bower_components/ace-builds/src-noconflict/mode-markdown.js',
'bower_components/ace-builds/src-noconflict/keybinding-emacs.js',
'bower_components/ace-builds/src-noconflict/ext-language_tools.js',
'bower_components/ace-builds/src-noconflict/theme-github.js',
'bower_components/angular-ui-ace/ui-ace.js',
'bower_components/jquery.scrollTo/jquery.scrollTo.js',
'bower_components/d3/d3.js',
'bower_components/nvd3/nv.d3.js',
'bower_components/jquery-ui/jquery-ui.js',
'bower_components/angular-dragdrop/src/angular-dragdrop.js',
'bower_components/perfect-scrollbar/src/perfect-scrollbar.js',
'bower_components/ng-sortable/dist/ng-sortable.js',
'bower_components/angular-elastic/elastic.js',
'bower_components/angular-elastic-input/dist/angular-elastic-input.min.js',
'bower_components/angular-xeditable/dist/js/xeditable.js',
'bower_components/highlightjs/highlight.pack.js',
'bower_components/lodash/lodash.js',
'bower_components/angular-filter/dist/angular-filter.min.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
'src/app/app.js',
'src/app/app.controller.js',
'src/app/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| DataScienceX/incubator-zeppelin | zeppelin-web/test/karma.conf.js | JavaScript | apache-2.0 | 3,685 |
// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
//
// Ice version 3.6.0
//
// <auto-generated>
//
// Generated from file `order.ice'
//
// Warning: do not edit this file.
//
// </auto-generated>
//
package io.mycat.ep.v1.order;
public final class CartOrderInfoHolder extends Ice.Holder<CartOrderInfo>
{
public
CartOrderInfoHolder()
{
}
public
CartOrderInfoHolder(CartOrderInfo value)
{
super(value);
}
}
| MyCATApache/Mycat-openEP | mycat-ep-server2/mycat-ep-order/src/main/java/io/mycat/ep/v1/order/CartOrderInfoHolder.java | Java | apache-2.0 | 739 |
// <copyright file="ElementCoordinates.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you 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.
// </copyright>
using System;
using System.Collections.Generic;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Defines the interface through which the user can discover where an element is on the screen.
/// </summary>
internal class ElementCoordinates : ICoordinates
{
private WebElement element;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteCoordinates"/> class.
/// </summary>
/// <param name="element">The <see cref="WebElement"/> to be located.</param>
public ElementCoordinates(WebElement element)
{
this.element = element;
}
/// <summary>
/// Gets the location of an element in absolute screen coordinates.
/// </summary>
public System.Drawing.Point LocationOnScreen
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Gets the location of an element relative to the origin of the view port.
/// </summary>
public System.Drawing.Point LocationInViewport
{
get { return this.element.LocationOnScreenOnceScrolledIntoView; }
}
/// <summary>
/// Gets the location of an element's position within the HTML DOM.
/// </summary>
public System.Drawing.Point LocationInDom
{
get { return this.element.Location; }
}
/// <summary>
/// Gets a locator providing a user-defined location for this element.
/// </summary>
public object AuxiliaryLocator
{
get
{
IWebDriverObjectReference elementReference = this.element as IWebDriverObjectReference;
if (elementReference == null)
{
return null;
}
// Note that the OSS dialect of the wire protocol for the Actions API
// uses the raw ID of the element, not an element reference. To use this,
// extract the ID using the well-known key to the dictionary for element
// references.
return elementReference.ObjectReferenceId;
}
}
}
}
| titusfortner/selenium | dotnet/src/webdriver/ElementCoordinates.cs | C# | apache-2.0 | 3,193 |
// bdlmt_timereventscheduler.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdlmt_timereventscheduler.h>
#include <bslim_testutil.h>
#include <bslma_testallocator.h>
#include <bsls_atomic.h>
#include <bslmt_barrier.h>
#include <bslmt_threadgroup.h>
#include <bdlf_bind.h>
#include <bdlf_placeholder.h>
#include <bdlf_memfn.h>
#include <bdlb_bitutil.h>
#include <bsl_climits.h> // for 'CHAR_BIT'
#include <bdlt_datetime.h>
#include <bdlt_currenttime.h>
#include <bsls_platform.h>
#include <bsls_stopwatch.h>
#include <bsls_systemtime.h>
#include <bsls_types.h>
#include <bsl_algorithm.h>
#include <bsl_cmath.h>
#include <bsl_cstddef.h>
#include <bsl_cstdlib.h>
#include <bsl_functional.h>
#include <bsl_iostream.h>
#include <bsl_list.h>
#include <bsl_ostream.h>
using namespace BloombergLP;
using bsl::cout;
using bsl::cerr;
using bsl::endl;
using bsl::flush;
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// Testing 'bdlmt::TimerEventScheduler' is divided into 2 parts (apart from
// breathing test and usage example). The first part tests the functions in
// isolation, the second is more integrated in that it tests a particular
// situation in context, with a combination of functions.
//
// [2] Verify that callbacks are invoked as expected when multiple clocks and
// multiple events are scheduled.
//
// [3] Verify that 'cancelEvent' works correctly in various white box states.
//
// [4] Verify that 'cancelAllEvents' works correctly in various white box
// states.
//
// [5] Verify that 'cancelClock' works correctly in various white box states.
//
// [6] Verify that 'cancelAllClocks' works correctly in various white box
// states.
//
// [7] Test 'scheduleEvent', 'cancelEvent', 'cancelAllEvents',
// 'startClock', 'cancelClock' and 'cancelAllClocks' when they are invoked from
// dispatcher thread.
//
// [8] Test the scheduler with a user-defined dispatcher.
//
// [9] Verify that 'start' and 'stop' work correctly in various white box
// states.
//
// [10] Verify the concurrent scheduling and cancelling of clocks and events.
//
// [11] Verify the concurrent scheduling and cancelling-all of clocks and
// events.
//
// [14] Given 'numEvents' and 'numClocks' (where 'numEvents <= 2**24 - 1' and
// 'numClocks <= 2**24 - 1'), ensure that *at least* 'numEvents' and
// 'numClocks' may be concurrently scheduled.
// ----------------------------------------------------------------------------
// CREATORS
// [01] bdlmt::TimerEventScheduler(allocator = 0);
// [19] bdlmt::TimerEventScheduler(clockType, allocator = 0);
//
// [08] bdlmt::TimerEventScheduler(dispatcher, allocator = 0);
// [20] bdlmt::TimerEventScheduler(disp, clockType, alloc = 0);
//
// [21] bdlmt::TimerEventScheduler(nE, nC, bA = 0);
// [22] bdlmt::TimerEventScheduler(nE, nC, cT, bA = 0);
//
// [23] bdlmt::TimerEventScheduler(nE, nC, disp, bA = 0);
// [24] bdlmt::TimerEventScheduler(nE, nC, disp, cT, bA = 0);
//
//
// [01] ~bdlmt::TimerEventScheduler();
//
// MANIPULATORS
// [09] int start();
//
// [16] int start(const bslmt::ThreadAttributes& threadAttributes);
//
// [09] void stop();
//
// [02] Handle scheduleEvent(time, callback);
//
// [12] int rescheduleEvent(handle, newTime);
//
// [12] int rescheduleEvent(handle, key, newTime);
//
// [03] int cancelEvent(Handle handle, bool wait=false);
//
// [04] void cancelAllEvents(bool wait=false);
// [17] void cancelAllEvents(bool wait=false);
//
// [02] Handle startClock(interval, callback, startTime=bsls::TimeInterval(0));
//
// [05] int cancelClock(Handle handle, bool wait=false);
//
// [06] void cancelAllClocks(bool wait=false);
//
// ACCESSORS
// ----------------------------------------------------------------------------
// [01] BREATHING TEST
// [07] TESTING METHODS INVOCATIONS FROM THE DISPATCHER THREAD
// [10] TESTING CONCURRENT SCHEDULING AND CANCELLING
// [11] TESTING CONCURRENT SCHEDULING AND CANCELLING-ALL
// [25] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
#define E(X) cout << (X) << endl; // Print value.
#define E_(X) cout << (X) << flush; // Print value.
// ============================================================================
// THREAD-SAFE OUTPUT AND ASSERT MACROS
// ----------------------------------------------------------------------------
static bslmt::Mutex printMutex; // mutex to protect output macros
#define ET(X) { printMutex.lock(); E(X); printMutex.unlock(); }
#define ET_(X) { printMutex.lock(); E_(X); printMutex.unlock(); }
#define PT(X) { printMutex.lock(); P(X); printMutex.unlock(); }
#define PT_(X) { printMutex.lock(); P_(X); printMutex.unlock(); }
static bslmt::Mutex &assertMutex = printMutex;// mutex to protect assert macros
#define ASSERTT(X) { assertMutex.lock(); aSsErT(!(X), #X, __LINE__); \
assertMutex.unlock();}
#define LOOP_ASSERTT(I,X) { \
if (!(X)) { assertMutex.lock(); cout << #I << ": " << I << endl; \
aSsErT(1, #X, __LINE__); assertMutex.unlock(); } }
#define LOOP2_ASSERTT(I,J,X) { \
if (!(X)) { assertMutex.lock(); cout << #I << ": " << I << "\t" \
<< #J << ": " << J << endl; aSsErT(1, #X, __LINE__); \
assertMutex.unlock(); } }
#define LOOP3_ASSERTT(I,J,K,X) { \
if (!(X)) { assertMutex.lock(); cout << #I << ": " << I << "\t" \
<< #J << ": " << J << "\t" << #K << ": " << K << endl; \
aSsErT(1, #X, __LINE__); assertMutex.unlock(); } }
#define LOOP4_ASSERTT(I,J,K,L,X) { \
if (!(X)) { assertMutex.lock(); cout << #I << ": " << I << "\t" \
<< #J << ": " << J << "\t" << #K << ": " << K << "\t" << #L \
<< ": " << L << endl; aSsErT(1, #X, __LINE__); assertMutex.unlock(); } }
#define LOOP5_ASSERTT(I,J,K,L,M,X) { \
if (!(X)) { assertMutex.lock(); cout << #I << ": " << I << "\t" \
<< #J << ": " << J << "\t" << #K << ": " << K << "\t" << #L \
<< ": " << L << "\t" << #M << ": " << M << endl; \
aSsErT(1, #X, __LINE__); assertMutex.unlock(); } }
// ============================================================================
// GLOBAL TYPEDEFS/CONSTANTS/VARIABLES/FUNCTIONS FOR TESTING
// ----------------------------------------------------------------------------
static int verbose;
static int veryVerbose;
static int veryVeryVerbose;
typedef bdlmt::TimerEventScheduler Obj;
typedef Obj::Handle Handle;
void sleepUntilMs(int ms)
{
int sleepIncrement = bsl::min(250, (ms/4)+1);
bsls::Stopwatch timer;
timer.start();
while (timer.elapsedTime() * 1000 < ms) {
bslmt::ThreadUtil::microSleep(sleepIncrement);
}
}
static const float DECI_SEC = 1.0/10; // 1 deci-second (a tenth of a second)
static const int DECI_SEC_IN_MICRO_SEC = 100000;
// number of microseconds in a tenth of a second
// Tolerance for testing correct timing
static const bsls::TimeInterval UNACCEPTABLE_DIFFERENCE(0, 500000000); // 500ms
static const bsls::TimeInterval ALLOWABLE_DIFFERENCE (0, 75000000); // 75ms
static const bsls::TimeInterval APPRECIABLE_DIFFERENCE (0, 20000000); // 20ms
static inline bool isUnacceptable(const bsls::TimeInterval& t1,
const bsls::TimeInterval& t2)
// Return true if the specified 't1' and 't2' are unacceptably not (the
// definition of *unacceptable* is implementation-defined) equal, otherwise
// return false.
{
bsls::TimeInterval absDifference = (t1 > t2) ? (t1 - t2) : (t2 - t1);
return (ALLOWABLE_DIFFERENCE > absDifference)? true : false;
}
static inline bool isApproxEqual(const bsls::TimeInterval& t1,
const bsls::TimeInterval& t2)
// Return true if the specified 't1' and 't2' are approximately (the
// definition of *approximate* is implementation-defined) equal, otherwise
// return false.
{
bsls::TimeInterval absDifference = (t1 > t2) ? (t1 - t2) : (t2 - t1);
return (ALLOWABLE_DIFFERENCE > absDifference)? true : false;
}
static inline bool isApproxGreaterThan(const bsls::TimeInterval& t1,
const bsls::TimeInterval& t2)
// Return true if the specified 't1' is approximately (the definition of
// *approximate* is implementation-defined) greater than the specified
// 't2', otherwise return false.
{
return ((t1 - t2) > APPRECIABLE_DIFFERENCE)? true : false;
}
void myMicroSleep(int microSeconds, int seconds)
// Sleep for *at* *least* the specified 'seconds' and 'microseconds'. This
// function is used for testing only. It uses the function
// 'bslmt::ThreadUtil::microSleep' but interleaves calls to 'yield' to give
// a chance to the event scheduler to process its dispatching thread.
// Without this, there have been a large number of unpredictable
// intermittent failures by this test driver, especially on AIX with
// xlc-8.0, in the nightly builds (i.e., when the load is higher than
// running the test driver by hand). It was noticed that calls to 'yield'
// helped, and this routine centralizes this as a mechanism.
{
sleepUntilMs(microSeconds / 1000 + seconds * 1000);
}
template <class TESTCLASS>
void makeSureTestObjectIsExecuted(TESTCLASS& testObject,
const int microSeconds,
int numAttempts,
int numExecuted = 0)
// Check that the specified 'testObject' has been executed one more time in
// addition to the optionally specified 'numExecuted' times, for the
// specified 'numAttempts' separated by the specified 'microSeconds', and
// return as soon as that is true or when the 'numAttempts' all fail.
{
for (int i = 0; i < numAttempts; ++i) {
if (numExecuted + 1 <= testObject.numExecuted()) {
return; // RETURN
}
sleepUntilMs(microSeconds / 1000);
bslmt::ThreadUtil::yield();
}
}
static inline double dnow()
{
// current time as a double
return bdlt::CurrentTime::now().totalSecondsAsDouble();
}
// ==========================
// function executeInParallel
// ==========================
static void executeInParallel(int numThreads,
bslmt::ThreadUtil::ThreadFunction func)
// Create the specified 'numThreads', each executing the specified 'func'.
// Number each thread (sequentially from 0 to 'numThreads-1') by passing i
// to i'th thread. Finally join all the threads.
{
bslmt::ThreadUtil::Handle *threads =
new bslmt::ThreadUtil::Handle[numThreads];
ASSERT(threads);
for (int i = 0; i < numThreads; ++i) {
bslmt::ThreadUtil::create(&threads[i], func, (void*)i);
}
for (int i = 0; i < numThreads; ++i) {
bslmt::ThreadUtil::join(threads[i]);
}
delete [] threads;
}
// ===============
// class TestClass
// ===============
class TestClass {
// This class encapsulates the data associated with a clock or an event.
bool d_isClock; // true if this is a clock,
// false when this is an
// event
bsls::TimeInterval d_periodicInterval; // periodic interval if this
// is a recurring event
bsls::TimeInterval d_expectedTimeAtExecution; // expected time at which
// callback should run
bsls::AtomicInt d_numExecuted; // number of times callback
// has been executed
bsls::AtomicInt d_executionTime; // duration for which
// callback executes
int d_line; // for error reporting
bsls::AtomicInt d_delayed; // will be set to true if
// any execution of the
// callback is delayed from
// its expected execution
// time
bsls::TimeInterval d_referenceTime; // time from which execution
// time is referenced for
// debugging purpose
bsls::TimeInterval *d_globalLastExecutionTime; // last time *ANY* callback
// was executed
bool d_assertOnFailure; // case 2 must not assert on
// failure unless it fails
// too many times
bsls::AtomicInt d_failures; // timing failures
// FRIENDS
friend bsl::ostream& operator<<(bsl::ostream& os,
const TestClass& testObject);
public:
// CREATORS
TestClass(int line,
bsls::TimeInterval expectedTimeAtExecution,
bsls::TimeInterval *globalLastExecutionTime ,
int executionTime = 0,
bool assertOnFailure = true):
d_isClock(false),
d_periodicInterval(0),
d_expectedTimeAtExecution(expectedTimeAtExecution),
d_numExecuted(0),
d_executionTime(executionTime),
d_line(line),
d_delayed(false),
d_referenceTime(bdlt::CurrentTime::now()),
d_globalLastExecutionTime(globalLastExecutionTime),
d_assertOnFailure(assertOnFailure),
d_failures(0)
{
}
TestClass(int line,
bsls::TimeInterval expectedTimeAtExecution,
bsls::TimeInterval periodicInterval,
bsls::TimeInterval *globalLastExecutionTime,
int executionTime = 0,
bool assertOnFailure = true):
d_isClock(true),
d_periodicInterval(periodicInterval),
d_expectedTimeAtExecution(expectedTimeAtExecution),
d_numExecuted(0),
d_executionTime(executionTime),
d_line(line),
d_delayed(false),
d_referenceTime(bdlt::CurrentTime::now()),
d_globalLastExecutionTime(globalLastExecutionTime),
d_assertOnFailure(assertOnFailure),
d_failures(0)
{
}
TestClass(const TestClass& rhs):
d_isClock(rhs.d_isClock),
d_periodicInterval(rhs.d_periodicInterval),
d_expectedTimeAtExecution(rhs.d_expectedTimeAtExecution),
d_numExecuted(rhs.d_numExecuted.load()),
d_executionTime(rhs.d_executionTime.load()),
d_line(rhs.d_line),
d_delayed(rhs.d_delayed.load()),
d_referenceTime(rhs.d_referenceTime),
d_globalLastExecutionTime(rhs.d_globalLastExecutionTime),
d_assertOnFailure(rhs.d_assertOnFailure),
d_failures(0)
{
}
// MANIPULATORS
void callback()
// This function is the callback associated with this clock or event.
// On execution, it print an error if it has not been executed at
// expected time. It also updates any relevant class data.
{
bsls::TimeInterval now = bdlt::CurrentTime::now();
if (veryVerbose) {
printMutex.lock();
cout << (d_isClock ? "CLOCK" : "EVENT") << " specified at line "
<< d_line << " executed "
<< (now - d_referenceTime).nanoseconds() / 1000000
<< " milliseconds after it was scheduled" << endl;
printMutex.unlock();
}
// if this execution has been delayed due to a long running callback or
// due to high loads during parallel testing
if (d_delayed || isApproxGreaterThan(*d_globalLastExecutionTime,
d_expectedTimeAtExecution)) {
d_delayed = true;
d_expectedTimeAtExecution = now;
}
// assert that it runs on expected time
if (d_assertOnFailure) {
LOOP3_ASSERTT(d_line, now, d_expectedTimeAtExecution,
isApproxEqual(now, d_expectedTimeAtExecution));
}
// in any case, keep track of number of failures
if (!isApproxEqual(now, d_expectedTimeAtExecution)) {
if (isUnacceptable(now, d_expectedTimeAtExecution)) {
d_failures += 100; // large number to trigger overall failure
} else {
++d_failures; // small failure, might still be below threshold
}
}
if (d_executionTime) {
sleepUntilMs(d_executionTime / 1000);
}
now = bdlt::CurrentTime::now();
*d_globalLastExecutionTime = now;
// if this is a clock, update the expected time for the *next*
// execution
if (d_isClock) {
d_expectedTimeAtExecution = now + d_periodicInterval;
}
++d_numExecuted;
}
// ACCESSORS
bool delayed() const
{
return d_delayed;
}
int numExecuted() const
{
return d_numExecuted;
}
int numFailures() const
{
return d_failures;
}
};
// FRIENDS
bsl::ostream& operator << (bsl::ostream& os, const TestClass& testObject)
{
P(testObject.d_line);
P(testObject.d_isClock);
P(testObject.d_periodicInterval);
P(testObject.d_expectedTimeAtExecution);
P(testObject.d_numExecuted);
P(testObject.d_executionTime);
P(testObject.d_delayed);
P(testObject.d_referenceTime);
return os;
}
// ================
// class TestClass1
// ================
struct TestClass1 {
// This class define a function 'callback' that is used as a callback for a
// clock or an event. The class keeps track of number of times the
// callback has been executed.
bsls::AtomicInt d_numStarted;
bsls::AtomicInt d_numExecuted;
int d_executionTime; // in microseconds
// CREATORS
TestClass1() :
d_numStarted(0),
d_numExecuted(0),
d_executionTime(0)
{
}
TestClass1(int executionTime) :
d_numStarted(0),
d_numExecuted(0),
d_executionTime(executionTime)
{
}
// MANIPULATORS
void callback()
{
++d_numStarted;
if (d_executionTime) {
sleepUntilMs(d_executionTime / 1000);
}
++d_numExecuted;
}
// ACCESSORS
int numStarted()
{
return d_numStarted;
}
int numExecuted()
{
return d_numExecuted;
}
};
// ====================
// class TestPrintClass
// ====================
struct TestPrintClass {
// This class define a function 'callback' that prints a message. This
// class is intended for use to verify changes to the system clock do or do
// not affect the behavior of the scheduler (see Test Case -1).
bsls::AtomicInt d_numExecuted;
// CREATORS
TestPrintClass() :
d_numExecuted(0)
{
}
// MANIPULATORS
void callback()
{
++d_numExecuted;
cout << "iteration: " << d_numExecuted << endl;
}
// ACCESSORS
int numExecuted()
{
return d_numExecuted;
}
};
void cancelEventCallback(Obj *scheduler,
int *handlePtr,
int wait,
int expectedStatus)
// Invoke 'cancelEvent' on the specified 'scheduler' passing the specified
// '*handlePtr' and 'wait' and assert that the result equals the specified
// 'expectedStatus'.
{
int ret = scheduler->cancelEvent(*handlePtr, wait);
LOOP_ASSERTT(ret, expectedStatus == ret);
}
void cancelEventCallbackWithState(Obj *scheduler,
int *handlePtr,
const bsl::shared_ptr<int>& state)
// Invoke 'cancelEvent' on the specified 'scheduler' passing '*handlePtr'
// and assert that the specified 'state' remains valid.
{
const int s = *state;
int ret = scheduler->cancelEvent(*handlePtr);
LOOP_ASSERT(ret, s == *state);
}
static void cancelClockCallback(Obj *scheduler,
int *handlePtr,
int wait,
int expectedStatus)
// Invoke 'cancelClocks' on the specified 'scheduler' passing the specified
// '*handlePtr' and 'wait' and assert that the result equals the specified
// 'expectedStatus'.
{
int ret = scheduler->cancelClock(*handlePtr, wait);
LOOP_ASSERT(ret, expectedStatus == ret);
}
static void cancelAllEventsCallback(Obj *scheduler, int wait)
// Invoke 'cancelAllEvents' on the specified 'scheduler' passing 'wait'.
{
scheduler->cancelAllEvents(wait);
}
static void cancelAllClocksCallback(Obj *scheduler, int wait)
// Invoke 'cancelAllClocks' on the specified 'scheduler' passing 'wait'.
{
scheduler->cancelAllClocks(wait);
}
// ============================================================================
// HELPER CLASSES AND FUNCTIONS FOR TESTING
// ============================================================================
// ----------------------------------------------------------------------------
// USAGE EXAMPLE RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_USAGE
{
// ================
// class my_Session
// ================
class my_Session{
public:
// MANIPULATORS
int processData(void *data, int length);
};
// MANIPULATORS
int my_Session::processData(void *data, int length)
{
return 0;
}
// ===============
// class my_Server
// ===============
class my_Server {
// TYPES
struct Connection {
bdlmt::TimerEventScheduler::Handle d_timerId;
my_Session *d_session_p;
};
// DATA
bsl::vector<Connection*> d_connections;
bdlmt::TimerEventScheduler d_scheduler;
bsls::TimeInterval d_ioTimeout;
// PRIVATE MANIPULATORS
void newConnection(Connection *connection);
void closeConnection(Connection *connection);
void dataAvailable(Connection *connection, void *data, int length);
my_Server(const my_Server&); // unimplemented
my_Server& operator=(const my_Server&); // unimplemented
public:
// CREATORS
my_Server(const bsls::TimeInterval& ioTimeout,
bslma::Allocator *allocator = 0);
~my_Server();
};
// CREATORS
my_Server::my_Server(const bsls::TimeInterval& ioTimeout,
bslma::Allocator *allocator)
: d_connections(allocator)
, d_scheduler(allocator)
, d_ioTimeout(ioTimeout)
{
d_scheduler.start();
}
my_Server::~my_Server()
{
d_scheduler.stop();
}
// PRIVATE MANIPULATORS
void my_Server::newConnection(my_Server::Connection *connection)
{
connection->d_timerId = d_scheduler.scheduleEvent(
bdlt::CurrentTime::now() + d_ioTimeout,
bdlf::BindUtil::bind(&my_Server::closeConnection, this, connection));
}
void my_Server::closeConnection(my_Server::Connection *connection)
{
}
void my_Server::dataAvailable(my_Server::Connection *connection,
void *data,
int length)
{
if (d_scheduler.cancelEvent(connection->d_timerId)) {
return; // RETURN
}
connection->d_session_p->processData(data, length);
connection->d_timerId = d_scheduler.scheduleEvent(
bdlt::CurrentTime::now() + d_ioTimeout,
bdlf::BindUtil::bind(&my_Server::closeConnection, this, connection));
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_USAGE
// ============================================================================
// CASE 20 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_24
{
void dispatcherFunction(bsl::function<void()> functor)
// This is a dispatcher function that simply execute the specified
// 'functor'.
{
functor();
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_24
// ============================================================================
// CASE 20 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_23
{
void dispatcherFunction(bsl::function<void()> functor)
// This is a dispatcher function that simply execute the specified
// 'functor'.
{
functor();
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_23
// ============================================================================
// CASE 22 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_22
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_22
// ============================================================================
// CASE 21 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_21
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_21
// ============================================================================
// CASE 20 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_20
{
void dispatcherFunction(bsl::function<void()> functor)
// This is a dispatcher function that simply execute the specified
// 'functor'.
{
functor();
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_20
// ============================================================================
// CASE 19 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_19
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_19
// ============================================================================
// CASE 17 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_18
{
struct Func {
int d_eventIndex;
// each event is marked by a unique index
static Obj* s_scheduler;
static bsl::vector<Obj::Handle> s_handles;
// 's_handles[i]' is the handle of event with index 'i'
static bsl::vector<int> s_indexes;
// each event, when run, pushes its index to this vector
static int s_kamikaze;
// index of the event that is to kill itself
Func(int index) : d_eventIndex(index) {}
void operator()();
};
Obj* Func::s_scheduler;
bsl::vector<Obj::Handle> Func::s_handles;
bsl::vector<int> Func::s_indexes;
int Func::s_kamikaze;
void Func::operator()()
{
s_indexes.push_back(d_eventIndex);
if (s_kamikaze == d_eventIndex) {
ASSERT(0 != s_scheduler->cancelEvent(s_handles[d_eventIndex]));
}
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_18
// ============================================================================
// CASE 17 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_17
{
struct Func {
static const Obj *s_scheduler;
static int s_numEvents;
void operator()()
{
sleepUntilMs(100 * 1000 / 1000);
-- s_numEvents;
int diff = bsl::abs(s_scheduler->numEvents() - s_numEvents);
LOOP3_ASSERT(s_scheduler->numEvents(), s_numEvents, diff, 2 >= diff);
}
};
const Obj *Func::s_scheduler;
int Func::s_numEvents;
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_17
// ============================================================================
// CASE 16 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_16
{
enum { BUFSIZE = 40 * 1000 };
template <class OBJECT>
OBJECT abs(const OBJECT& x) {
return 0 < x ? x : -x;
}
struct Recurser {
int d_recurseDepth;
char *d_topPtr;
static bool s_finished;
void deepRecurser() {
char buffer[BUFSIZE];
int curDepth = abs(buffer - d_topPtr);
if (veryVerbose) {
cout << "Depth: " << curDepth << endl;
}
if (curDepth < d_recurseDepth) {
// recurse
this->deepRecurser();
}
}
void operator()() {
char topRef;
d_topPtr = &topRef;
this->deepRecurser();
s_finished = true;
}
};
bool Recurser::s_finished = false;
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_16
// ============================================================================
// CASE 15 RELATED ENTITIES
// ----------------------------------------------------------------------------
// case 15 just reuses the case 14 related entities
// ============================================================================
// CASE 14 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_14
{
struct Slowfunctor {
typedef bsl::list<double> dateTimeList;
enum {
SLEEP_MICROSECONDS = 100*1000
};
static const double SLEEP_SECONDS;
dateTimeList d_timeList;
dateTimeList& timeList() {
return d_timeList;
}
static double timeofday() {
return bdlt::CurrentTime::now().totalSecondsAsDouble();
}
void callback() {
d_timeList.push_back(timeofday());
sleepUntilMs(SLEEP_MICROSECONDS / 1000);
d_timeList.push_back(timeofday());
}
double tolerance(int i) {
return Slowfunctor::SLEEP_SECONDS * (0.2 * i + 2);
}
};
const double Slowfunctor::SLEEP_SECONDS =
Slowfunctor::SLEEP_MICROSECONDS * 1e-6;
struct Fastfunctor {
typedef bsl::list<double> dateTimeList;
static const double TOLERANCE;
dateTimeList d_timeList;
dateTimeList& timeList() {
return d_timeList;
}
static double timeofday() {
return bdlt::CurrentTime::now().totalSecondsAsDouble();
}
void callback() {
d_timeList.push_back(timeofday());
}
};
const double Fastfunctor::TOLERANCE = Slowfunctor::SLEEP_SECONDS * 3;
template<class _Tp>
inline const _Tp
abs(const _Tp& __a) {
return 0 <= __a ? __a : - __a;
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_14
// ----------------------------------------------------------------------------
// CASE 13 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_13
{
void countInvoked(bsls::AtomicInt *numInvoked)
{
if (numInvoked) {
++*numInvoked;
}
}
void scheduleEvent(Obj *scheduler,
bsls::AtomicInt *numAdded,
bsls::AtomicInt *numInvoked,
bslmt::Barrier *barrier)
{
barrier->wait();
while (true) {
Obj::Handle handle = scheduler->scheduleEvent(
bdlt::CurrentTime::now(),
bdlf::BindUtil::bind(&countInvoked, numInvoked));
if (Obj::e_INVALID_HANDLE == handle) {
break;
}
++*numAdded;
}
}
void startClock(Obj *scheduler,
bsls::AtomicInt *numAdded,
bsls::AtomicInt *numInvoked,
bslmt::Barrier *barrier)
{
barrier->wait();
while (true) {
Obj::Handle handle = scheduler->startClock(
bsls::TimeInterval(1),
bdlf::BindUtil::bind(&countInvoked, numInvoked));
if (Obj::e_INVALID_HANDLE == handle) {
break;
}
++*numAdded;
}
}
// Calculate the number of bits required to store an index with the specified
// 'maxValue'.
int numBitsRequired(int maxValue)
{
ASSERT(0 <= maxValue);
return (sizeof(maxValue) * CHAR_BIT) - bdlb::BitUtil::numLeadingUnsetBits(
static_cast<bsl::uint32_t>(maxValue));
}
// Calculate the largest integer identifiable using the specified 'numBits'.
int maxNodeIndex(int numBits)
{
return (1 << numBits) - 2;
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_13
// ============================================================================
// CASE 12 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_12
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_12
// ============================================================================
// CASE 11 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_11
{
enum {
NUM_THREADS = 8, // number of threads
NUM_ITERATIONS = 1000 // number of iterations
};
const bsls::TimeInterval T6(6 * DECI_SEC); // decrease chance of timing failure
bool testTimingFailure = false;
bslmt::Barrier barrier(NUM_THREADS);
bslma::TestAllocator ta;
Obj x(&ta);
TestClass1 testObj[NUM_THREADS]; // one test object for each thread
extern "C" {
void *workerThread11(void *arg)
{
int id = (int)(bsls::Types::IntPtr)arg;
barrier.wait();
switch(id % 2) {
// even numbered threads run 'case 0:'
case 0: {
for (int i = 0; i< NUM_ITERATIONS; ++i) {
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(now + T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj[id]));
x.cancelAllEvents();
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (!testTimingFailure) {
// This logic is such that if testTimingFailure is false,
// then we can *guarantee* that no job should have been able
// to execute. The logic always errs in the favor of doubt,
// but the common case is that elapsed will always be < T4.
testTimingFailure = (elapsed >= T6);
}
}
}
break;
// odd numbered threads run 'case 1:'
case 1: {
for (int i = 0; i< NUM_ITERATIONS; ++i) {
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj[id]));
x.cancelAllClocks();
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (!testTimingFailure) {
// This logic is such that if testTimingFailure is false,
// then we can *guarantee* that no job should have been able
// to execute. The logic always errs in the favor of doubt,
// but the common case is that elapsed will always be < T4.
testTimingFailure = (elapsed >= T6);
}
}
}
break;
};
barrier.wait();
return NULL;
}
} // extern "C"
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_11
// ============================================================================
// CASE 10 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_10
{
enum {
NUM_THREADS = 8, // number of threads
NUM_ITERATIONS = 1000 // number of iterations
};
const bsls::TimeInterval T6(6 * DECI_SEC); // decrease chance of timing failure
bool testTimingFailure = false;
bslmt::Barrier barrier(NUM_THREADS);
bslma::TestAllocator ta;
Obj x(&ta);
TestClass1 testObj[NUM_THREADS]; // one test object for each thread
extern "C" {
void *workerThread10(void *arg)
{
int id = (int)(bsls::Types::IntPtr)arg;
barrier.wait();
switch(id % 2) {
// even numbered threads run 'case 0:'
case 0: {
if (veryVerbose) {
printMutex.lock();
cout << "\tStart event iterations" << endl;
printMutex.unlock();
}
for (int i = 0; i< NUM_ITERATIONS; ++i) {
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h =
x.scheduleEvent(now + T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj[id]));
if (veryVeryVerbose) {
int *handle = (int*)(h & 0x8fffffff);
printMutex.lock();
cout << "\t\tAdded event: "; P_(id); P_(i); P_(h); P(handle);
printMutex.unlock();
}
if (0 != x.cancelEvent(h) && !testTimingFailure) {
// We tried and the 'cancelEvent' failed, but we do not want
// to generate an error unless we can *guarantee* that the
// 'cancelEvent' should have succeeded.
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
LOOP3_ASSERTT(id, i, (int*)h, elapsed < T6);
testTimingFailure = (elapsed >= T6);
}
}
}
break;
// odd numbered threads run 'case 1:'
case 1: {
if (veryVerbose) {
printMutex.lock();
cout << "\tStart clock iterations" << endl;
printMutex.unlock();
}
for (int i = 0; i< NUM_ITERATIONS; ++i) {
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h =
x.startClock(T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj[id]));
if (veryVeryVerbose) {
int *handle = (int*)(h & 0x8fffffff);
printMutex.lock();
cout << "\t\tAdded clock: "; P_(id); P_(i); P_(h); P(handle);
printMutex.unlock();
}
if (0 != x.cancelClock(h) && !testTimingFailure) {
// We tried and the 'cancelClock' failed, but we do not want
// to generate an error unless we can *guarantee* that the
// 'cancelClock' should have succeeded.
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
LOOP3_ASSERTT(id, i, (int*)h, elapsed < T6);
testTimingFailure = (elapsed >= T6);
}
}
}
break;
};
return NULL;
}
} // extern "C"
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_10
// ============================================================================
// CASE 9 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_9
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_9
// ============================================================================
// CASE 8 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_8
{
void dispatcherFunction(bsl::function<void()> functor)
// This is a dispatcher function that simply execute the specified
// 'functor'.
{
functor();
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_8
// ============================================================================
// CASE 7 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_7
{
void schedulingCallback(Obj *scheduler,
TestClass1 *event,
TestClass1 *clock)
// Schedule the specified 'event' and the specified 'clock' on the
// specified 'scheduler'. Schedule the clock first to ensure that it will
// get executed before the event does.
{
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T4(4 * DECI_SEC);
scheduler->startClock(T2, bdlf::MemFnUtil::memFn(&TestClass1::callback,
clock));
scheduler->scheduleEvent(bdlt::CurrentTime::now() + T4,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
event));
}
void test7_a()
{
// Schedule an event at T2 that itself schedules an event at T2+T4=T7 and
// a clock with period T2 (clicking at T4, T6, ...), and verify that
// callbacks are executed as expected.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T8 = 8 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T10(10 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 event;
TestClass1 clock;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(
now + T2,
bdlf::BindUtil::bind(&schedulingCallback, &x, &event, &clock));
myMicroSleep(T8, 0);
makeSureTestObjectIsExecuted(event, mT, 200);
LOOP_ASSERT(event.numExecuted(), 1 == event.numExecuted() );
LOOP_ASSERT(clock.numExecuted(), 1 <= clock.numExecuted() );
}
void test7_b()
{
// Schedule an event e1 at time T such that it cancels itself with wait
// argument (this will fail), and an event e2 that will be pending when
// c1 will execute (this is done by waiting long enough before starting
// the scheduler). Make sure no deadlock results.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
Handle handleToBeCancelled =
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::BindUtil::bind(&cancelEventCallback,
&x,
&handleToBeCancelled,
1,
-1));
x.scheduleEvent(bdlt::CurrentTime::now() + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T6, 0); // let testObj's callback be pending
x.start();
myMicroSleep(T3, 0); // give enough time to complete testObj's callback
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
}
void test7_c()
{
// Schedule an event e1 at time T such that it invokes 'cancelAllEvents'
// with wait argument, and another event e2 at time T2 that will be
// pending when e1 will execute (this is done by waiting long enough
// before starting the scheduler). Make sure no deadlock results of e1
// waiting for e2 to complete (both are running in the dispatcher
// thread).
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1;
TestClass1 testObj2;
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::BindUtil::bind(&cancelAllEventsCallback, &x, 1));
x.scheduleEvent(bdlt::CurrentTime::now() + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
myMicroSleep(T6, 0); // let testObj1's callback be pending
x.start();
myMicroSleep(T3, 0); // give enough time to complete testObj's callback
makeSureTestObjectIsExecuted(testObj1, mT, 100);
ASSERT( 1 == testObj1.numExecuted() );
}
void test7_d()
{
// Schedule a clock c1 such that it cancels itself with wait argument (this
// will fail), and an event e2 that will be pending when c1 will execute
// (this is done by waiting long enough before starting the scheduler).
// Make sure no deadlock results.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
Handle handleToBeCancelled = x.startClock(
T,
bdlf::BindUtil::bind(&cancelClockCallback,
&x,
&handleToBeCancelled,
1,
0));
x.scheduleEvent(bdlt::CurrentTime::now() + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T6, 0); // let testObj1's callback be pending
x.start();
myMicroSleep(T3, 0); // give enough time to complete testObj's callback
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
}
void test7_e()
{
// Schedule a clock c1 such that it invokes 'cancelAllClocks' with wait
// argument, and an event e2 that will be pending when c1 will execute
// (this is done by waiting long enough before starting the scheduler).
// Make sure no deadlock results.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
x.startClock(T, bdlf::BindUtil::bind(&cancelAllClocksCallback, &x, 1));
x.scheduleEvent(bdlt::CurrentTime::now() + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T6, 0); // let testObj1's callback be pending
x.start();
myMicroSleep(T3, 0); // give enough time to complete testObj's callback
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
}
void test7_f()
{
// Cancel from dispatcher thread and verify that the state is still
// valid. For DRQS 7272737, it takes two events to reproduce the
// problem.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T3(3 * DECI_SEC);
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj;
Handle h1, h2;
{
bsl::shared_ptr<int> ptr1; ptr1.createInplace(&ta, 1);
bsl::shared_ptr<int> ptr2; ptr2.createInplace(&ta, 2);
h1 = x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::BindUtil::bind(
&cancelEventCallbackWithState,
&x,
&h1,
ptr1));
h2 = x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::BindUtil::bind(
&cancelEventCallbackWithState,
&x,
&h2,
ptr2));
}
x.scheduleEvent(bdlt::CurrentTime::now() + T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T10, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_7
// ============================================================================
// CASE 6 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_6
{
void test6_a()
{
// Schedule clocks starting at T3 and T5, invoke 'cancelAllClocks' at
// time T and make sure that both are cancelled successfully.
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T3(3 * DECI_SEC);
const bsls::TimeInterval T5(5 * DECI_SEC);
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj1;
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T3, bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
x.startClock(T5, bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
sleepUntilMs(T / 1000);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
// put a little margin between this and the first clock (T3).
x.cancelAllClocks();
myMicroSleep(T6, 0);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
ASSERT( 0 == testObj1.numExecuted() );
ASSERT( 0 == testObj2.numExecuted() );
}
}
void test6_b()
{
// Schedule clocks c1 at T(which executes for T10 time), c2 at T2 and c3
// at T3. Let all clocks be simultaneously put onto the pending list
// (this is done by sleeping enough time before starting the scheduler).
// Let c1's first execution be started (by sleeping enough time), invoke
// 'cancelAllClocks' without wait argument, verify that c1's first
// execution has not yet completed and verify that c2 and c3 are
// cancelled without any executions.
bsls::TimeInterval T(1 * DECI_SEC);
bsls::TimeInterval T2(2 * DECI_SEC);
bsls::TimeInterval T3(3 * DECI_SEC);
const int TM1 = 1 * DECI_SEC_IN_MICRO_SEC;
const int TM4 = 4 * DECI_SEC_IN_MICRO_SEC;
const int TM10 = 10 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1(TM10);
TestClass1 testObj2;
TestClass1 testObj3;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1),
now - T3);
x.startClock(T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2),
now - T2);
x.startClock(T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj3),
now - T);
double start = dnow();
x.start();
myMicroSleep(TM4, 0); // let the callback of 'testObj1' be started
x.cancelAllClocks();
if (testObj1.numStarted() > 0 && dnow() - start < 0.9) {
ASSERT( 0 == testObj1.numExecuted() );
ASSERT( 0 == testObj2.numExecuted() );
ASSERT( 0 == testObj3.numExecuted() );
while ( 1 > testObj1.numExecuted() ) {
myMicroSleep(TM1, 0);
}
myMicroSleep(TM10, 0);
ASSERT( 1 == testObj1.numExecuted() );
ASSERT( 0 == testObj2.numExecuted() );
ASSERT( 0 == testObj3.numExecuted() );
}
}
void test6_c()
{
// Schedule clocks c1 at T(which executes for T10 time), c2 at. T2 and c3
// at T3. Let all clocks be simultaneously put onto the pending list (this
// is done by sleeping enough time before starting the scheduler). Let
// c1's first execution be started (by sleeping enough time), invoke
// 'cancelAllClocks' with wait argument, verify that c1's first execution
// has completed and verify that c2 and c3 are cancelled without any
// executions.
bsls::TimeInterval T(1 * DECI_SEC);
bsls::TimeInterval T2(2 * DECI_SEC);
bsls::TimeInterval T3(3 * DECI_SEC);
const int T4 = 4 * DECI_SEC_IN_MICRO_SEC;
const int T5 = 5 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
const int T15 = 15 * DECI_SEC_IN_MICRO_SEC;
if (veryVerbose) {
P_(T4); P_(T5); P_(T10); P(T15);
}
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1(T10);
TestClass1 testObj2;
TestClass1 testObj3;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1),
now - T2);
x.startClock(T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2),
now - T);
x.startClock(T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj3),
now);
double start = dnow();
x.start();
myMicroSleep(T4, 0); // let the callback of 'testObj1' be started
double endSleep = dnow();
int wait = 1;
x.cancelAllClocks(wait);
int numExecuted[4];
numExecuted[1] = testObj1.numExecuted();
numExecuted[2] = testObj2.numExecuted();
numExecuted[3] = testObj3.numExecuted();
if (endSleep - start <= 0.9) {
ASSERT( 1 == numExecuted[1] );
ASSERT( 0 == numExecuted[2] );
ASSERT( 0 == numExecuted[3] );
}
else {
if (verbose) ET("test6_c() overslept");
}
myMicroSleep(T15, 0);
ASSERT( numExecuted[1] == testObj1.numExecuted() );
ASSERT( numExecuted[2] == testObj2.numExecuted() );
ASSERT( numExecuted[3] == testObj3.numExecuted() );
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_6
// ============================================================================
// CASE 5 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_5
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_5
// ============================================================================
// CASE 4 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_4
{
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_4
// ============================================================================
// CASE 3 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_3
{
void test3_a()
{
if (verbose) ET_("\tSchedule event and cancel before execution.\n");
// Schedule an event at T2, cancel it at time T and verify the result.
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T5(5 * DECI_SEC);
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.scheduleEvent(now + T5,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
sleepUntilMs(T / 1000);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
ASSERT( 0 == x.cancelEvent(h) );
myMicroSleep(T6, 0);
ASSERT( 0 == testObj.numExecuted() );
}
}
void test3_b()
{
if (verbose) ET_("\tCancel pending event (should fail).\n");
// Schedule 2 events at T and T2. Let both be simultaneously put onto
// the pending list (this is done by sleeping enough time before starting
// the scheduler), invoke 'cancelEvent(handle)' on the second event while
// it is still on pending list and verify that cancel fails.
bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1(T10);
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
(void)x.scheduleEvent(now + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
Handle h2 = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
myMicroSleep(T3, 0);
x.start();
myMicroSleep(T3, 0);
ASSERT( 0 != x.cancelEvent(h2) );
if ((bdlt::CurrentTime::now() - now).totalSecondsAsDouble() < 1.29) {
ASSERT( 0 == testObj2.numExecuted() );
}
x.stop();
ASSERT( 1 == testObj2.numExecuted() );
}
void test3_c()
{
if (verbose) ET_("\tCancel pending event (should fail again).\n");
// Schedule 2 events at T and T2. Let both be simultaneously put onto
// the pending list (this is done by sleeping enough time before starting
// the scheduler), invoke 'cancelEvent(handle, wait)' on the second event
// while it is still on pending list and verify that cancel fails.
bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1(T10);
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
(void)x.scheduleEvent(now + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
Handle h2 = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
myMicroSleep(T3, 0);
x.start();
myMicroSleep(T3, 0); // give enough time to be put on pending list
int wait = 1;
ASSERT( 0 != x.cancelEvent(h2, wait) );
ASSERT( 1 == testObj2.numExecuted() );
}
void test3_d()
{
if (verbose) ET_("\tCancel event from another event prior.\n");
// Schedule events e1 and e2 at T and T2 respectively, cancel e2 from e1
// and verify that cancellation succeed.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj;
Handle handleToBeCancelled;
bsls::TimeInterval now = bdlt::CurrentTime::now();
handleToBeCancelled = x.scheduleEvent(
now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
// It could possibly happen that testObj has already been scheduled for
// execution, and thus the following cancelEvent will fail. Make sure that
// does not happen.
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T) {
x.scheduleEvent(now + T,
bdlf::BindUtil::bind(&cancelEventCallback,
&x,
&handleToBeCancelled,
0,
0));
myMicroSleep(T3, 0);
ASSERT( 0 == testObj.numExecuted() );
}
// Else should we complain that too much time has elapsed? In any case,
// this is not a failure, do not stop.
}
void test3_e()
{
if (verbose) ET_("\tCancel event from subsequent event (should fail).\n");
// Schedule events e1 and e2 at T and T2 respectively, cancel e1 from e2
// and verify that cancellation fails.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj;
Handle handleToBeCancelled;
bsls::TimeInterval now = bdlt::CurrentTime::now();
handleToBeCancelled = x.scheduleEvent(
now + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
x.scheduleEvent(now + T2,
bdlf::BindUtil::bind(&cancelEventCallback,
&x,
&handleToBeCancelled,
0,
-1));
myMicroSleep(T3, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
}
void test3_f()
{
if (verbose) ET_("\tCancel event from itself (should fail).\n");
// Schedule an event that invokes cancel on itself. Verify that
// cancellation fails.
const bsls::TimeInterval T(1 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle handleToBeCancelled =
x.scheduleEvent(now + T,
bdlf::BindUtil::bind(&cancelEventCallback,
&x,
&handleToBeCancelled,
0,
-1));
myMicroSleep(T3, 0);
// The assert is performed by 'cancelEventCallback'.
}
void test3_g()
{
if (verbose) ET_("\tCancel pending event from pending event prior.\n");
// Schedule e1 and e2 at T and T2 respectively. Let both be
// simultaneously put onto the pending list (this is done by sleeping
// enough time before starting the scheduler), cancel e2 from e1 and
// verify that it succeeds.
bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle handleToBeCancelled = x.scheduleEvent(
now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
x.scheduleEvent(now + T,
bdlf::BindUtil::bind(&cancelEventCallback,
&x,
&handleToBeCancelled,
0,
0));
myMicroSleep(T3, 0);
x.start();
// Note that it is guaranteed that pending events are executed in time
// order.
myMicroSleep(T3, 0);
ASSERT( 0 == testObj.numExecuted() );
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_3
// ============================================================================
// CASE 2 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_2
{
struct testCase2Data {
int d_line;
int d_startTime; // in 1/10th of a sec.
bool d_isClock;
int d_periodicInterval; // in 1/10th of a sec.
int d_executionTime; // in 1/10th of a sec.
bool d_delayed;
};
bool testCallbacks(int *failures,
const float totalTime,
const testCase2Data *DATA,
const int NUM_DATA,
TestClass **testObjects)
{
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
bsls::TimeInterval globalLastExecutionTime = bdlt::CurrentTime::now();
bool assertOnFailure = (failures == 0);
bsls::TimeInterval now = bdlt::CurrentTime::now();
// the assumption is this loop will complete in insignificant time
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_line;
const int STARTTIME = DATA[i].d_startTime;
const bool ISCLOCK = DATA[i].d_isClock;
const int PERIODICINTERVAL = DATA[i].d_periodicInterval;
const int EXECUTIONTIME = DATA[i].d_executionTime;
// const bool DELAYED = DATA[i].d_delayed;
if (ISCLOCK) {
testObjects[i] = new TestClass(
LINE,
now + bsls::TimeInterval(STARTTIME * DECI_SEC),
bsls::TimeInterval(PERIODICINTERVAL * DECI_SEC),
&globalLastExecutionTime,
EXECUTIONTIME * DECI_SEC_IN_MICRO_SEC,
assertOnFailure);
x.startClock(bsls::TimeInterval(PERIODICINTERVAL * DECI_SEC),
bdlf::MemFnUtil::memFn(&TestClass::callback,
testObjects[i]),
now + bsls::TimeInterval(STARTTIME * DECI_SEC));
}
else {
testObjects[i] = new TestClass(
LINE,
now + bsls::TimeInterval(STARTTIME * DECI_SEC),
&globalLastExecutionTime,
EXECUTIONTIME * DECI_SEC_IN_MICRO_SEC,
assertOnFailure);
x.scheduleEvent(now + bsls::TimeInterval(STARTTIME * DECI_SEC),
bdlf::MemFnUtil::memFn(&TestClass::callback,
testObjects[i]));
}
}
x.start();
double delta = .5;
myMicroSleep((int) ((totalTime + delta) * DECI_SEC_IN_MICRO_SEC), 0);
x.stop();
double finishTime = bdlt::CurrentTime::now().totalSecondsAsDouble();
finishTime = (finishTime - now.totalSecondsAsDouble()) * 10 - delta;
// if the 'microSleep' function slept for exactly how long we asked it to,
// 'finishTime' should equal totalTime, but myMicroSleep often lags. By a
// lot.
bool result = true;
for (int i = 0; i < NUM_DATA; ++i) {
const int LINE = DATA[i].d_line;
const int STARTTIME = DATA[i].d_startTime;
const bool ISCLOCK = DATA[i].d_isClock;
const int PERIODICINTERVAL = DATA[i].d_periodicInterval;
// const int EXECUTIONTIME = DATA[i].d_executionTime;
const bool DELAYED = DATA[i].d_delayed;
if (veryVerbose) {
cout << *testObjects[i] << endl;
}
if (testObjects[i]->numFailures()) {
result = false;
if (!assertOnFailure) {
++(*failures); // counts number of slightly delayed events
}
}
if (assertOnFailure) {
LOOP_ASSERTT(LINE, DELAYED == testObjects[i]->delayed());
} else if (DELAYED != testObjects[i]->delayed()) {
result = false;
*failures += 10000; // large number to trigger overall failure
}
if (ISCLOCK) {
if (!testObjects[i]->delayed()) {
int n1 = (int) ((finishTime-STARTTIME) / PERIODICINTERVAL) + 1;
// this formula is bogus in general but works for the data
// and relies on totalTime being a float
int n2 = testObjects[i]->numExecuted();
if (assertOnFailure) {
LOOP3_ASSERTT(LINE, n1, n2, n1 == n2);
} else if (n1 != n2) {
result = false;
*failures += 10000; // idem
}
}
}
else {
if (assertOnFailure) {
LOOP_ASSERTT(LINE, 1 == testObjects[i]->numExecuted());
} else if (1 != testObjects[i]->numExecuted()) {
result = false;
}
}
delete testObjects[i];
}
return result;
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_2
// ============================================================================
// CASE 1 RELATED ENTITIES
// ----------------------------------------------------------------------------
namespace TIMER_EVENT_SCHEDULER_TEST_CASE_1
{
void test1_a()
{
// Create and start a scheduler object, schedule a clock of T3 interval,
// schedule an event at T6, invoke 'stop' at T4 and then verify the state.
// Invoke 'start' and then verify the state.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T4 = 4 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T3(3 * DECI_SEC);
const bsls::TimeInterval T6(6 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj1;
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T3, bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
x.scheduleEvent(now + T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
myMicroSleep(T4, 0);
makeSureTestObjectIsExecuted(testObj1, mT, 100);
x.stop();
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
const int NEXEC1 = testObj1.numExecuted();
const int NEXEC2 = testObj2.numExecuted();
if (elapsed < T6) {
LOOP_ASSERT(NEXEC1, 1 == NEXEC1);
LOOP_ASSERT(NEXEC2, 0 == NEXEC2);
} else {
LOOP_ASSERT(NEXEC1, 1 <= NEXEC1);
}
myMicroSleep(T4, 0);
int nExec = testObj1.numExecuted();
LOOP2_ASSERT(NEXEC1, nExec, NEXEC1 == nExec);
nExec = testObj2.numExecuted();
LOOP2_ASSERT(NEXEC2, nExec, NEXEC2 == nExec);
if (0 == NEXEC2) {
// If testObj2 has already executed its event, there is not much point
// to test this.
x.start();
myMicroSleep(T4, 0);
makeSureTestObjectIsExecuted(testObj2, mT, 100, NEXEC2);
nExec = testObj2.numExecuted();
LOOP2_ASSERT(NEXEC2, nExec, NEXEC2 + 1 <= nExec);
}
else {
// However, if testObj2 has already executed its event, we should make
// sure it do so legally, i.e., after the requisite period of time.
// Note that 'elapsed' was measure *after* the 'x.stop()'.
LOOP2_ASSERT(NEXEC2, elapsed, T6 < elapsed);
}
}
void test1_b()
{
// Create and start a scheduler object, schedule two clocks of T3 interval,
// invoke 'cancelAllClocks' and verify the result.
const bsls::TimeInterval T3(3 * DECI_SEC);
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj1;
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h1 = x.startClock(T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
Handle h2 = x.startClock(T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
x.cancelAllClocks();
ASSERT( 0 != x.cancelClock(h1) );
ASSERT( 0 != x.cancelClock(h2) );
const int NEXEC1 = testObj1.numExecuted();
const int NEXEC2 = testObj2.numExecuted();
myMicroSleep(T10, 0);
int nExec = testObj1.numExecuted();
LOOP2_ASSERT(NEXEC1, nExec, NEXEC1 == nExec);
nExec = testObj2.numExecuted();
LOOP2_ASSERT(NEXEC2, nExec, NEXEC2 == nExec);
}
void test1_c()
{
// Create and start a scheduler object, schedule a clock of T3, let it
// execute once and then cancel it and then verify the expected result.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T3(3 * DECI_SEC);
const int T4 = 4 * DECI_SEC_IN_MICRO_SEC;
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.startClock(T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
sleepUntilMs(T4 / 1000);
makeSureTestObjectIsExecuted(testObj, mT, 100);
int nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 1 <= nExec);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T6) {
ASSERT( 0 == x.cancelClock(h) );
ASSERT( 0 != x.cancelClock(h) );
const int NEXEC = testObj.numExecuted();
sleepUntilMs(T4 / 1000);
nExec = testObj.numExecuted();
LOOP2_ASSERT(NEXEC, nExec, NEXEC == nExec);
}
// Else complain but do not stop the test suite.
}
void test1_d()
{
// Create and start a scheduler object, schedule 3 events at T,
// T2, T3. Invoke 'cancelAllEvents' and verify it.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T3(3 * DECI_SEC);
const int T5 = 5 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj1;
TestClass1 testObj2;
TestClass1 testObj3;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h1 = x.scheduleEvent(now + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
Handle h2 = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
Handle h3 = x.scheduleEvent(now + T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj3));
x.cancelAllEvents();
bsls::TimeInterval elapsed = bdlt::CurrentTime::now();
// It is possible that h1 (more likely), h2, or h3 (less likely) have run
// before they got cancelled because of delays. (Happened once on xlC-8.2i
// in 64 bit mode...) But in either case, cancelling the event again
// should fail. However the numExecuted() test below may be 1 in that
// case.
ASSERT( 0 != x.cancelEvent(h1) );
ASSERT( 0 != x.cancelEvent(h2) );
ASSERT( 0 != x.cancelEvent(h3) );
sleepUntilMs(T5 / 1000);
int nExec;
// Be defensive about this and only assert when *guaranteed* that object
// cannot have been called back.
if (elapsed < T) {
nExec = testObj1.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
}
if (elapsed < T2) {
nExec = testObj2.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
}
if (elapsed < T3) {
nExec = testObj3.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
}
// Else should we complain that too much time has elapsed? In any case,
// this is not a failure, do not stop.
}
void test1_e()
{
// Create and start a scheduler object, schedule an event at
// T2, cancelling it at T3 should result in failure.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
myMicroSleep(T3, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
int nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT( 0 != x.cancelEvent(h) );
}
void test1_f()
{
// Create and start a scheduler object, schedule an event at T2, cancel it
// at T and verify that it is cancelled. Verify that cancelling it again
// results in failure.
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
sleepUntilMs(T / 1000);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
ASSERT( 0 == x.cancelEvent(h) );
ASSERT( 0 != x.cancelEvent(h) );
sleepUntilMs(T3 / 1000);
int nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
}
// Else should we complain that too much time has elapsed? In any case,
// this is not a failure, do not stop.
}
void test1_g()
{
// Create and start a scheduler object, schedule a clock of T3 interval,
// schedule an event at T3. Verify that event and clock callbacks are
// being invoked at expected times.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 100 microsecs
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T3(3 * DECI_SEC);
const bsls::TimeInterval T5(5 * DECI_SEC);
const bsls::TimeInterval T6(6 * DECI_SEC);
const bsls::TimeInterval T8(8 * DECI_SEC);
const bsls::TimeInterval T9(9 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj1;
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T3, bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
x.scheduleEvent(now + T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
ASSERT(1 == x.numEvents());
ASSERT(1 == x.numClocks());
}
sleepUntilMs(T2 / 1000);
int nExec = testObj1.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT(1 == x.numEvents());
// ASSERT(1 == x.numClocks());
}
nExec = testObj2.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT(1 == x.numEvents());
// ASSERT(1 == x.numClocks());
}
sleepUntilMs(T2 / 1000);
makeSureTestObjectIsExecuted(testObj1, mT, 100);
nExec = testObj1.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T5) {
LOOP_ASSERT(nExec, 1 == nExec);
}
makeSureTestObjectIsExecuted(testObj2, mT, 100);
nExec = testObj2.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT(0 == x.numEvents());
// ASSERT(1 == x.numClocks());
sleepUntilMs(T2 / 1000);
sleepUntilMs(T / 1000);
makeSureTestObjectIsExecuted(testObj1, mT, 100, 1);
nExec = testObj1.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T8) {
LOOP_ASSERT(nExec, 2 == nExec)
} else {
LOOP_ASSERT(nExec, 2 <= nExec);
}
nExec = testObj2.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
}
void test1_h()
{
// Create and start a scheduler object, schedule a clock of T3 interval,
// verify that clock callback gets invoked at expected times. The reason
// we cannot test that 1 == X.numClocks() is that the clocks may be in the
// middle of execution (popped and not yet rescheduled, in which case
// 0 == X.numClocks()).
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T3(3 * DECI_SEC);
const int T4 = 4 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T6(6 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.startClock(T3, bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
ASSERT(0 == x.numEvents());
ASSERT(1 == x.numClocks());
}
sleepUntilMs(T2 / 1000);
int nExec = testObj.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
LOOP_ASSERT(nExec, 0 == nExec);
}
ASSERT(0 == x.numEvents());
// ASSERT(1 == x.numClocks());
sleepUntilMs(T2 / 1000);
makeSureTestObjectIsExecuted(testObj, mT, 100, nExec);
nExec = testObj.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T6) {
LOOP_ASSERT(nExec, 1 == nExec);
}
else {
LOOP_ASSERT(nExec, 1 <= nExec);
}
myMicroSleep(T4, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100, nExec);
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 2 <= nExec);
ASSERT(0 == x.numEvents());
// ASSERT(1 == x.numClocks());
}
void test1_i()
{
// Create and start a scheduler object, schedule 2 events at different
// times, verify that they execute at expected time.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T3(3 * DECI_SEC);
const bsls::TimeInterval T4(4 * DECI_SEC);
const bsls::TimeInterval T5(5 * DECI_SEC);
const bsls::TimeInterval T6(6 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
ASSERT(0 == x.numEvents());
ASSERT(0 == x.numClocks());
TestClass1 testObj1;
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(now + T4,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
x.scheduleEvent(now + T6,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
ASSERT(2 == x.numEvents());
}
ASSERT(0 == x.numClocks());
sleepUntilMs(T2 / 1000);
int nExec = testObj1.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T3) {
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT(2 == x.numEvents());
ASSERT(0 == x.numClocks());
}
nExec = testObj2.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T5) {
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT(2 - testObj1.numExecuted() == x.numEvents());
ASSERT(0 == x.numClocks());
}
sleepUntilMs(T2 / 1000);
makeSureTestObjectIsExecuted(testObj1, mT, 100);
nExec = testObj1.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
nExec = testObj2.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T5) {
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT(1 == x.numEvents());
ASSERT(0 == x.numClocks());
}
myMicroSleep(T2, 0);
myMicroSleep(T, 0);
nExec = testObj1.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
makeSureTestObjectIsExecuted(testObj2, mT, 100);
nExec = testObj2.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT(0 == x.numEvents());
ASSERT(0 == x.numClocks());
}
void test1_j()
{
// Create and start a scheduler object, schedule an event at T2, using key
// K2. Try to cancel using K1 and verify that it fails. Then try to
// cancel using K2 and verify that it succeeds.
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
typedef Obj::EventKey Key;
const Key K1(123);
const Key K2(456);
bsls::TimeInterval now = bdlt::CurrentTime::now();
double start = dnow();
Handle h = x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj),
K2);
ASSERT(1 == x.numEvents());
ASSERT(0 == x.numClocks());
ASSERT( 0 != x.cancelEvent(h, K1) );
int sts = x.cancelEvent(h, K2);
bool fast = dnow() - start < 0.2;
if (fast) {
ASSERT( 0 == sts ); // this could fail due to long
// delays and unfairness of thread allocation, but very unlikely
}
ASSERT(0 == x.numEvents());
ASSERT(0 == x.numClocks());
myMicroSleep(T, 0);
int nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, !fast || 0 == nExec); // ok, even if overslept
myMicroSleep(T3, 0);
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, !fast || 0 == nExec); // ok, even if overslept
}
void test1_k()
{
// Create and start a scheduler object, schedule an event at T2, verify
// that it is not executed at T but is executed at T3.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
ASSERT(0 == x.numEvents());
ASSERT(0 == x.numClocks());
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
ASSERT(1 == x.numEvents());
}
ASSERT(0 == x.numClocks());
sleepUntilMs(T / 1000);
int nExec = testObj.numExecuted();
elapsed = bdlt::CurrentTime::now() - now;
// myMicroSleep could have overslept, especially if load is high
if (elapsed < T2) {
LOOP_ASSERT(nExec, 0 == nExec);
}
sleepUntilMs(T3 / 1000);
makeSureTestObjectIsExecuted(testObj, mT, 100);
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT(0 == x.numEvents());
ASSERT(0 == x.numClocks());
}
} // close namespace TIMER_EVENT_SCHEDULER_TEST_CASE_1
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
int nExec;
bslma::TestAllocator ta;
bsl::cout << "TEST " << __FILE__ << " CASE " << test << bsl::endl;
switch (test) { case 0: // Zero is always the leading case.
case 25: {
// --------------------------------------------------------------------
// TESTING USAGE EXAMPLE:
//
// Concerns:
// The usage example provided in the component header file must
// compile, link, and execute as shown.
//
// Plan:
// Incorporate the usage example from the header file into the test
// driver.
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING USAGE EXAMPLE" << endl
<< "=====================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_USAGE;
bslma::TestAllocator ta(veryVeryVerbose);
my_Server server(bsls::TimeInterval(10), &ta);
} break;
case 24: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(nE, nC, disp, cT, bA = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// specified dispatcher, specified clock, and provides capacity
// guarantees, correctly schedules events.
//
// Concerns:
//: 1 The creator with the specified dispatcher, specified clock, and
//: capacity guarantees correctly initializes the object.
//
// Plan:
//: 1 Define a dispatcher that simply executes the specified
// functor. Create a scheduler using this dispatcher and the
// monotonic clock, schedule an event and make sure that it is
// executed by the specified dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(nE, nC, disp, cT, bA = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(nE, nC, disp, cT, bA = 0)'" << endl
<< "================================="
<< "===========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_24;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bdlmt::TimerEventScheduler::Dispatcher dispatcher =
bdlf::BindUtil::bind(&dispatcherFunction, _1);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(4, 4, dispatcher, bsls::SystemClockType::e_MONOTONIC, &ta);
x.start();
TestClass1 testObj;
x.scheduleEvent(
bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC) + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 23: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(nE, nC, disp, bA = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// specified dispatcher, realtime clock, and provides capacity
// guarantees, correctly schedules events.
//
// Concerns:
//: 1 The creator with the specified dispatcher, realtime clock, and
//: capacity guarantees correctly initializes the object.
//
// Plan:
//: 1 Define a dispatcher that simply executes the specified
// functor. Create a scheduler using this dispatcher and the
// realtime clock, schedule an event and make sure that it is
// executed by the specified dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(nE, nC, disp, bA = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(nE, nC, disp, bA = 0)'" << endl
<< "================================="
<< "=======================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_23;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bdlmt::TimerEventScheduler::Dispatcher dispatcher =
bdlf::BindUtil::bind(&dispatcherFunction, _1);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(4, 4, dispatcher, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 22: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(nE, nC, cT, bA = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// default dispatcher, specified clock, and provides capacity
// guarantees, correctly schedules events.
//
// Concerns:
//: 1 The creator with the default dispatcher, specified clock, and
//: capacity guarantees correctly initializes the object.
//
// Plan:
//: 1 Create a scheduler using the default dispatcher and the specified
// clock, schedule an event and make sure that it is executed by the
// default dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(nE, nC, cT, bA = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(nE, nC, cT, bA = 0)'" << endl
<< "================================="
<< "=====================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_22;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(4, 4, bsls::SystemClockType::e_MONOTONIC, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(
bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC) + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 21: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(nE, nC, bA = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// default dispatcher, realtime clock, and provides capacity
// guarantees, correctly schedules events.
//
// Concerns:
//: 1 The creator with the default dispatcher and realtime clock
//: correctly initializes the object.
//
// Plan:
//: 1 Create a scheduler using the default dispatcher and the realtime
// clock, schedule an event and make sure that it is executed by the
// default dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(nE, nC, bA = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(nE, nC, bA = 0)'" << endl
<< "================================="
<< "=================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_21;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(4, 4, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 20: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(disp, clockType, alloc = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// specified dispatcher and specified clock, correctly schedules
// events.
//
// Concerns:
//: 1 The creator with a user-defined dispatcher and clock correctly
//: initializes the object.
//
// Plan:
//: 1 Define a dispatcher that simply executes the specified
// functor. Create a scheduler using this dispatcher and the
// monotonic clock, schedule an event and make sure that it is
// executed by the specified dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(disp, clockType, alloc = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(disp, clockType, alloc = 0)'" << endl
<< "================================="
<< "=============================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_20;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bdlmt::TimerEventScheduler::Dispatcher dispatcher =
bdlf::BindUtil::bind(&dispatcherFunction, _1);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(dispatcher, bsls::SystemClockType::e_MONOTONIC, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(
bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC) + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 19: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(clockType, allocator = 0)':
// Verify this 'bdlmt::TimerEventScheduler' creator, which uses the
// default dispatcher and specified clock, correctly schedules
// events.
//
// Concerns:
//: 1 The creator with the default dispatcher and specified clock
//: correctly initializes the object.
//
// Plan:
//: 1 Create a scheduler using the default dispatcher and the monotonic
// clock, schedule an event and make sure that it is executed by the
// default dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(clockType, allocator = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(clockType, allocator = 0)'" << endl
<< "================================="
<< "===========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_19;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(bsls::SystemClockType::e_MONOTONIC, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(
bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC) + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 18: {
// -----------------------------------------------------------------
// Testing cancelEvent
//
// Concerns:
// Verify that 'cancelEvent' does the right thing when an event
// tries to cancel itself, and that pending events after the
// event being canceled are unaffected.
//
// Plan:
// Set up a situation where many events are pending, then have an
// event cancel itself, and show that the next subsequent event
// does not disappear.
// -----------------------------------------------------------------
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_18;
if (verbose) {
cout << "cancelEvent test\n"
"================\n";
}
Obj mX;
Func::s_scheduler = &mX;
bsls::TimeInterval now = bdlt::CurrentTime::now();
for (int i = 0; i < 10; ++i) {
Obj::Handle handle =
mX.scheduleEvent(now - bsls::TimeInterval((10 - i) * 0.1),
Func(i));
Func::s_handles.push_back(handle);
}
Func::s_kamikaze = 4;
mX.start();
// make sure the events all get pending
bslmt::ThreadUtil::yield();
sleepUntilMs(10 * 1000 / 1000);
bslmt::ThreadUtil::yield();
sleepUntilMs(10 * 1000 / 1000);
mX.stop();
LOOP_ASSERT(Func::s_indexes.size(), Func::s_indexes.size() == 10);
for (int i = 0; i < 10; ++i) {
LOOP2_ASSERT(i, Func::s_indexes[i], i == Func::s_indexes[i]);
}
} break;
case 17: {
// -----------------------------------------------------------------
// Testing cancelAllEvents
//
// Concerns:
// There is a bug in 'cancelAllEvents' regarding the updating of
// 'd_numEvents' that previous testing was not exposing.
//
// Plan:
// Get several events on the pending events vector, then
// call 'cancelAllEvents()', keeping track of the # of outstanding
// events, and expose the discrepancy.
// -----------------------------------------------------------------
if (verbose) {
cout << "cancelAllEvents & numEvents test\n"
"================================\n";
}
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_17;
Obj mX;
Func::s_scheduler = &mX;
Func::s_numEvents = 0;
bsls::TimeInterval now = bdlt::CurrentTime::now();
for (int i = 0; i < 7; ++i) {
++Func::s_numEvents;
mX.scheduleEvent(now, Func());
}
mX.start();
bslmt::ThreadUtil::yield();
sleepUntilMs(100 * 1000 / 1000);
mX.cancelAllEvents();
sleepUntilMs(500 * 1000 / 1000);
mX.stop();
} break;
case 16: {
// -----------------------------------------------------------------
// TESTING PASSING ATTRIBUTES TO START:
//
// Concerns:
// That we are able to specify attributes of dispatcher thread by
// passing them to 'start()'.
//
// Plan:
// Configure the stack size to be much bigger than the default,
// then verify that it really is bigger. Note: veryVeryVerbose
// will deliberately make this test crash to find out how big the
// default stack size is (just displaying attr.stackSize() just
// shows 0 if you let stack size default on Solaris).
//
// Also verify that DETACHED attribute is ignored by setting the
// attributes passed to be DETACHED and then doing a 'stop()',
// which will join with the dispatcher thread.
//
// Testing:
// int start(const bslmt::ThreadAttributes& threadAttributes);
// -----------------------------------------------------------------
if (verbose) {
cout << "Attributes test\n";
}
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_16;
bslmt::ThreadAttributes attr;
if (!veryVeryVerbose) {
attr.setStackSize(80 * 1000 * 1000);
}
attr.setDetachedState(bslmt::ThreadAttributes::e_CREATE_DETACHED);
if (verbose) {
cout << "StackSize: " << attr.stackSize() << endl;
}
// As of 10/16/08, the default stack size was about 1MB on Solaris,
// 0.25MB on AIX, and 10MB on Linux.
Recurser r;
r.d_recurseDepth = 79 * 1000 * 1000;
r.s_finished = false;
bdlmt::TimerEventScheduler scheduler;
int sts = scheduler.start(attr);
ASSERT(!sts);
scheduler.scheduleEvent(bdlt::CurrentTime::now() +
bsls::TimeInterval(0.1),
r);
sleepUntilMs(250 * 1000 / 1000);
scheduler.stop();
if (verbose) {
cout << (r.s_finished ? "Finished OK"
: "Error -- did not finish") << endl;
}
ASSERT(r.s_finished);
} break;
case 15: {
// -----------------------------------------------------------------
// TESTING ACCUMULATED TIME LAG
//
// Concerns:
// That if a clock is scheduled that taking longer than the clock
// frequency, that it will execute pretty much continuously, and
// that scheduled events will still get to happen.
//
// Plan:
// We have two functors, 'Slowfunctor' and 'Fastfunctor', the
// first of which takes 0.1 seconds, the second of which runs
// instantaneously. We schedule 'Slowfunctor' as a clock
// occurring every 0.5 seconds, and schedule 'Fastfunctor' to
// happen at 2 specific times. We sleep 4 seconds, and then
// observe that both functors happened roughly when they were
// supposed to.
//
if (verbose) cout <<"\nTesting accumulated time lag, with events\n"
"===========================================\n";
// reusing
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_14;
int ii;
enum { MAX_LOOP = 4 };
for (ii = 0; ii <= MAX_LOOP; ++ii) {
bdlmt::TimerEventScheduler scheduler(&ta);
scheduler.start();
Slowfunctor sf;
Fastfunctor ff;
const double CLOCKTIME1 = sf.SLEEP_SECONDS / 2;
scheduler.startClock(bsls::TimeInterval(CLOCKTIME1),
bdlf::MemFnUtil::memFn(&Slowfunctor::callback,
&sf));
bsls::TimeInterval afterStarted = bdlt::CurrentTime::now();
scheduler.scheduleEvent(
afterStarted + bsls::TimeInterval(2.0),
bdlf::MemFnUtil::memFn(&Fastfunctor::callback, &ff));
scheduler.scheduleEvent(
afterStarted + bsls::TimeInterval(3.0),
bdlf::MemFnUtil::memFn(&Fastfunctor::callback, &ff));
sleepUntilMs(4 * 1000 * 1000 / 1000);
// wait 40 time execution time of sf.callback().
scheduler.stop();
sleepUntilMs(2 * 1000 * 1000 / 1000);
// wait until events can run, verify that clock queue
// stayed small
int slowfunctorSize = sf.timeList().size();
ASSERT(!(slowfunctorSize & 1)); // should not be odd element
slowfunctorSize &= ~1; // ignore odd element if there
if (verbose) { P_(slowfunctorSize); P(ff.timeList().size()); }
ASSERT(ii < MAX_LOOP || slowfunctorSize >= 35*2);
ASSERT(ii < MAX_LOOP || slowfunctorSize <= 44*2);
if (slowfunctorSize < 35*2 || slowfunctorSize > 44*2) {
if (verbose || MAX_LOOP == ii) { P_(L_) P(slowfunctorSize); }
continue; // start over
}
ASSERT(ii < MAX_LOOP || 2 == ff.timeList().size());
if (2 != ff.timeList().size()) {
if (verbose || MAX_LOOP == ii) {
P_(L_) P(ff.timeList().size());
}
}
Slowfunctor::dateTimeList::iterator sfit = sf.timeList().begin();
double startTime = *sfit;
if (verbose) {
P(afterStarted.totalSecondsAsDouble() - startTime);
}
// go through even elements - they should be right on time Note
// this has unavoidable intermittent failures as the sleep function
// may go over by as much as 2 seconds.
double prevTime = startTime;
const double sTolerance = 0.03;
++sfit, ++sfit;
bool startOver = false;
for (int i = 2; i+2 <= slowfunctorSize; ++sfit, ++sfit, i += 2) {
double offBy = *sfit - Slowfunctor::SLEEP_SECONDS - prevTime;
if (veryVerbose) { P_(i); P_(offBy); P(sTolerance); }
ASSERT(ii < MAX_LOOP || sTolerance > abs(offBy));
if (sTolerance <= abs(offBy)) {
if (verbose || MAX_LOOP == ii) {
P_(L_) P_(i) P_(sTolerance) P(offBy);
}
startOver = true;
}
prevTime = *sfit;
}
if (startOver) continue;
#if 0
// This has been commented out because it is really inappropriate
// to be testing the accuracy of the 'microSleep' method in this
// component -- especially since it can be really unreasonably slow
// on a heavily loaded machine (i.e., during the nighttime runs).
// Testing of that routine has been moved to
// 'bslmt_threadutil.t.cpp'.
// go through odd elements - they should be SLEEP_SECONDS later
sfit = sf.timeList().begin();
++sfit;
for (int i = 1; i+2 <= slowfunctorSize; ++sfit, ++sfit, i += 2) {
double diff = *sfit - start_time;
double offBy = (i/2 + 1)*sf.SLEEP_SECONDS - diff;
if (veryVerbose) { P_(L_) P_(i); P_(offBy);
P(sf.tolerance(i/2)); }
LOOP4_ASSERT(i, diff, offBy, sf.tolerance(i/2),
sf.tolerance(i/2) > abs(offBy));
}
#endif
Fastfunctor::dateTimeList::iterator ffit = ff.timeList().begin();
double ffdiff = *ffit - afterStarted.totalSecondsAsDouble();
double ffoffBy = ffdiff - 2;
if (veryVerbose) { P_(ffdiff); P_(ffoffBy); P(ff.TOLERANCE); }
ASSERT(ii < MAX_LOOP || ff.TOLERANCE > abs(ffoffBy));
if (ff.TOLERANCE <= abs(ffoffBy)) {
if (verbose || MAX_LOOP == ii) {
P_(L_) P_(ffdiff) P(ffoffBy);
}
continue;
}
++ffit;
ffdiff = *ffit - afterStarted.totalSecondsAsDouble();
ffoffBy = ffdiff - 3;
if (veryVerbose) { P_(ffdiff); P_(ffoffBy); P(ff.TOLERANCE); }
ASSERT(ii < MAX_LOOP || ff.TOLERANCE > abs(ffoffBy));
if (ff.TOLERANCE <= abs(ffoffBy)) {
if (!veryVerbose && MAX_LOOP == ii) {
P_(L_) P_(ffdiff); P_(ffoffBy); P(ff.TOLERANCE);
}
continue;
}
break;
}
ASSERT(ii <= MAX_LOOP);
if (verbose) { P_(L_) P(ii); }
} break;
case 14: {
// -----------------------------------------------------------------
// TESTING REGULARITY OF CLOCK EVENTS
//
// Concerns:
// That clock events happen when scheduled.
//
// Plan:
// Schedule a clocked event that will take less time than the
// period of the clock to execute, and verify that it happens
// regularly with a fixed accuracy, without any creep or
// accumulated lag.
//
// <<NOTE>> -- due to unreliability of
// 'bslmt::Condition::timedWait', this test is going to fail a
// certain percentage of the time.
// -----------------------------------------------------------------
if (verbose) cout << "\nTesting accumulated time lag\n"
"============================\n";
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_14;
bslma::TestAllocator ta;
int ii;
enum { MAX_LOOP = 4 };
for (ii = 0; ii <= MAX_LOOP; ++ii) {
bdlmt::TimerEventScheduler scheduler(&ta);
scheduler.start();
Slowfunctor sf;
const double CLOCKTIME1 = 0.3;
const double TOLERANCE_BEHIND = 0.25;
const double TOLERANCE_AHEAD = 0.03;
scheduler.startClock(
bsls::TimeInterval(CLOCKTIME1),
bdlf::MemFnUtil::memFn(&Slowfunctor::callback, &sf));
sleepUntilMs(6 * 1000 * 1000 / 1000);
// wait 20 clock cycles
scheduler.stop();
sleepUntilMs(3 * 1000 * 1000 / 1000);
// let running tasks finish, test that clock queue did not
// get large
int slowfunctorSize = sf.timeList().size();
if (verbose) { P(slowfunctorSize); }
ASSERT(!(slowfunctorSize & 1)); // should not be odd element
slowfunctorSize &= ~1; // ignore odd element if there
ASSERT(ii < MAX_LOOP || slowfunctorSize >= 18*2);
ASSERT(ii < MAX_LOOP || slowfunctorSize <= 22*2);
if (slowfunctorSize < 18*2 || slowfunctorSize > 22*2) {
if (verbose || ii == MAX_LOOP) { P_(L_) P(slowfunctorSize); }
continue;
}
Slowfunctor::dateTimeList::iterator it = sf.timeList().begin();
double start_time = *it;
// go through even elements - they should be right on time
bool startOver = false;
for (int i = 0; i+2 <= slowfunctorSize; ++it, ++it, i += 2) {
double diff = *it - start_time;
double offBy = diff - (i/2)*CLOCKTIME1;
if (veryVerbose) { P_(i); P(offBy); }
ASSERT(ii < MAX_LOOP || TOLERANCE_BEHIND > offBy);
ASSERT(ii < MAX_LOOP || TOLERANCE_AHEAD > -offBy);
if (TOLERANCE_BEHIND <= offBy || TOLERANCE_AHEAD <= -offBy) {
if (verbose || ii == MAX_LOOP) {
P_(L_) P_(i) P_(diff)
P_(TOLERANCE_BEHIND) P(TOLERANCE_AHEAD)
P(offBy);
}
startOver = true;
}
}
if (startOver) continue;
break;
}
ASSERT(ii <= MAX_LOOP);
if (verbose) { P_(L_) P(ii); }
// TBD
#if 0
// This has been commented out because it is really inappropriate to
// be testing the accuracy of the 'microSleep' method in this component
// -- especially since it can be really unreasonably slow on a heavily
// loaded machine (i.e., during the nighttime runs). Testing of that
// routine has been moved to 'bslmt_threadutil.t.cpp'.
// go through odd elements - they should be SLEEP_SECONDS later
it = sf.timeList().begin();
++it;
for (int i = 1; i+2 <= slowfunctorSize; ++it, ++it, i += 2) {
double diff = *it - start_time;
double offBy = (i/2)*CLOCKTIME1 + sf.SLEEP_SECONDS - diff;
if (veryVerbose) { P_(i); P(offBy); }
LOOP4_ASSERT(i, diff, offBy, TOLERANCE, TOLERANCE > abs(offBy));
}
#endif
} break;
case 13: {
// -----------------------------------------------------------------
// TESTING CONCERN: Maximum number of concurrently scheduled events
// and clocks.
//
// Concerns:
// Given 'numEvents' and 'numClocks' (where
// 'numEvents <= 2**24 - 1' and 'numClocks <= 2**24 - 1'), ensure
// that *at least* 'numEvents' and 'numClocks' may be concurrently
// scheduled.
//
// Plan:
// Define two values 'numEvents' and 'numClocks', then construct a
// timer event scheduler using these values. In order to prevent
// any scheduled events from firing, leave the scheduler in the
// "stopped" state. Schedule events from multiple threads and
// ensure *at least* 'numEvents' may be concurrently scheduled.
// Cancel all events, then again schedule events from multiple
// threads and ensure the maximum number of events may again be
// scheduled. Repeat for clocks.
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING MAX CONCURRENT EVENTS & CLOCKS"
<< endl
<< "======================================"
<< endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_13;
const int TEST_DATA[] = {
(1 << 3), // some small value
(1 << 17) - 2 // the default "minimum guarantee"
};
const int NUM_TESTS = sizeof TEST_DATA / sizeof *TEST_DATA;
const int NUM_THREADS = 4;
for (int testIter = 0; testIter < NUM_TESTS; ++testIter) {
const int NUM_OBJECTS = TEST_DATA[testIter];
Obj mX(NUM_OBJECTS, NUM_OBJECTS);
for (int i = 0; i < 2; ++i) {
bsls::AtomicInt numAdded(0);
bslmt::Barrier barrier(NUM_THREADS + 1);
bslmt::ThreadGroup threadGroup;
threadGroup.addThreads(
bdlf::BindUtil::bind(&scheduleEvent,
&mX,
&numAdded,
(bsls::AtomicInt *)0,
&barrier),
NUM_THREADS);
barrier.wait();
threadGroup.joinAll();
ASSERT(numAdded >= NUM_OBJECTS);
ASSERT(mX.numEvents() >= NUM_OBJECTS);
numAdded = 0;
threadGroup.addThreads(
bdlf::BindUtil::bind(&startClock,
&mX,
&numAdded,
(bsls::AtomicInt *)0,
&barrier),
NUM_THREADS);
barrier.wait();
threadGroup.joinAll();
ASSERT(numAdded >= NUM_OBJECTS);
ASSERT(mX.numClocks() >= NUM_OBJECTS);
mX.cancelAllEvents();
mX.cancelAllClocks();
ASSERT(0 == mX.numEvents());
ASSERT(0 == mX.numClocks());
}
}
} break;
case 12: {
// -----------------------------------------------------------------
// TESTING 'rescheduleEvent':
//
// Concerns:
// That 'rescheduleEvent' should be successful when it is possible
// to reschedule it.
//
// That 'rescheduleEvent' should fail when it not is possible
// to reschedule it.
//
// Plan:
// Create and start a scheduler object, schedule an event at T2,
// reschedule it after T and verify that reschedule succeeds.
// Verify that the callback executes at the new rescheduled
// time. Now verify that rescheduling the same event fails.
//
// Repeat above, but this time use an arbitrary key.
//
// Testing:
// int rescheduleEvent(handle, key, newTime);
// int rescheduleEvent(handle, newTime);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'rescheduleEvent'" << endl
<< "=========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_12;
{
// Create and start a scheduler object, schedule an event at T2,
// reschedule it at T and verify that reschedule succeeds. Verify
// that the callback executes at the new rescheduled time. Now
// verify that rescheduling the same event fails.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T4(4 * DECI_SEC);
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T8(8 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.scheduleEvent(
now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T, 0);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT( 0 == x.rescheduleEvent(h, now + T4, true) );
myMicroSleep(T6, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT( 0 != x.rescheduleEvent(h, now + T8, true) );
}
}
{
// Repeat above, but this time use an arbitrary key.
typedef Obj::EventKey Key;
const Key key(123);
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T4(4 * DECI_SEC);
const int T6 = 6 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T8(8 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.scheduleEvent(
now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj),
key);
myMicroSleep(T, 0);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 0 == nExec);
ASSERT( 0 == x.rescheduleEvent(h, key, now + T4, true) );
myMicroSleep(T6, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
nExec = testObj.numExecuted();
LOOP_ASSERT(nExec, 1 == nExec);
ASSERT( 0 != x.rescheduleEvent(h, key, now + T8, true) );
}
}
} break;
case 11: {
// -----------------------------------------------------------------
// TESTING CONCURRENT SCHEDULING AND CANCELLING-ALL:
// Verify concurrent scheduling and cancelling-All.
//
// Concerns:
// That concurrent scheduling and cancelling-all of clocks and
// events are safe.
//
// Plan:
// Create several threads. Half of the threads execute 'h =
// scheduler.scheduleEvent(..), scheduler.cancelAllEvent()' in a
// loop and other half execute 'h = scheduler.startClock(..);
// scheduler.cancelAllClocks(h)' in a loop. Finally join all the
// threads and verify that no callback has been invoked and that
// the scheduler is still in good state (this is done by
// scheduling an event and verifying that it is executed as
// expected).
//
// Testing:
// Concurrent scheduling and cancelling-All.
// -----------------------------------------------------------------
if (verbose)
cout << endl
<< "TESTING CONCURRENT SCHEDULING AND CANCELLING-ALL" << endl
<< "================================================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_11;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
ASSERT( 0 == x.start() );
executeInParallel(NUM_THREADS, workerThread11);
myMicroSleep(T10, 0);
if (!testTimingFailure) {
for (int i = 0; i< NUM_THREADS; ++i) {
ASSERT( 0 == testObj[i].numExecuted() );
}
} else {
// In the highly unlikely event, that one thread could not invoke
// 'cancelAllEvents' or 'cancelAllClocks' in time to guarantee that
// the event it had scheduled earlier was cancelled, the test
// fails. This can be prevented by increasing the delay (initially
// T, currently T4) with which the event is scheduled. Note that
// the delay T5 with which this test is executed must be increased
// correspondingly.
// The following message will be reported by the nightly build,
// although it will not trigger a failure.
cout << "TIMING FAILURE ERROR IN CASE 11 - INCREASE DELAYS\n";
}
// test if the scheduler is still in good state
const bsls::TimeInterval T(1 * DECI_SEC);
const int T4 = 4 * DECI_SEC_IN_MICRO_SEC;
TestClass1 testObj;
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
myMicroSleep(T4, 0);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 10: {
// -----------------------------------------------------------------
// TESTING CONCURRENT SCHEDULING AND CANCELLING:
// Verify concurrent scheduling and cancelling.
//
// Concerns:
// That concurrent scheduling and cancelling of clocks and
// events are safe.
//
// Plan:
// Create several threads. Half of the threads execute 'h =
// scheduler.scheduleEvent(..), scheduler.cancelEvent(h)' in a
// loop and other half execute 'h = scheduler.startClock(..);
// scheduler.cancelClock(h)' in a loop. Finally join all the
// threads and verify that no callback has been invoked and that
// the scheduler is still in good state (this is done by
// scheduling an event and verifying that it is executed as
// expected).
//
// Testing:
// Concurrent scheduling and cancelling.
// -----------------------------------------------------------------
if (verbose)
cout << endl
<< "TESTING CONCURRENT SCHEDULING AND CANCELLING" << endl
<< "============================================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_10;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
ASSERT( 0 == x.start() );
executeInParallel(NUM_THREADS, workerThread10);
myMicroSleep(T10, 0);
if (!testTimingFailure) {
for (int i = 0; i < NUM_THREADS; ++i) {
LOOP2_ASSERT(i, testObj[i].numExecuted(),
0 == testObj[i].numExecuted() );
}
} else {
// In the highly unlikely event, that one thread could not invoke
// 'cancelEvent' or 'cancelClock' in time to guarantee that the
// event it had scheduled earlier was cancelled, the test fails.
// This can be prevented by increasing the delay (initially T,
// currently T4) with which the event is scheduled. Note that the
// delay T10 with which this test is executed must be increased
// correspondingly.
// The following message will be reported by the nightly build,
// although it will not trigger a failure.
cout << "TIMING FAILURE ERROR IN CASE 10 - INCREASE DELAYS\n";
}
// test if the scheduler is still in good state
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
TestClass1 testObj;
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 9: {
// -----------------------------------------------------------------
// TESTING 'start' and 'stop':
// Verifying 'start' and 'stop'.
//
// Concerns:
//
// That invoking 'start' multiple times is harmless.
//
// That invoking 'stop' multiple times is harmless.
//
// That it is possible to restart the scheduler after stopping
// it.
//
// That invoking 'stop' work correctly even when the dispatcher
// is blocked waiting for any callback to be scheduled.
//
// That invoking 'stop' work correctly even when the dispatcher
// is blocked waiting for the expiration of any scheduled
// callback.
//
// Plan:
// Invoke 'start' multiple times and verify that the scheduler
// is still in good state (this is done by scheduling an event
// and verifying that it is executed as expected).
//
// Invoke 'stop' multiple times and verify that the scheduler is
// still in good state (this is done by starting the scheduler,
// scheduling an event and verifying that it is executed as
// expected).
//
// Restart scheduler after stopping and make sure that the
// scheduler is still in good state (this is done by starting
// the scheduler, scheduling an event and verifying that it is
// executed as expected). Repeat this several time.
//
// Start the scheduler, sleep for a while to ensure that
// scheduler gets blocked, invoke 'stop' and verify that scheduler
// is actually stopped.
//
// Start the scheduler, schedule an event, sleep for a while to
// ensure that scheduler gets blocked, invoke 'stop' before the
// event is expired and verify the state.
//
// Testing:
// int start();
// void stop();
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'start' and 'stop'" << endl
<< "==========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_9;
{
// Invoke 'start' multiple times and verify that the scheduler is
// still in good state (this is done by scheduling an event and
// verifying that it is executed as expected).
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
ASSERT(0 == x.start());
ASSERT(0 == x.start());
TestClass1 testObj;
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT(1 == testObj.numExecuted());
}
{
// Invoke 'stop' multiple times and verify that the scheduler is
// still in good state (this is done by starting the scheduler,
// scheduling an event and verifying that it is executed as
// expected).
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.stop();
x.stop();
ASSERT(0 == x.start());
x.stop();
x.stop();
ASSERT(0 == x.start());
TestClass1 testObj;
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT(1 == testObj.numExecuted());
}
{
// Restart scheduler after stopping and make sure that the
// scheduler is still in good state (this is done by starting the
// scheduler, scheduling an event and verifying that it is executed
// as expected). Repeat this several time.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
ASSERT(0 == x.start());
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT(1 == testObj.numExecuted());
x.stop();
nExec = testObj.numExecuted();
ASSERT(0 == x.start());
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100, nExec);
ASSERT(2 == testObj.numExecuted());
x.stop();
nExec = testObj.numExecuted();
ASSERT(0 == x.start());
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100, nExec);
ASSERT(3 == testObj.numExecuted());
}
{
// Start the scheduler, sleep for a while to ensure that scheduler
// gets blocked, invoke 'stop' and verify that scheduler is
// actually stopped.
const bsls::TimeInterval T(1 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
ASSERT(0 == x.start());
myMicroSleep(T3, 0);
x.stop();
// Make sure that scheduler is stopped.
TestClass1 testObj;
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T3, 0);
ASSERT(0 == testObj.numExecuted());
}
{
// Start the scheduler, schedule an event, sleep for a while to
// ensure that scheduler gets blocked, invoke 'stop' before the
// event is expired and verify the state.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T4(4 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj;
ASSERT(0 == x.start());
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(
now + T4,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
x.stop();
// Make sure that scheduler is stopped, but allow for the
// possibility that myMicroSleep overslept and apply defensive
// techniques.
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T4) {
myMicroSleep(T3, 0);
ASSERT(0 == testObj.numExecuted());
}
// Make *really* sure that scheduler is stopped.
int numExecutedUnchanged = testObj.numExecuted();
x.scheduleEvent(
bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T3, 0);
ASSERT(numExecutedUnchanged == testObj.numExecuted());
}
} break;
case 8: {
// -----------------------------------------------------------------
// TESTING 'bdlmt::TimerEventScheduler(dispatcher, allocator = 0)':
// Verifying 'bdlmt::TimerEventScheduler(dispatcher, allocator = 0)'.
//
// Concerns:
// To test the scheduler with a user-defined dispatcher.
//
// Plan:
// Define a dispatcher that simply executes the specified
// functor. Create a scheduler using this dispatcher, schedule
// an event and make sure that it is executed by the specified
// dispatcher.
//
// Testing:
// bdlmt::TimerEventScheduler(dispatcher, allocator = 0);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'bdlmt::TimerEventScheduler"
<< "(dispatcher, allocator = 0)'" << endl
<< "================================="
<< "============================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_8;
using namespace bdlf::PlaceHolders;
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
bdlmt::TimerEventScheduler::Dispatcher dispatcher =
bdlf::BindUtil::bind(&dispatcherFunction, _1);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(dispatcher, &ta); x.start();
TestClass1 testObj;
x.scheduleEvent(bdlt::CurrentTime::now() + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj));
myMicroSleep(T2, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT( 1 == testObj.numExecuted() );
} break;
case 7: {
// -----------------------------------------------------------------
// TESTING METHODS INVOCATIONS FROM THE DISPATCHER THREAD:
// Verify various methods invocations from the dispatcher thread.
//
// Concerns:
// That it is possible to schedule events and clocks from the
// dispatcher thread.
//
// That when 'cancelEvent' is invoked from the dispatcher thread
// then the wait argument is ignored.
//
// That when 'cancelAllEvent' is invoked from the dispatcher
// thread then the wait argument is ignored.
//
// That when 'cancelClock' is invoked from the dispatcher thread
// then the wait argument is ignored.
//
// That when 'cancelAllClocks' is invoked from the dispatcher
// thread then the wait argument is ignored.
//
// That DRQS 7272737 is solved.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule an event at T2 that itself schedules an event at
// T2+T=T3 and a clock with period T4, verify that callbacks are
// executed as expected.
//
// Schedule an event e1 at time T such that it cancels itself with
// wait argument (this will fail), and an event e2 that will be
// pending when c1 will execute (this is done by waiting long
// enough before starting the scheduler). Make sure no deadlock
// results.
//
// Schedule an event e1 at time T such that it invokes
// 'cancelAllEvents' with wait argument, and another event e2 at
// time T2 that will be pending when e1 will execute (this is done
// by waiting long enough before starting the scheduler). Make
// sure no deadlock results of e1 waiting for e2 to complete (both
// are running in the dispatcher thread).
//
// Schedule a clock c1 such that it cancels itself with wait
// argument (this will fail), and an event e2 that will be pending
// when c1 will execute (this is done by waiting long enough
// before starting the scheduler). Make sure no deadlock results.
//
// Schedule a clock c1 such that it invokes 'cancelAllClocks' with
// wait argument, and an event e2 that will be pending when c1
// will execute (this is done by waiting long enough before
// starting the scheduler). Make sure no deadlock results.
//
// Testing:
// Methods invocations from the dispatcher thread.
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING METHODS INVOCATIONS FROM THE DISPATCHER "
<< "THREAD\n"
<< "================================================"
<< "======\n";
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_7;
typedef void (*Func)();
const Func funcPtrs[] = { &test7_a, &test7_b, &test7_c, &test7_d,
&test7_e, &test7_f };
enum { NUM_THREADS = sizeof funcPtrs / sizeof funcPtrs[0] };
bslmt::ThreadUtil::Handle handles[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::create(&handles[i], funcPtrs[i]));
}
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::join(handles[i]));
}
} break;
case 6: {
// -----------------------------------------------------------------
// TESTING 'cancelAllClocks':
// Verifying 'cancelAllClocks'.
//
// Concerns:
// That if no clock has not yet been put onto the pending list
// then invoking 'cancelAllClocks' should successfully cancel
// all clocks.
//
// That once a clock callback has started its execution, invoking
// 'cancelAllClocks' without wait argument should not block for
// that execution to complete and should cancel its further
// executions. It should also cancel other pending clocks.
//
// That once a clock callback has started its execution, invoking
// 'cancelAllClocks' with wait argument should block for that
// execution to complete and should cancel its further
// executions. It should also cancel other pending clocks.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule clocks starting at T2 and T3, invoke
// 'cancelAllClocks' at time T and make sure that both are
// cancelled successfully.
//
// Schedule clocks c1 at T(which executes for T10 time), c2 at
// T2 and c3 at T3. Let all clocks be simultaneously put onto
// the pending list (this is done by sleeping enough time before
// starting the scheduler). Let c1's first execution be started
// (by sleeping enough time), invoke 'cancelAllClocks' without
// wait argument, verify that c1's first execution has not yet
// completed and verify that c2 and c3 are cancelled without any
// executions.
//
// Schedule clocks c1 at T(which executes for T10 time), c2 at
// T2 and c3 at T3. Let all clocks be simultaneously put onto
// the pending list (this is done by sleeping enough time before
// starting the scheduler). Let c1's first execution be started
// (by sleeping enough time), invoke 'cancelAllClocks' with wait
// argument, verify that c1's first execution has completed and
// verify that c2 and c3 are cancelled without any executions.
//
// Testing:
// void cancelAllClocks(bool wait=false);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'cancelAllClocks'" << endl
<< "=========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_6;
typedef void (*Func)();
const Func funcPtrs[] = { &test6_a, &test6_b, &test6_c };
enum { NUM_THREADS = sizeof funcPtrs / sizeof funcPtrs[0] };
bslmt::ThreadUtil::Handle handles[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::create(&handles[i], funcPtrs[i]));
}
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::join(handles[i]));
}
} break;
case 5: {
// -----------------------------------------------------------------
// TESTING 'cancelClock':
// Verifying 'cancelClock'.
//
// Concerns:
// That if a clock has not yet been put onto the pending list
// then it can successfully be cancelled.
//
// That if a clock callback has been put onto the pending list
// but not yet executed then it can still be cancelled.
//
// That once a clock callback has started its execution,
// cancelling it without wait should not block for that
// execution to complete and should cancel its further
// executions.
//
// That once a clock callback has started its execution,
// cancelling it with wait should block for that execution to
// complete and should cancel its further executions.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule a clock starting at T2, cancel it at time T and
// verify that it has been successfully cancelled.
//
// Schedule two clocks c1 and c2 starting at T and T2. Let both
// be simultaneously put onto the pending list (this is done by
// sleeping enough time before starting the scheduler), cancel
// c2 before it's callback is dispatched and verify the result.
//
// Schedule a clock (whose callback executes for T5 time)
// starting at T. Let its first execution be started (by
// sleeping for T2 time), cancel it without wait argument,
// verify that its execution has not yet completed, make sure
// that it is cancelled after this execution.
//
// Schedule a clock (whose callback executes for T5 time)
// starting at T. Let its first execution be started (by
// sleeping for T2 time), cancel it with wait argument, verify
// that its execution has completed, make sure that it is
// cancelled after this execution.
//
// Testing:
// int cancelClock(Handle handle, bool wait=false);
// -----------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'cancelClock'" << endl
<< "=====================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_5;
{
// Schedule a clock starting at T2, cancel it at time T and verify
// that it has been successfully cancelled.
const int T = 1 * DECI_SEC_IN_MICRO_SEC;
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.startClock(
T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
sleepUntilMs(T / 1000);
bsls::TimeInterval elapsed = bdlt::CurrentTime::now() - now;
if (elapsed < T2) {
ASSERT(0 == x.cancelClock(h));
myMicroSleep(T3, 0);
ASSERT(0 == testObj.numExecuted());
}
}
{
// Schedule two clocks c1 and c2 starting at T and T2. Let both be
// simultaneously put onto the pending list (this is done by
// sleeping enough time before starting the scheduler), cancel c2
// before it's callback is dispatched and verify the result.
bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
const int T20 = 20 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
TestClass1 testObj1(T10);
TestClass1 testObj2;
bsls::TimeInterval now = bdlt::CurrentTime::now();
(void)x.startClock(
T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
Handle h2 = x.startClock(
T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
myMicroSleep(T3, 0);
x.start();
myMicroSleep(T3, 0);
ASSERT(0 == x.cancelClock(h2));
bool cancelledInTime =
(bdlt::CurrentTime::now() - now).totalSecondsAsDouble() < 0.99;
myMicroSleep(T20, 0);
if (cancelledInTime) {
LOOP_ASSERT(testObj2.numExecuted(),
0 == testObj2.numExecuted());
}
}
{
// Schedule a clock (whose callback executes for T5 time) starting
// at T. Let its first execution be started (by sleeping for T2
// time), cancel it without wait argument, verify that its
// execution has not yet completed, make sure that it is cancelled
// after this execution.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const int T5 = 5 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj(T5);
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.startClock(
T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
ASSERT(0 == x.cancelClock(h));
if ((bdlt::CurrentTime::now() - now).totalSecondsAsDouble() <
0.59) {
ASSERT(0 == testObj.numExecuted());
myMicroSleep(T5, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
ASSERT(1 == testObj.numExecuted());
}
}
{
// Schedule a clock (whose callback executes for T5 time) starting
// at T. Let its first execution be started (by sleeping for T2
// time), cancel it with wait argument, verify that its execution
// has completed, make sure that it is cancelled after this
// execution.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
bsls::TimeInterval T(1 * DECI_SEC);
const int T2 = 2 * DECI_SEC_IN_MICRO_SEC;
const int T5 = 5 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta);
x.start();
TestClass1 testObj(T5);
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h = x.startClock(
T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
myMicroSleep(T2, 0);
int wait = 1;
ASSERT(0 == x.cancelClock(h, wait));
int numEx = testObj.numExecuted();
if ((bdlt::CurrentTime::now() - now).totalSecondsAsDouble() <
0.59) {
LOOP_ASSERT(testObj.numExecuted(), 1 == numEx);
}
myMicroSleep(T5, 0);
makeSureTestObjectIsExecuted(testObj, mT, 100);
LOOP2_ASSERT(numEx, testObj.numExecuted(),
numEx == testObj.numExecuted());
}
} break;
case 4: {
// --------------------------------------------------------------------
// TESTING 'cancelAllEvents':
// Verifying 'cancelAllEvents'.
//
// Concerns:
// That if no event has yet been put onto the pending list, then
// invoking 'cancelAllEvents' should be able to cancel all
// events.
//
// That 'cancelAllEvents' without wait argument should
// immediately cancel the events not yet put onto the pending
// list and should not wait for events on the pending list to be
// executed.
//
// That 'cancelAllEvents' with wait argument should cancel the
// events not yet put onto the pending list and should wait for
// events on the pending list to be executed.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule events at T, T2 and T3, invoke 'cancelAllEvents' and
// verify the result.
//
// Schedule events e1, e2 and e3 at T, T2 and T8 respectively.
// Let both e1 and e2 be simultaneously put onto the pending
// list (this is done by sleeping enough time before starting
// the scheduler). Invoke 'cancelAllEvents' and ensure that it
// cancels e3 and does not wait for e1 and e2 to complete their
// execution.
//
// Schedule events e1, e2 and e3 at T, T2 and T8 respectively.
// Let both e1 and e2 be simultaneously put onto the pending
// list (this is done by sleeping enough time before starting
// the scheduler). Invoke 'cancelAllEvents' with wait argument
// and ensure that it cancels e3 and wait for e1 and e2 to
// complete their execution.
//
// Testing:
// void cancelAllEvents(bool wait=false);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'cancelAllEvents'" << endl
<< "=========================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_4;
{
// Schedule events at T, T2 and T3, invoke 'cancelAllEvents' and
// verify the result.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T3(3 * DECI_SEC);
bslma::TestAllocator ta(veryVeryVerbose);
Obj x(&ta); x.start();
TestClass1 testObj1;
TestClass1 testObj2;
TestClass1 testObj3;
bsls::TimeInterval now = bdlt::CurrentTime::now();
Handle h1 = x.scheduleEvent(
now + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj1));
Handle h2 = x.scheduleEvent(
now + T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj2));
Handle h3 = x.scheduleEvent(
now + T3,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj3));
x.cancelAllEvents();
ASSERT( 0 != x.cancelEvent(h1) );
ASSERT( 0 != x.cancelEvent(h2) );
ASSERT( 0 != x.cancelEvent(h3) );
}
{
// Schedule a few events in the past and one in the future. The
// second event will take a long time. Sleep long enough to get
// the events in the past pending, but not the one in the future.
// CancelAllEvents without 'wait' specified. Verify that the
// appropriate events got canceled. So as not to be thrown off by
// intermittent excessively long sleeps, be prepared to start this
// test over a certain number of times before giving up.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T7(7 * DECI_SEC);
// This will not be put onto the pending list.
const int mT = DECI_SEC_IN_MICRO_SEC / 10; // 10ms
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
const int T20 = 20 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
int ii;
enum { MAX_LOOP = 4 };
for (ii = 0; ii <= MAX_LOOP; ++ii) {
TestClass1 testObj0;
TestClass1 testObj1(T10);
TestClass1 testObj2;
TestClass1 testObj3;
Obj x(&ta);
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(now - (T2 + T),
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj0));
x.scheduleEvent(now - T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
x.scheduleEvent(now - T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
x.scheduleEvent(now + T7,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj3));
now = bdlt::CurrentTime::now();
x.start();
myMicroSleep(T3, 0); // give enough time to put on pending list
x.cancelAllEvents();
if ( 0 == testObj0.numExecuted() ) {
if (veryVerbose || MAX_LOOP == ii) {
P_(L_) Q(Events did not get on pending list);
}
continue; // events did not get on pending list, start over
}
if ((bdlt::CurrentTime::now() -
now).totalSecondsAsDouble() > 0.59) {
if (veryVerbose || MAX_LOOP == ii) {
P_(L_) Q(Overslept);
}
continue; // overslept, start over
}
ASSERT( 1 == testObj0.numExecuted() );
ASSERT( 0 == testObj1.numExecuted() );
ASSERT( 0 == testObj2.numExecuted() );
ASSERT( 0 == testObj3.numExecuted() );
makeSureTestObjectIsExecuted(testObj1, mT, 100);
myMicroSleep(T3, 0);
ASSERT( 1 == testObj0.numExecuted() );
ASSERT( 1 == testObj1.numExecuted() );
ASSERT( 1 == testObj2.numExecuted() );
ASSERT( 0 == testObj3.numExecuted() );
break;
}
ASSERT(ii <= MAX_LOOP);
if (veryVerbose) { P_(L_) P(ii); }
}
{
// Schedule a few events in the past and one in the future. The
// second event will take a long time. Sleep long enough to get
// the events in the past pending, but not the one in the future.
// CancelAllEvents with 'wait' specified. Verify that the
// appropriate events got canceled. So as not to be thrown off by
// intermittent excessively long sleeps, be prepared to start this
// test over a certain number of times before giving up.
const bsls::TimeInterval T(1 * DECI_SEC);
const bsls::TimeInterval T2(2 * DECI_SEC);
const bsls::TimeInterval T6(6 * DECI_SEC);
const bsls::TimeInterval T7(7 * DECI_SEC);
const int T3 = 3 * DECI_SEC_IN_MICRO_SEC;
const int T10 = 10 * DECI_SEC_IN_MICRO_SEC;
const int T20 = 20 * DECI_SEC_IN_MICRO_SEC;
bslma::TestAllocator ta(veryVeryVerbose);
int ii;
enum { MAX_LOOP = 4 };
for (ii = 0; ii <= MAX_LOOP; ++ii) {
Obj x(&ta);
TestClass1 testObj0;
TestClass1 testObj1(T10);
TestClass1 testObj2;
TestClass1 testObj3;
bsls::TimeInterval now = bdlt::CurrentTime::now();
x.scheduleEvent(now - (T + T2),
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj0));
x.scheduleEvent(now - T2,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj1));
x.scheduleEvent(now - T,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj2));
x.scheduleEvent(now + T7,
bdlf::MemFnUtil::memFn(&TestClass1::callback,
&testObj3));
x.start();
myMicroSleep(T3, 0); // give enough time to put on pending list
if ( 0 == testObj0.numExecuted() ) {
if (verbose || MAX_LOOP == ii) {
P_(L_) Q(Events not pending);
}
continue;
}
if (bdlt::CurrentTime::now() - now >= T6) {
if (verbose || MAX_LOOP == ii) {
P_(L_) Q(Overslept);
}
continue;
}
int wait = 1;
x.cancelAllEvents(wait);
ASSERT( 1 == testObj1.numExecuted() );
ASSERT( 1 == testObj2.numExecuted() );
ASSERT( 0 == testObj3.numExecuted() );
myMicroSleep(T10, 0);
ASSERT( 0 == testObj3.numExecuted() );
break;
}
ASSERT(ii <= MAX_LOOP);
if (verbose) { P_(L_) P(ii); }
}
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING 'cancelEvent':
// Verifying 'cancelEvent'.
//
// Concerns:
// That if an event has not yet been put onto the pending list,
// then it can successfully be cancelled.
//
// That once an event has been put onto the pending list, it can
// not be cancelled from a non-dispatcher thread.
//
// That once an event has been put onto the pending list, it can
// not be cancelled from a non-dispatcher thread.
//
// That if the dispatcher thread cancels an event that has not
// yet been put onto the pending list then it should succeed.
//
// That if the dispatcher thread cancels an event that has
// already been executed then it should fail.
//
// That an event can not cancel itself.
//
// That if the dispatcher thread cancels an event that has been
// put onto the pending list but not yet executed, then the
// cancellation should succeed.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule an event at T2, cancel it at time T and verify the
// result.
//
// Schedule 2 events at T and T2. Let both be simultaneously put
// onto the pending list (this is done by sleeping enough time
// before starting the scheduler), invoke 'cancelEvent(handle)'
// on the second event while it is still on pending list and
// verify that cancel fails.
//
// Schedule 2 events at T and T2. Let both be simultaneously put
// onto the pending list (this is done by sleeping enough time
// before starting the scheduler), invoke 'cancelEvent(handle,
// wait)' on the second event while it is still on pending list
// and verify that cancel fails.
//
// Schedule events e1 and e2 at T and T2 respectively, cancel
// e2 from e1 and verify that cancellation succeed.
//
// Schedule events e1 and e2 at T and T2 respectively, cancel
// e1 from e2 and verify that cancellation fails.
//
// Schedule an event that invokes cancel on itself. Verify that
// cancellation fails.
//
// Schedule e1 and e2 at T and T2 respectively. Let both be
// simultaneously put onto the pending list (this is done by
// sleeping enough time before starting the scheduler), cancel
// e2 from e1 and verify that it succeeds.
//
// Note:
// Defensive programming: myMicroSleep can (and does sometimes,
// especially when load is high during nightly builds) oversleep, so
// all assumptions have to be checked against the actual elapsed
// time.
//
// Testing:
// int cancelEvent(Handle handle, bool wait=false);
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'cancelEvent'" << endl
<< "=====================" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_3;
typedef void (*Func)();
const Func funcPtrs[] = { &test3_a, &test3_b, &test3_c, &test3_d,
&test3_e, &test3_f, &test3_g };
enum { NUM_THREADS = sizeof funcPtrs / sizeof funcPtrs[0] };
bslmt::ThreadUtil::Handle handles[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::create(&handles[i], funcPtrs[i]));
}
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::join(handles[i]));
}
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING 'scheduleEvent' and 'startClock':
// Verifying 'scheduleEvent' and 'startClock'.
//
// Concerns:
// That multiple clocks and multiple events can be scheduled.
//
// That when a scheduler runs a *very long* running callback
// then callbacks scheduled after that callback are shifted as
// expected.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Schedule multiple clocks and multiple events and verify that
// their callback executes at appropriate times.
//
// Schedule a long running callback and several other callbacks.
// Verify that other callbacks are shifted as expected.
//
// Note:
// Test sometimes fail due to too much thread contention in parallel
// testing with high load. This is not necessarily a test failure,
// but reflects stressed conditions. We try to be as defensive as we
// can, and start long after the scheduling to allow settling down of
// threads. In addition, we run the test several times or until it
// succeeds a minimum number of times (threshold). We consider the
// first outcome a failure (and assert, in order to still catch
// systematic failures should the code regress), but we let the
// second outcome be a success although some runs may have failed.
// In that case, we report the results for nightly build diagnostics,
// but do not generate a test failure.
//
// Testing:
// Handle scheduleEvent(time, callback);
// Handle startClock(interval, callback,
// startTime=bsls::TimeInterval(0));
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "TESTING 'scheduleEvent' and 'startClock'" << endl
<< "========================================" << endl;
const int ATTEMPTS = 9;
const int SUCCESS_THRESHOLD = 1;
const int ALLOWED_DEVIATIONS = 1;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_2;
{
// schedule multiple clocks and multiple events and verify that
// their callbacks execute at appropriate times.
static const testCase2Data DATA[] = {
//line no. start isClock interval executionTime delayed
//------- ----- ------- -------- ------------- -------
{ L_, 1, true, 10, 0, false },
{ L_, 2, true, 10, 0, false },
{ L_, 3, true, 10, 0, false },
{ L_, 4, true, 10, 0, false },
{ L_, 5, true, 10, 0, false },
{ L_, 6, false, 0, 0, false },
{ L_, 7, false, 0, 0, false },
{ L_, 8, false, 0, 0, false },
{ L_, 9, false, 0, 0, false },
{ L_, 16, false, 0, 0, false },
{ L_, 17, false, 0, 0, false },
{ L_, 18, false, 0, 0, false },
{ L_, 19, false, 0, 0, false },
{ L_, 26, false, 0, 0, false },
{ L_, 27, false, 0, 0, false },
{ L_, 28, false, 0, 0, false },
{ L_, 29, false, 0, 0, false },
{ L_, 36, false, 0, 0, false },
{ L_, 37, false, 0, 0, false },
{ L_, 38, false, 0, 0, false },
{ L_, 39, false, 0, 0, false },
{ L_, 46, false, 0, 0, false },
{ L_, 47, false, 0, 0, false },
{ L_, 48, false, 0, 0, false },
{ L_, 49, false, 0, 0, false }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
const float TOTAL_TIME = 29.;
TestClass *testObjects[NUM_DATA];
int passed = 0, failed = 0, deviations = 0;
for (int i = 0; passed < SUCCESS_THRESHOLD && i < ATTEMPTS; ++i)
{
deviations = 0;
if (testCallbacks(&deviations,
TOTAL_TIME,
DATA,
NUM_DATA,
testObjects) ||
deviations <= ALLOWED_DEVIATIONS) {
++passed;
if (verbose)
cout << " Test case 2: PASSED\n";
} else {
++failed;
if (verbose)
cout << " Test case 2: FAILED (deviation "
<< deviations << ")\n";
}
}
if (passed < SUCCESS_THRESHOLD) {
// Run one more time and let LOOP_ASSERT report the failures.
// If this should succeed, then count it towards the successes
// and run again, until either failure or enough successes.
while (testCallbacks(0,
TOTAL_TIME,
DATA,
NUM_DATA,
testObjects)) {
++passed;
if (verbose)
cout << " Test case 2: PASSED\n";
if (passed == SUCCESS_THRESHOLD) {
break; // while loop
}
}
}
if (passed < SUCCESS_THRESHOLD) {
++failed; // for the additional failure in the while loop above
cout << "Failed test case 2 " << failed
<< " out of " << passed+failed << " times.\n";
ASSERT( 0 );
}
}
{
// schedule a long running callback and several other callbacks.
// Verify that other callbacks are shifted as expected.
static const testCase2Data DATA[] = {
//line no. start isClock interval executionTime delayed
//------- ----- ------- -------- ------------- --------
// a long running callback
{ L_, 1, false, 0, 10, false },
{ L_, 2, false, 0, 0, true },
{ L_, 4, false, 0, 0, true },
{ L_, 6, false, 0, 0, true },
{ L_, 8, false, 0, 0, true },
{ L_, 3, true, 10, 0, true },
{ L_, 5, true, 10, 0, true },
{ L_, 7, true, 10, 0, true }
};
const int NUM_DATA = sizeof DATA / sizeof *DATA;
const float TOTAL_TIME = 12.;
TestClass *testObjects[NUM_DATA];
int passed = 0, failed = 0, deviations = 0;
for (int i = 0; passed < SUCCESS_THRESHOLD && i < ATTEMPTS; ++i) {
deviations = 0;
if (testCallbacks(&deviations,
TOTAL_TIME,
DATA,
NUM_DATA,
testObjects) ||
deviations <= ALLOWED_DEVIATIONS) {
++passed;
if (verbose)
cout << " Test case 2: PASSED\n";
} else {
++failed;
if (verbose)
cout << " Test case 2: FAILED (deviation "
<< deviations << ")\n";
}
}
if (passed < SUCCESS_THRESHOLD) {
// Run one more time and let LOOP_ASSERT report the failures.
// If this should succeed, then count it towards the successes
// and run again, until either failure or enough successes.
while (testCallbacks(0,
TOTAL_TIME,
DATA,
NUM_DATA,
testObjects)) {
++passed;
if (verbose)
cout << " Test case 2: PASSED\n";
if (passed == SUCCESS_THRESHOLD) {
break; // while loop
}
}
}
if (passed < SUCCESS_THRESHOLD) {
++failed; // for the additional failure in the while loop above
cout << "Failed test case 2 " << failed
<< " out of " << passed+failed << " times.\n";
ASSERT( 0 );
}
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// Exercise the basic functionality.
//
// Concerns:
// That basic essential functionality is operational
// for one thread.
//
// Plan:
// Define T, T2, T3, T4 .. as time intervals such that T2 = T * 2,
// T3 = T * 3, T4 = T * 4, and so on.
//
// Create and start a scheduler object, schedule an event at T2,
// verify that it is not executed at T but is executed at T3.
//
// Create and start a scheduler object, schedule 2 events at
// different times, verify that they execute at expected time.
//
// Create and start a scheduler object, schedule a clock of T3
// interval, verify that clock callback gets invoked at expected
// times.
//
// Create and start a scheduler object, schedule a clock of T3
// interval, schedule an event of at T3. Verify that event and
// clock callbacks are being invoked at expected times.
//
// Create and start a scheduler object, schedule an event at
// T2, cancel it at T and verify that it is cancelled. Verify
// that cancelling it again results in failure.
//
// Create and start a scheduler object, schedule an event at
// T2, cancelling it at T3 should result in failure.
//
// Create and start a scheduler object, schedule 3 events at T,
// T2, T3. Invoke 'cancelAllEvents' and verify it.
//
// Create and start a scheduler object, schedule a clock of T3,
// let it execute once and then cancel it and then verify the
// expected result.
//
// Create and start a scheduler object, schedule two clocks of
// T3 interval, invoke 'cancelAllClocks' and verify the result.
//
// Create and start a scheduler object, schedule a clock of T3
// interval, schedule an event at T6, invoke 'stop' at T4 and
// then verify the state. Invoke 'start' and then verify the
// state.
//
// Note:
// Defensive programming: myMicroSleep can (and does sometimes,
// especially when load is high during nightly builds) oversleep, so
// all assumptions have to be checked against the actual elapsed
// time. The function 'makeSureTestObjectIsExecuted' also helps in
// making sure that the dispatcher thread has a good chance to
// process timers and clocks.
//
// Testing:
// This Test Case exercises basic functionality.
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "BREATHING TEST" << endl
<< "==============" << endl;
using namespace TIMER_EVENT_SCHEDULER_TEST_CASE_1;
typedef void (*Func)();
const Func funcPtrs[] = { &test1_a, &test1_b, &test1_c, &test1_d,
&test1_e, &test1_f, &test1_g, &test1_h,
&test1_i, &test1_j, &test1_k };
enum { NUM_THREADS = sizeof funcPtrs / sizeof funcPtrs[0] };
bslmt::ThreadUtil::Handle handles[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::create(&handles[i], funcPtrs[i]));
}
for (int i = 0; i < NUM_THREADS; ++i) {
ASSERT(0 == bslmt::ThreadUtil::join(handles[i]));
}
} break;
case -1: {
// --------------------------------------------------------------------
// SYSTEM CLOCK CHANGES CAUSE EXPECTED BEHAVIOR
//
// Concerns:
//: 1 Changes to the system clock must not affect the behavior of the
//: component when the monotonic clock is used.
//
// Plan:
//: 1 Use the realtime clock first, verify changes to the system clock
//: do affect the behavior, and then repeat the test with a monotonic
//: clock and manually verify no effect on behavior.
//
// Testing:
// SYSTEM CLOCK CHANGES CAUSE EXPECTED BEHAVIOR
// --------------------------------------------------------------------
if (verbose) {
cout << "SYSTEM CLOCK CHANGES CAUSE EXPECTED BEHAVIOR" << endl
<< "============================================" << endl;
}
{
cout << "\n"
"\nFirst, a realtime clock will be used to verify"
"\nunexpected behavior during a system clock"
"\nchange (this test will continue until this"
"\nproblem is detected; *you* must move the system"
"\ntime backwards)."
"\n";
Obj x(bsls::SystemClockType::e_REALTIME);
x.start();
TestClass1 testObj;
bsls::TimeInterval currentTime =
bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME);
for (int i = 1; i <= 300; ++i) {
const bsls::TimeInterval T(static_cast<double>(i));
x.scheduleEvent(
currentTime + T,
bdlf::MemFnUtil::memFn(&TestClass1::callback, &testObj));
}
int numExecuted = -1;
while (numExecuted < testObj.numExecuted()) {
numExecuted = testObj.numExecuted();
myMicroSleep(200000, 1); // 1.2 seconds
}
x.cancelAllEvents(true);
}
{
cout << "\n"
"\nExcellent! The expected behavior occurred. For"
"\nthe second part of the test, a monotonic clock"
"\nwill be used. Here, a message will be printed"
"\nevery second and if the messages stop printing"
"\nbefore iteration 300 while you are changing the"
"\nsystem time there is an issue. You may use"
"\nCNTRL-C to exit this test at any time. The test"
"\nwill begin in three seconds; do not change the"
"\nsystem time until after you see the first printed"
"\nmessage."
"\n";
myMicroSleep(0, 3); // 3 seconds
Obj x(bsls::SystemClockType::e_MONOTONIC);
x.start();
TestPrintClass testObj;
bsls::TimeInterval currentTime =
bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC);
for (int i = 1; i <= 300; ++i) {
const bsls::TimeInterval T(static_cast<double>(i));
x.scheduleEvent(
currentTime + T,
bdlf::MemFnUtil::memFn(&TestPrintClass::callback, &testObj));
}
int numExecuted = -1;
while (numExecuted < testObj.numExecuted()) {
numExecuted = testObj.numExecuted();
myMicroSleep(200000, 1); // 1.2 seconds
}
x.cancelAllEvents(true);
}
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
}
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| idispatch/bde | groups/bdl/bdlmt/bdlmt_timereventscheduler.t.cpp | C++ | apache-2.0 | 192,172 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.camel.component.rabbitmq.integration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.rabbitmq.RabbitMQConstants;
import org.apache.camel.support.ObjectHelper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.test.junit5.TestSupport.assertListSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class RabbitMQProducerIntTest extends AbstractRabbitMQIntTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQProducerIntTest.class);
private static final String EXCHANGE = "ex1";
private static final String ROUTE = "route1";
private static final String CUSTOM_HEADER = "CustomHeader";
private static final String BASIC_URI_FORMAT
= "rabbitmq:localhost:5672/%s?routingKey=%s&username=cameltest&password=cameltest&skipQueueDeclare=true";
private static final String BASIC_URI = String.format(BASIC_URI_FORMAT, EXCHANGE, ROUTE);
private static final String ALLOW_NULL_HEADERS = BASIC_URI + "&allowNullHeaders=true&allowCustomHeaders=false";
private static final String ALLOW_CUSTOM_HEADERS = BASIC_URI + "&allowCustomHeaders=true";
private static final String PUBLISHER_ACKNOWLEDGES_URI = BASIC_URI + "&mandatory=true&publisherAcknowledgements=true";
private static final String PUBLISHER_ACKNOWLEDGES_BAD_ROUTE_URI
= String.format(BASIC_URI_FORMAT, EXCHANGE, "route2") + "&publisherAcknowledgements=true";
private static final String GUARANTEED_DELIVERY_URI = BASIC_URI + "&mandatory=true&guaranteedDeliveries=true";
private static final String GUARANTEED_DELIVERY_BAD_ROUTE_NOT_MANDATORY_URI
= String.format(BASIC_URI_FORMAT, EXCHANGE, "route2") + "&guaranteedDeliveries=true";
private static final String GUARANTEED_DELIVERY_BAD_ROUTE_URI
= String.format(BASIC_URI_FORMAT, EXCHANGE, "route2") + "&mandatory=true&guaranteedDeliveries=true";
@Produce("direct:start")
protected ProducerTemplate template;
@Produce("direct:start-allow-null-headers")
protected ProducerTemplate templateAllowNullHeaders;
@Produce("direct:start-not-allow-custom-headers")
protected ProducerTemplate templateNotAllowCustomHeaders;
@Produce("direct:start-allow-custom-headers")
protected ProducerTemplate templateAllowCustomHeaders;
@Produce("direct:start-with-confirms")
protected ProducerTemplate templateWithConfirms;
@Produce("direct:start-with-confirms-bad-route")
protected ProducerTemplate templateWithConfirmsAndBadRoute;
@Produce("direct:start-with-guaranteed-delivery")
protected ProducerTemplate templateWithGuranteedDelivery;
@Produce("direct:start-with-guaranteed-delivery-bad-route")
protected ProducerTemplate templateWithGuranteedDeliveryAndBadRoute;
@Produce("direct:start-with-guaranteed-delivery-bad-route-but-not-mandatory")
protected ProducerTemplate templateWithGuranteedDeliveryBadRouteButNotMandatory;
private Connection connection;
private Channel channel;
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
context().setTracing(true);
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to(BASIC_URI);
from("direct:start-allow-null-headers").to(ALLOW_NULL_HEADERS);
from("direct:start-not-allow-custom-headers").to(ALLOW_NULL_HEADERS);
from("direct:start-allow-custom-headers").to(ALLOW_CUSTOM_HEADERS);
from("direct:start-with-confirms").to(PUBLISHER_ACKNOWLEDGES_URI);
from("direct:start-with-confirms-bad-route").to(PUBLISHER_ACKNOWLEDGES_BAD_ROUTE_URI);
from("direct:start-with-guaranteed-delivery").to(GUARANTEED_DELIVERY_URI);
from("direct:start-with-guaranteed-delivery-bad-route").to(GUARANTEED_DELIVERY_BAD_ROUTE_URI);
from("direct:start-with-guaranteed-delivery-bad-route-but-not-mandatory")
.to(GUARANTEED_DELIVERY_BAD_ROUTE_NOT_MANDATORY_URI);
}
};
}
@BeforeEach
public void setUpRabbitMQ() throws Exception {
connection = connection();
channel = connection.createChannel();
channel.queueDeclare("sammyq", true, false, false, null);
channel.queueBind("sammyq", EXCHANGE, ROUTE);
}
@AfterEach
public void tearDownRabbitMQ() throws Exception {
channel.abort();
connection.abort();
}
@Test
public void producedMessageIsReceived() throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));
template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
assertThatBodiesReceivedIn(received, "new message");
}
@Test
public void producedMessageWithNotNullHeaders() throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
final Map<String, Object> receivedHeaders = new HashMap<>();
Map<String, Object> headers = new HashMap<>();
headers.put(RabbitMQConstants.EXCHANGE_NAME, EXCHANGE);
headers.put(CUSTOM_HEADER, CUSTOM_HEADER.toLowerCase());
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received, receivedHeaders));
template.sendBodyAndHeaders("new message", headers);
assertThatBodiesAndHeadersReceivedIn(receivedHeaders, headers, received, "new message");
}
@Test
public void producedMessageAllowNullHeaders() throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
final Map<String, Object> receivedHeaders = new HashMap<>();
Map<String, Object> headers = new HashMap<>();
headers.put(RabbitMQConstants.EXCHANGE_NAME, null);
headers.put(CUSTOM_HEADER, null);
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received, receivedHeaders));
templateAllowNullHeaders.sendBodyAndHeaders("new message", headers);
assertThatBodiesAndHeadersReceivedIn(receivedHeaders, headers, received, "new message");
}
@Test
public void producedMessageNotAllowCustomHeaders() throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
final Map<String, Object> receivedHeaders = new HashMap<>();
Map<String, Object> headers = new HashMap<>();
headers.put(RabbitMQConstants.EXCHANGE_NAME, "testa");
headers.put(CUSTOM_HEADER, "exchange");
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received, receivedHeaders));
templateNotAllowCustomHeaders.sendBodyAndHeaders("new message", headers);
Thread.sleep(500);
assertEquals(received.get(0), "new message");
assertTrue(receivedHeaders.containsKey(RabbitMQConstants.EXCHANGE_NAME));
assertFalse(receivedHeaders.containsKey(CUSTOM_HEADER));
}
@Test
public void producedMessageAllowCustomHeaders() throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
final Map<String, Object> receivedHeaders = new HashMap<>();
Map<String, Object> headers = new HashMap<>();
headers.put(RabbitMQConstants.EXCHANGE_NAME, "testa");
headers.put(CUSTOM_HEADER, "exchange");
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received, receivedHeaders));
templateAllowCustomHeaders.sendBodyAndHeaders("new message", headers);
Thread.sleep(500);
assertEquals(received.get(0), "new message");
assertTrue(receivedHeaders.containsKey(RabbitMQConstants.EXCHANGE_NAME));
assertTrue(receivedHeaders.containsKey(CUSTOM_HEADER));
}
private void assertThatBodiesReceivedIn(final List<String> received, final String... expected) throws InterruptedException {
Thread.sleep(500);
assertListSize(received, expected.length);
for (String body : expected) {
assertEquals(body, received.get(0));
}
}
private void assertThatBodiesAndHeadersReceivedIn(
Map<String, Object> receivedHeaders, Map<String, Object> expectedHeaders, final List<String> received,
final String... expected)
throws InterruptedException {
Thread.sleep(500);
assertListSize(received, expected.length);
for (String body : expected) {
assertEquals(body, received.get(0));
}
for (Map.Entry<String, Object> headers : expectedHeaders.entrySet()) {
Object receivedValue = receivedHeaders.get(headers.getKey());
Object expectedValue = headers.getValue();
assertTrue(receivedHeaders.containsKey(headers.getKey()), "Header key " + headers.getKey() + " not found");
assertEquals(0, ObjectHelper.compare(receivedValue == null ? "" : receivedValue.toString(),
expectedValue == null ? "" : expectedValue.toString()));
}
}
@Test
public void producedMessageIsReceivedWhenPublisherAcknowledgementsAreEnabled()
throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));
templateWithConfirms.sendBodyAndHeader("publisher ack message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
assertThatBodiesReceivedIn(received, "publisher ack message");
}
@Test
public void producedMessageIsReceivedWhenPublisherAcknowledgementsAreEnabledAndBadRoutingKeyIsUsed()
throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));
templateWithConfirmsAndBadRoute.sendBody("publisher ack message");
assertThatBodiesReceivedIn(received);
}
@Test
public void shouldSuccessfullyProduceMessageWhenGuaranteedDeliveryIsActivatedAndMessageIsMarkedAsMandatory()
throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));
templateWithGuranteedDelivery.sendBodyAndHeader("publisher ack message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
assertThatBodiesReceivedIn(received, "publisher ack message");
}
@Test
public void shouldFailIfMessageIsMarkedAsMandatoryAndGuaranteedDeliveryIsActiveButNoQueueIsBound() {
assertThrows(RuntimeCamelException.class,
() -> templateWithGuranteedDeliveryAndBadRoute.sendBody("publish with ack and return message"));
}
@Test
public void shouldSuccessfullyProduceMessageWhenGuaranteedDeliveryIsActivatedOnABadRouteButMessageIsNotMandatory()
throws InterruptedException, IOException, TimeoutException {
final List<String> received = new ArrayList<>();
channel.basicConsume("sammyq", true, new ArrayPopulatingConsumer(received));
templateWithGuranteedDeliveryBadRouteButNotMandatory.sendBodyAndHeader("publisher ack message",
RabbitMQConstants.EXCHANGE_NAME, "ex1");
assertThatBodiesReceivedIn(received);
}
private class ArrayPopulatingConsumer extends DefaultConsumer {
private final List<String> received;
private final Map<String, Object> receivedHeaders;
ArrayPopulatingConsumer(final List<String> received) {
super(RabbitMQProducerIntTest.this.channel);
this.received = received;
receivedHeaders = new HashMap<>();
}
ArrayPopulatingConsumer(final List<String> received, Map<String, Object> receivedHeaders) {
super(RabbitMQProducerIntTest.this.channel);
this.received = received;
this.receivedHeaders = receivedHeaders;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
LOGGER.info("AMQP.BasicProperties: {}", properties);
receivedHeaders.putAll(properties.getHeaders());
received.add(new String(body));
}
}
}
| adessaigne/camel | components/camel-rabbitmq/src/test/java/org/apache/camel/component/rabbitmq/integration/RabbitMQProducerIntTest.java | Java | apache-2.0 | 14,304 |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* 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 com.vaadin.v7.tests.components.tree;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Actions;
import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.tests.tb3.MultiBrowserTest;
/**
* Test for keyboard navigation in tree in case when there are no items to
* navigate.
*
* @author Vaadin Ltd
*/
public class TreeKeyboardNavigationToNoneTest extends MultiBrowserTest {
@Before
public void setUp() {
setDebug(true);
openTestURL();
}
@Test
public void navigateUpForTheFirstItem() {
sendKey(Keys.ARROW_UP);
checkNotificationErrorAbsence("first");
}
@Test
public void navigateDownForTheLastItem() {
$(ButtonElement.class).first().click();
sendKey(Keys.ARROW_DOWN);
checkNotificationErrorAbsence("last");
}
private void checkNotificationErrorAbsence(String item) {
Assert.assertFalse(
"Notification is found after using keyboard for navigation "
+ "from " + item + " tree item",
isElementPresent(By.className("v-Notification")));
}
private void sendKey(Keys key) {
Actions actions = new Actions(getDriver());
actions.sendKeys(key).build().perform();
}
}
| peterl1084/framework | uitest/src/test/java/com/vaadin/v7/tests/components/tree/TreeKeyboardNavigationToNoneTest.java | Java | apache-2.0 | 1,995 |
'use strict';
const router = require('express').Router();
const inviteCtrl = require('./inviteController');
router.post('/sendInviteEmail', inviteCtrl.sendInviteEmail);
router.get('/followQuestion', inviteCtrl.followQuestion);
router.post('/sendInviteTopicEmail', inviteCtrl.sendInviteTopicEmail);
router.get('/followTopic', inviteCtrl.followTopic);
module.exports = router;
| stackroute-immersive-wave/Zynla | server/followinvite/inviteRouter.js | JavaScript | apache-2.0 | 393 |
defineSuite([
'Scene/Expression',
'Core/Cartesian2',
'Core/Cartesian3',
'Core/Cartesian4',
'Core/Color',
'Core/Math',
'Scene/ExpressionNodeType'
], function(
Expression,
Cartesian2,
Cartesian3,
Cartesian4,
Color,
CesiumMath,
ExpressionNodeType) {
'use strict';
var frameState = {};
function MockFeature() {
this._properties = {};
this._className = undefined;
this._inheritedClassName = undefined;
this.content = {
tileset : {
timeSinceLoad : 0.0
}
};
}
MockFeature.prototype.addProperty = function(name, value) {
this._properties[name] = value;
};
MockFeature.prototype.getProperty = function(name) {
return this._properties[name];
};
MockFeature.prototype.setClass = function(className) {
this._className = className;
};
MockFeature.prototype.setInheritedClass = function(className) {
this._inheritedClassName = className;
};
MockFeature.prototype.isExactClass = function(className) {
return this._className === className;
};
MockFeature.prototype.isClass = function(className) {
return (this._className === className) || (this._inheritedClassName === className);
};
MockFeature.prototype.getExactClassName = function() {
return this._className;
};
it('parses backslashes', function() {
var expression = new Expression('"\\he\\\\\\ll\\\\o"');
expect(expression.evaluate(frameState, undefined)).toEqual('\\he\\\\\\ll\\\\o');
});
it('evaluates variable', function() {
var feature = new MockFeature();
feature.addProperty('height', 10);
feature.addProperty('width', 5);
feature.addProperty('string', 'hello');
feature.addProperty('boolean', true);
feature.addProperty('vector', Cartesian3.UNIT_X);
feature.addProperty('null', null);
feature.addProperty('undefined', undefined);
var expression = new Expression('${height}');
expect(expression.evaluate(frameState, feature)).toEqual(10);
expression = new Expression('\'${height}\'');
expect(expression.evaluate(frameState, feature)).toEqual('10');
expression = new Expression('${height}/${width}');
expect(expression.evaluate(frameState, feature)).toEqual(2);
expression = new Expression('${string}');
expect(expression.evaluate(frameState, feature)).toEqual('hello');
expression = new Expression('\'replace ${string}\'');
expect(expression.evaluate(frameState, feature)).toEqual('replace hello');
expression = new Expression('\'replace ${string} multiple ${height}\'');
expect(expression.evaluate(frameState, feature)).toEqual('replace hello multiple 10');
expression = new Expression('"replace ${string}"');
expect(expression.evaluate(frameState, feature)).toEqual('replace hello');
expression = new Expression('\'replace ${string\'');
expect(expression.evaluate(frameState, feature)).toEqual('replace ${string');
expression = new Expression('${boolean}');
expect(expression.evaluate(frameState, feature)).toEqual(true);
expression = new Expression('\'${boolean}\'');
expect(expression.evaluate(frameState, feature)).toEqual('true');
expression = new Expression('${vector}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian3.UNIT_X);
expression = new Expression('\'${vector}\'');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian3.UNIT_X.toString());
expression = new Expression('${null}');
expect(expression.evaluate(frameState, feature)).toEqual(null);
expression = new Expression('\'${null}\'');
expect(expression.evaluate(frameState, feature)).toEqual('');
expression = new Expression('${undefined}');
expect(expression.evaluate(frameState, feature)).toEqual(undefined);
expression = new Expression('\'${undefined}\'');
expect(expression.evaluate(frameState, feature)).toEqual('');
expression = new Expression('abs(-${height}) + max(${height}, ${width}) + clamp(${height}, 0, 2)');
expect(expression.evaluate(frameState, feature)).toEqual(22);
expect(function() {
return new Expression('${height');
}).toThrowRuntimeError();
});
it('evaluates with defines', function() {
var defines = {
halfHeight: '${Height}/2'
};
var feature = new MockFeature();
feature.addProperty('Height', 10);
var expression = new Expression('${halfHeight}', defines);
expect(expression.evaluate(frameState, feature)).toEqual(5);
});
it('evaluates with defines, honoring order of operations', function() {
var defines = {
value: '1 + 2'
};
var expression = new Expression('5.0 * ${value}', defines);
expect(expression.evaluate(frameState, undefined)).toEqual(15);
});
it('evaluate takes result argument', function() {
var expression = new Expression('vec3(1.0)');
var result = new Cartesian3();
var value = expression.evaluate(frameState, undefined, result);
expect(value).toEqual(new Cartesian3(1.0, 1.0, 1.0));
expect(value).toBe(result);
});
it('evaluate takes a color result argument', function() {
var expression = new Expression('color("red")');
var result = new Color();
var value = expression.evaluate(frameState, undefined, result);
expect(value).toEqual(Color.RED);
expect(value).toBe(result);
});
it('gets expressions', function() {
var expressionString = "(regExp('^Chest').test(${County})) && (${YearBuilt} >= 1970)";
var expression = new Expression(expressionString);
expect(expression.expression).toEqual(expressionString);
});
it('throws on invalid expressions', function() {
expect(function() {
return new Expression(false);
}).toThrowDeveloperError();
expect(function() {
return new Expression('');
}).toThrowRuntimeError();
expect(function() {
return new Expression('this');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2; 3;');
}).toThrowRuntimeError();
});
it('throws on unknown characters', function() {
expect(function() {
return new Expression('#');
}).toThrowRuntimeError();
});
it('throws on unmatched parenthesis', function() {
expect(function() {
return new Expression('((true)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('(true))');
}).toThrowRuntimeError();
});
it('throws on unknown identifiers', function() {
expect(function() {
return new Expression('flse');
}).toThrowRuntimeError();
});
it('throws on unknown function calls', function() {
expect(function() {
return new Expression('unknown()');
}).toThrowRuntimeError();
});
it('throws on unknown member function calls', function() {
expect(function() {
return new Expression('regExp().unknown()');
}).toThrowRuntimeError();
});
it('throws with unsupported operators', function() {
expect(function() {
return new Expression('~1');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2 | 3');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2 & 3');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2 << 3');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2 >> 3');
}).toThrowRuntimeError();
expect(function() {
return new Expression('2 >>> 3');
}).toThrowRuntimeError();
});
it('evaluates literal null', function() {
var expression = new Expression('null');
expect(expression.evaluate(frameState, undefined)).toEqual(null);
});
it('evaluates literal undefined', function() {
var expression = new Expression('undefined');
expect(expression.evaluate(frameState, undefined)).toEqual(undefined);
});
it('evaluates literal boolean', function() {
var expression = new Expression('true');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('false');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('converts to literal boolean', function() {
var expression = new Expression('Boolean()');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('Boolean(1)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('Boolean("true")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('evaluates literal number', function() {
var expression = new Expression('1');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('0');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('NaN');
expect(expression.evaluate(frameState, undefined)).toEqual(NaN);
expression = new Expression('Infinity');
expect(expression.evaluate(frameState, undefined)).toEqual(Infinity);
});
it('evaluates math constants', function() {
var expression = new Expression('Math.PI');
expect(expression.evaluate(frameState, undefined)).toEqual(Math.PI);
expression = new Expression('Math.E');
expect(expression.evaluate(frameState, undefined)).toEqual(Math.E);
});
it('converts to literal number', function() {
var expression = new Expression('Number()');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('Number("1")');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('Number(true)');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
});
it('evaluates literal string', function() {
var expression = new Expression('\'hello\'');
expect(expression.evaluate(frameState, undefined)).toEqual('hello');
expression = new Expression('\'Cesium\'');
expect(expression.evaluate(frameState, undefined)).toEqual('Cesium');
expression = new Expression('"Cesium"');
expect(expression.evaluate(frameState, undefined)).toEqual('Cesium');
});
it('converts to literal string', function() {
var expression = new Expression('String()');
expect(expression.evaluate(frameState, undefined)).toEqual('');
expression = new Expression('String(1)');
expect(expression.evaluate(frameState, undefined)).toEqual('1');
expression = new Expression('String(true)');
expect(expression.evaluate(frameState, undefined)).toEqual('true');
});
it('evaluates literal color', function() {
var expression = new Expression('color(\'#ffffff\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(\'#00FFFF\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.CYAN));
expression = new Expression('color(\'#fff\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(\'#0FF\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.CYAN));
expression = new Expression('color(\'white\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(\'cyan\')');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.CYAN));
expression = new Expression('color(\'white\', 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromAlpha(Color.WHITE, 0.5)));
expression = new Expression('rgb(255, 255, 255)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('rgb(100, 255, 190)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromBytes(100, 255, 190)));
expression = new Expression('hsl(0, 0, 1)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('hsl(1.0, 0.6, 0.7)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromHsl(1.0, 0.6, 0.7)));
expression = new Expression('rgba(255, 255, 255, 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromAlpha(Color.WHITE, 0.5)));
expression = new Expression('rgba(100, 255, 190, 0.25)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromBytes(100, 255, 190, 0.25 * 255)));
expression = new Expression('hsla(0, 0, 1, 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(new Color(1.0, 1.0, 1.0, 0.5)));
expression = new Expression('hsla(1.0, 0.6, 0.7, 0.75)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.fromHsl(1.0, 0.6, 0.7, 0.75)));
expression = new Expression('color()');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
});
it('evaluates literal color with result parameter', function() {
var color = new Color();
var expression = new Expression('color(\'#0000ff\')');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.BLUE);
expect(color).toEqual(Color.BLUE);
expression = new Expression('color(\'#f00\')');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.RED);
expect(color).toEqual(Color.RED);
expression = new Expression('color(\'cyan\')');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.CYAN);
expect(color).toEqual(Color.CYAN);
expression = new Expression('color(\'white\', 0.5)');
expect(expression.evaluate(frameState, undefined, color)).toEqual(new Color(1.0, 1.0, 1.0, 0.5));
expect(color).toEqual(new Color(1.0, 1.0, 1.0, 0.5));
expression = new Expression('rgb(0, 0, 0)');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.BLACK);
expect(color).toEqual(Color.BLACK);
expression = new Expression('hsl(0, 0, 1)');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.WHITE);
expect(color).toEqual(Color.WHITE);
expression = new Expression('rgba(255, 0, 255, 0.5)');
expect(expression.evaluate(frameState, undefined, color)).toEqual(new Color(1.0, 0, 1.0, 0.5));
expect(color).toEqual(new Color(1.0, 0, 1.0, 0.5));
expression = new Expression('hsla(0, 0, 1, 0.5)');
expect(expression.evaluate(frameState, undefined, color)).toEqual(new Color(1.0, 1.0, 1.0, 0.5));
expect(color).toEqual(new Color(1.0, 1.0, 1.0, 0.5));
expression = new Expression('color()');
expect(expression.evaluate(frameState, undefined, color)).toEqual(Color.WHITE);
expect(color).toEqual(Color.WHITE);
});
it('evaluates color with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('hex6', '#ffffff');
feature.addProperty('hex3', '#fff');
feature.addProperty('keyword', 'white');
feature.addProperty('alpha', 0.2);
var expression = new Expression('color(${hex6})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(${hex3})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(${keyword})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('color(${keyword}, ${alpha} + 0.6)');
expect(expression.evaluate(frameState, feature).x).toEqual(1.0);
expect(expression.evaluate(frameState, feature).y).toEqual(1.0);
expect(expression.evaluate(frameState, feature).z).toEqual(1.0);
expect(expression.evaluate(frameState, feature).w).toEqual(0.8);
});
it('evaluates rgb with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('red', 100);
feature.addProperty('green', 200);
feature.addProperty('blue', 255);
var expression = new Expression('rgb(${red}, ${green}, ${blue})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(100, 200, 255)));
expression = new Expression('rgb(${red}/2, ${green}/2, ${blue})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(50, 100, 255)));
});
it('evaluates hsl with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('h', 0.0);
feature.addProperty('s', 0.0);
feature.addProperty('l', 1.0);
var expression = new Expression('hsl(${h}, ${s}, ${l})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('hsl(${h} + 0.2, ${s} + 1.0, ${l} - 0.5)');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromHsl(0.2, 1.0, 0.5)));
});
it('evaluates rgba with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('red', 100);
feature.addProperty('green', 200);
feature.addProperty('blue', 255);
feature.addProperty('a', 0.3);
var expression = new Expression('rgba(${red}, ${green}, ${blue}, ${a})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(100, 200, 255, 0.3*255)));
expression = new Expression('rgba(${red}/2, ${green}/2, ${blue}, ${a} * 2)');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(50, 100, 255, 0.6*255)));
});
it('evaluates hsla with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('h', 0.0);
feature.addProperty('s', 0.0);
feature.addProperty('l', 1.0);
feature.addProperty('a', 1.0);
var expression = new Expression('hsla(${h}, ${s}, ${l}, ${a})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('hsla(${h} + 0.2, ${s} + 1.0, ${l} - 0.5, ${a} / 4)');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromHsl(0.2, 1.0, 0.5, 0.25)));
});
it('evaluates rgba with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('red', 100);
feature.addProperty('green', 200);
feature.addProperty('blue', 255);
feature.addProperty('alpha', 0.5);
var expression = new Expression('rgba(${red}, ${green}, ${blue}, ${alpha})');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(100, 200, 255, 0.5 * 255)));
expression = new Expression('rgba(${red}/2, ${green}/2, ${blue}, ${alpha} + 0.1)');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.fromColor(Color.fromBytes(50, 100, 255, 0.6 * 255)));
});
it('color constructors throw with wrong number of arguments', function() {
expect(function() {
return new Expression('rgb(255, 255)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('hsl(1, 1)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('rgba(255, 255, 255)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('hsla(1, 1, 1)');
}).toThrowRuntimeError();
});
it('evaluates color properties (r, g, b, a)', function() {
var expression = new Expression('color(\'#ffffff\').r');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgb(255, 255, 0).g');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('color("cyan").b');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgba(255, 255, 0, 0.5).a');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
});
it('evaluates color properties (x, y, z, w)', function() {
var expression = new Expression('color(\'#ffffff\').x');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgb(255, 255, 0).y');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('color("cyan").z');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgba(255, 255, 0, 0.5).w');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
});
it('evaluates color properties ([0], [1], [2]. [3])', function() {
var expression = new Expression('color(\'#ffffff\')[0]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgb(255, 255, 0)[1]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('color("cyan")[2]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgba(255, 255, 0, 0.5)[3]');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
});
it('evaluates color properties (["r"], ["g"], ["b"], ["a"])', function() {
var expression = new Expression('color(\'#ffffff\')["r"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgb(255, 255, 0)["g"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('color("cyan")["b"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgba(255, 255, 0, 0.5)["a"]');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
});
it('evaluates color properties (["x"], ["y"], ["z"], ["w"])', function() {
var expression = new Expression('color(\'#ffffff\')["x"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgb(255, 255, 0)["y"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('color("cyan")["z"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('rgba(255, 255, 0, 0.5)["w"]');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
});
it('evaluates vec2', function() {
var expression = new Expression('vec2(2.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(2.0, 2.0));
expression = new Expression('vec2(3.0, 4.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3.0, 4.0));
expression = new Expression('vec2(vec2(3.0, 4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3.0, 4.0));
expression = new Expression('vec2(vec3(3.0, 4.0, 5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3.0, 4.0));
expression = new Expression('vec2(vec4(3.0, 4.0, 5.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3.0, 4.0));
});
it('throws if vec2 has invalid number of arguments', function() {
var expression = new Expression('vec2()');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec2(3.0, 4.0, 5.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec2(vec2(3.0, 4.0), 5.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws if vec2 has invalid argument', function() {
var expression = new Expression('vec2("1")');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates vec3', function() {
var expression = new Expression('vec3(2.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(2.0, 2.0, 2.0));
expression = new Expression('vec3(3.0, 4.0, 5.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expression = new Expression('vec3(vec2(3.0, 4.0), 5.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expression = new Expression('vec3(3.0, vec2(4.0, 5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expression = new Expression('vec3(vec3(3.0, 4.0, 5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expression = new Expression('vec3(vec4(3.0, 4.0, 5.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
});
it ('throws if vec3 has invalid number of arguments', function() {
var expression = new Expression('vec3()');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec3(3.0, 4.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec3(3.0, 4.0, 5.0, 6.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec3(vec2(3.0, 4.0), vec2(5.0, 6.0))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec3(vec4(3.0, 4.0, 5.0, 6.0), 1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws if vec3 has invalid argument', function() {
var expression = new Expression('vec3(1.0, "1.0", 2.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates vec4', function() {
var expression = new Expression('vec4(2.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(2.0, 2.0, 2.0, 2.0));
expression = new Expression('vec4(3.0, 4.0, 5.0, 6.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(vec2(3.0, 4.0), 5.0, 6.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(3.0, vec2(4.0, 5.0), 6.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(3.0, 4.0, vec2(5.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(vec3(3.0, 4.0, 5.0), 6.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(3.0, vec3(4.0, 5.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
expression = new Expression('vec4(vec4(3.0, 4.0, 5.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3.0, 4.0, 5.0, 6.0));
});
it ('throws if vec4 has invalid number of arguments', function() {
var expression = new Expression('vec4()');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec4(3.0, 4.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec4(3.0, 4.0, 5.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec4(3.0, 4.0, 5.0, 6.0, 7.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec4(vec3(3.0, 4.0, 5.0))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws if vec4 has invalid argument', function() {
var expression = new Expression('vec4(1.0, "2.0", 3.0, 4.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates vector with expressions as arguments', function() {
var feature = new MockFeature();
feature.addProperty('height', 2);
feature.addProperty('width', 4);
feature.addProperty('depth', 3);
feature.addProperty('scale', 1);
var expression = new Expression('vec4(${height}, ${width}, ${depth}, ${scale})');
expect(expression.evaluate(frameState, feature)).toEqual(new Cartesian4(2.0, 4.0, 3.0, 1.0));
});
it('evaluates expression with multiple nested vectors', function() {
var expression = new Expression('vec4(vec2(1, 2)[vec3(6, 1, 5).y], 2, vec4(1.0).w, 5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(2.0, 2.0, 1.0, 5.0));
});
it('evaluates vector properties (x, y, z, w)', function() {
var expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).x');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).y');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).z');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).w');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
});
it('evaluates vector properties (r, g, b, a)', function() {
var expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).r');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).g');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).b');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0).a');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
});
it('evaluates vector properties ([0], [1], [2], [3])', function() {
var expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)[0]');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)[1]');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)[2]');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)[3]');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
});
it('evaluates vector properties (["x"], ["y"], ["z"]. ["w"])', function() {
var expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["x"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["y"]');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["z"]');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["w"]');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
});
it('evaluates vector properties (["r"], ["g"], ["b"]. ["a"])', function() {
var expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["r"]');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["g"]');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["b"]');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('vec4(1.0, 2.0, 3.0, 4.0)["a"]');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
});
it('evaluates unary not', function() {
var expression = new Expression('!true');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('!!true');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('throws if unary not takes invalid argument', function() {
var expression = new Expression('!"true"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates unary negative', function() {
var expression = new Expression('-5');
expect(expression.evaluate(frameState, undefined)).toEqual(-5);
expression = new Expression('-(-5)');
expect(expression.evaluate(frameState, undefined)).toEqual(5);
});
it('throws if unary negative takes invalid argument', function() {
var expression = new Expression('-"56"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates unary positive', function() {
var expression = new Expression('+5');
expect(expression.evaluate(frameState, undefined)).toEqual(5);
});
it('throws if unary positive takes invalid argument', function() {
var expression = new Expression('+"56"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary addition', function() {
var expression = new Expression('1 + 2');
expect(expression.evaluate(frameState, undefined)).toEqual(3);
expression = new Expression('1 + 2 + 3 + 4');
expect(expression.evaluate(frameState, undefined)).toEqual(10);
});
it('evaluates binary addition with strings', function() {
var expression = new Expression('1 + "10"');
expect(expression.evaluate(frameState, undefined)).toEqual('110');
expression = new Expression('"10" + 1');
expect(expression.evaluate(frameState, undefined)).toEqual('101');
expression = new Expression('"name_" + "building"');
expect(expression.evaluate(frameState, undefined)).toEqual('name_building');
expression = new Expression('"name_" + true');
expect(expression.evaluate(frameState, undefined)).toEqual('name_true');
expression = new Expression('"name_" + null');
expect(expression.evaluate(frameState, undefined)).toEqual('name_null');
expression = new Expression('"name_" + undefined');
expect(expression.evaluate(frameState, undefined)).toEqual('name_undefined');
expression = new Expression('"name_" + vec2(1.1)');
expect(expression.evaluate(frameState, undefined)).toEqual('name_(1.1, 1.1)');
expression = new Expression('"name_" + vec3(1.1)');
expect(expression.evaluate(frameState, undefined)).toEqual('name_(1.1, 1.1, 1.1)');
expression = new Expression('"name_" + vec4(1.1)');
expect(expression.evaluate(frameState, undefined)).toEqual('name_(1.1, 1.1, 1.1, 1.1)');
expression = new Expression('"name_" + regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual('name_/a/');
});
it('throws if binary addition takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) + vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 + vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary subtraction', function() {
var expression = new Expression('2 - 1');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('4 - 3 - 2 - 1');
expect(expression.evaluate(frameState, undefined)).toEqual(-2);
});
it('throws if binary subtraction takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) - vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 - vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('"name1" - "name2"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary multiplication', function() {
var expression = new Expression('1 * 2');
expect(expression.evaluate(frameState, undefined)).toEqual(2);
expression = new Expression('1 * 2 * 3 * 4');
expect(expression.evaluate(frameState, undefined)).toEqual(24);
});
it('throws if binary multiplication takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) * vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec2(1.0) * "name"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary division', function() {
var expression = new Expression('2 / 1');
expect(expression.evaluate(frameState, undefined)).toEqual(2);
expression = new Expression('1/2');
expect(expression.evaluate(frameState, undefined)).toEqual(0.5);
expression = new Expression('24 / -4 / 2');
expect(expression.evaluate(frameState, undefined)).toEqual(-3);
});
it('throws if binary division takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) / vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec2(1.0) / "2.0"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 / vec4(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary modulus', function() {
var expression = new Expression('2 % 1');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('6 % 4 % 3');
expect(expression.evaluate(frameState, undefined)).toEqual(2);
});
it('throws if binary modulus takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) % vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('vec2(1.0) % "2.0"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 % vec4(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary equals strict', function() {
var expression = new Expression('\'hello\' === \'hello\'');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('1 === 2');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('false === true === false');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('1 === "1"');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('evaluates binary not equals strict', function() {
var expression = new Expression('\'hello\' !== \'hello\'');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('1 !== 2');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('false !== true !== false');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('1 !== "1"');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('evaluates binary less than', function() {
var expression = new Expression('2 < 3');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('2 < 2');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('3 < 2');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('throws if binary less than takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) < vec2(2.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 < vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('true < false');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('color(\'blue\') < 10');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary less than or equals', function() {
var expression = new Expression('2 <= 3');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('2 <= 2');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('3 <= 2');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('throws if binary less than or equals takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) <= vec2(2.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 <= vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 <= "5"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('true <= false');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('color(\'blue\') <= 10');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary greater than', function() {
var expression = new Expression('2 > 3');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('2 > 2');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('3 > 2');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('throws if binary greater than takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) > vec2(2.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 > vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 > "5"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('true > false');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('color(\'blue\') > 10');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates binary greater than or equals', function() {
var expression = new Expression('2 >= 3');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('2 >= 2');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('3 >= 2');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('throws if binary greater than or equals takes invalid arguments', function() {
var expression = new Expression('vec2(1.0) >= vec2(2.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 >= vec3(1.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1.0 >= "5"');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('true >= false');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('color(\'blue\') >= 10');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates logical and', function() {
var expression = new Expression('false && false');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('false && true');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('true && true');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('2 && color(\'red\')');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws with invalid and operands', function() {
var expression = new Expression('2 && true');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('true && color(\'red\')');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates logical or', function() {
var expression = new Expression('false || false');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('false || true');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('true || true');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('throws with invalid or operands', function() {
var expression = new Expression('2 || false');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('false || color(\'red\')');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates color operations', function() {
var expression = new Expression('+rgba(255, 0, 0, 1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.RED));
expression = new Expression('rgba(255, 0, 0, 0.5) + rgba(0, 0, 255, 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.MAGENTA));
expression = new Expression('rgba(0, 255, 255, 1.0) - rgba(0, 255, 0, 0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.BLUE));
expression = new Expression('rgba(255, 255, 255, 1.0) * rgba(255, 0, 0, 1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.RED));
expression = new Expression('rgba(255, 255, 0, 1.0) * 1.0');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.YELLOW));
expression = new Expression('1 * rgba(255, 255, 0, 1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.YELLOW));
expression = new Expression('rgba(255, 255, 255, 1.0) / rgba(255, 255, 255, 1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(Color.WHITE));
expression = new Expression('rgba(255, 255, 255, 1.0) / 2');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(new Color(0.5, 0.5, 0.5, 0.5)));
expression = new Expression('rgba(255, 255, 255, 1.0) % rgba(255, 255, 255, 1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Cartesian4.fromColor(new Color(0, 0, 0, 0)));
expression = new Expression('color(\'green\') === color(\'green\')');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('color(\'green\') !== color(\'green\')');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('evaluates vector operations', function() {
var expression = new Expression('+vec2(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1, 2));
expression = new Expression('+vec3(1, 2, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1, 2, 3));
expression = new Expression('+vec4(1, 2, 3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1, 2, 3, 4));
expression = new Expression('-vec2(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(-1, -2));
expression = new Expression('-vec3(1, 2, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(-1, -2, -3));
expression = new Expression('-vec4(1, 2, 3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(-1, -2, -3, -4));
expression = new Expression('vec2(1, 2) + vec2(3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(4, 6));
expression = new Expression('vec3(1, 2, 3) + vec3(3, 4, 5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(4, 6, 8));
expression = new Expression('vec4(1, 2, 3, 4) + vec4(3, 4, 5, 6)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(4, 6, 8, 10));
expression = new Expression('vec2(1, 2) - vec2(3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(-2, -2));
expression = new Expression('vec3(1, 2, 3) - vec3(3, 4, 5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(-2, -2, -2));
expression = new Expression('vec4(1, 2, 3, 4) - vec4(3, 4, 5, 6)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(-2, -2, -2, -2));
expression = new Expression('vec2(1, 2) * vec2(3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3, 8));
expression = new Expression('vec2(1, 2) * 3.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3, 6));
expression = new Expression('3.0 * vec2(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(3, 6));
expression = new Expression('vec3(1, 2, 3) * vec3(3, 4, 5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3, 8, 15));
expression = new Expression('vec3(1, 2, 3) * 3.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3, 6, 9));
expression = new Expression('3.0 * vec3(1, 2, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3, 6, 9));
expression = new Expression('vec4(1, 2, 3, 4) * vec4(3, 4, 5, 6)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3, 8, 15, 24));
expression = new Expression('vec4(1, 2, 3, 4) * 3.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3, 6, 9, 12));
expression = new Expression('3.0 * vec4(1, 2, 3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(3, 6, 9, 12));
expression = new Expression('vec2(1, 2) / vec2(2, 5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.5, 0.4));
expression = new Expression('vec2(1, 2) / 2.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.5, 1.0));
expression = new Expression('vec3(1, 2, 3) / vec3(2, 5, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.5, 0.4, 1.0));
expression = new Expression('vec3(1, 2, 3) / 2.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.5, 1.0, 1.5));
expression = new Expression('vec4(1, 2, 3, 4) / vec4(2, 5, 3, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0.5, 0.4, 1.0, 2.0));
expression = new Expression('vec4(1, 2, 3, 4) / 2.0');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0.5, 1.0, 1.5, 2.0));
expression = new Expression('vec2(2, 3) % vec2(3, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(2, 0));
expression = new Expression('vec3(2, 3, 4) % vec3(3, 3, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(2, 0, 1));
expression = new Expression('vec4(2, 3, 4, 5) % vec4(3, 3, 3, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(2, 0, 1, 1));
expression = new Expression('vec2(1, 2) === vec2(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('vec3(1, 2, 3) === vec3(1, 2, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('vec4(1, 2, 3, 4) === vec4(1, 2, 3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('vec2(1, 2) !== vec2(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('vec3(1, 2, 3) !== vec3(1, 2, 3)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('vec4(1, 2, 3, 4) !== vec4(1, 2, 3, 4)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('evaluates color toString function', function() {
var expression = new Expression('color("red").toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('(1, 0, 0, 1)');
expression = new Expression('rgba(0, 0, 255, 0.5).toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('(0, 0, 1, 0.5)');
});
it('evaluates vector toString function', function() {
var feature = new MockFeature();
feature.addProperty('property', new Cartesian4(1, 2, 3, 4));
var expression = new Expression('vec2(1, 2).toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('(1, 2)');
expression = new Expression('vec3(1, 2, 3).toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('(1, 2, 3)');
expression = new Expression('vec4(1, 2, 3, 4).toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('(1, 2, 3, 4)');
expression = new Expression('${property}.toString()');
expect(expression.evaluate(frameState, feature)).toEqual('(1, 2, 3, 4)');
});
it('evaluates isNaN function', function() {
var expression = new Expression('isNaN()');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isNaN(NaN)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isNaN(1)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isNaN(Infinity)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isNaN(null)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isNaN(true)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isNaN("hello")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isNaN(color("white"))');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
});
it('evaluates isFinite function', function() {
var expression = new Expression('isFinite()');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isFinite(NaN)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isFinite(1)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isFinite(Infinity)');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isFinite(null)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isFinite(true)');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('isFinite("hello")');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('isFinite(color("white"))');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
});
it('evaluates isExactClass function', function() {
var feature = new MockFeature();
feature.setClass('door');
var expression = new Expression('isExactClass("door")');
expect(expression.evaluate(frameState, feature)).toEqual(true);
expression = new Expression('isExactClass("roof")');
expect(expression.evaluate(frameState, feature)).toEqual(false);
});
it('throws if isExactClass takes an invalid number of arguments', function() {
expect(function() {
return new Expression('isExactClass()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('isExactClass("door", "roof")');
}).toThrowRuntimeError();
});
it('evaluates isClass function', function() {
var feature = new MockFeature();
feature.setClass('door');
feature.setInheritedClass('building');
var expression = new Expression('isClass("door") && isClass("building")');
expect(expression.evaluate(frameState, feature)).toEqual(true);
});
it('throws if isClass takes an invalid number of arguments', function() {
expect(function() {
return new Expression('isClass()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('isClass("door", "building")');
}).toThrowRuntimeError();
});
it('evaluates getExactClassName function', function() {
var feature = new MockFeature();
feature.setClass('door');
var expression = new Expression('getExactClassName()');
expect(expression.evaluate(frameState, feature)).toEqual('door');
});
it('throws if getExactClassName takes an invalid number of arguments', function() {
expect(function() {
return new Expression('getExactClassName("door")');
}).toThrowRuntimeError();
});
it('throws if built-in unary function is given an invalid argument', function() {
// Argument must be a number or vector
var expression = new Expression('abs("-1")');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates abs function', function() {
var expression = new Expression('abs(-1)');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('abs(1)');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('abs(vec2(-1.0, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, 1.0));
expression = new Expression('abs(vec3(-1.0, 1.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1.0, 1.0, 0.0));
expression = new Expression('abs(vec4(-1.0, 1.0, 0.0, -1.2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1.0, 1.0, 0.0, 1.2));
});
it('throws if abs function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('abs()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('abs(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates cos function', function() {
var expression = new Expression('cos(0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('cos(vec2(0, Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(1.0, -1.0), CesiumMath.EPSILON7);
expression = new Expression('cos(vec3(0, Math.PI, -Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(1.0, -1.0, -1.0), CesiumMath.EPSILON7);
expression = new Expression('cos(vec4(0, Math.PI, -Math.PI, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(1.0, -1.0, -1.0, 1.0), CesiumMath.EPSILON7);
});
it('throws if cos function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('cos()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('cos(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates sin function', function() {
var expression = new Expression('sin(0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('sin(vec2(0, Math.PI/2))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(0.0, 1.0), CesiumMath.EPSILON7);
expression = new Expression('sin(vec3(0, Math.PI/2, -Math.PI/2))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(0.0, 1.0, -1.0), CesiumMath.EPSILON7);
expression = new Expression('sin(vec4(0, Math.PI/2, -Math.PI/2, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(0.0, 1.0, -1.0, 0.0), CesiumMath.EPSILON7);
});
it('throws if sin function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('sin()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('sin(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates tan function', function() {
var expression = new Expression('tan(0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('tan(vec2(0, Math.PI/4))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(0.0, 1.0), CesiumMath.EPSILON7);
expression = new Expression('tan(vec3(0, Math.PI/4, Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(0.0, 1.0, 0.0), CesiumMath.EPSILON7);
expression = new Expression('tan(vec4(0, Math.PI/4, Math.PI, -Math.PI/4))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(0.0, 1.0, 0.0, -1.0), CesiumMath.EPSILON7);
});
it('throws if tan function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('tan()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('tan(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates acos function', function() {
var expression = new Expression('acos(1)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('acos(vec2(1, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(0.0, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
expression = new Expression('acos(vec3(1, 0, 1))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(0.0, CesiumMath.PI_OVER_TWO, 0.0, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
expression = new Expression('acos(vec4(1, 0, 1, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(0.0, CesiumMath.PI_OVER_TWO, 0.0, CesiumMath.PI_OVER_TWO, 0.0), CesiumMath.EPSILON7);
});
it('throws if acos function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('acos()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('acos(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates asin function', function() {
var expression = new Expression('asin(0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('asin(vec2(0, 1))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(0.0, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
expression = new Expression('asin(vec3(0, 1, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(0.0, CesiumMath.PI_OVER_TWO, 0.0, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
expression = new Expression('asin(vec4(0, 1, 0, 1))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(0.0, CesiumMath.PI_OVER_TWO, 0.0, CesiumMath.PI_OVER_TWO, 0.0), CesiumMath.EPSILON7);
});
it('throws if asin function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('asin()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('asin(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates atan function', function() {
var expression = new Expression('atan(0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('atan(vec2(0, 1))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(0.0, CesiumMath.PI_OVER_FOUR), CesiumMath.EPSILON7);
expression = new Expression('atan(vec3(0, 1, 0))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(0.0, CesiumMath.PI_OVER_FOUR, 0.0, CesiumMath.PI_OVER_FOUR), CesiumMath.EPSILON7);
expression = new Expression('atan(vec4(0, 1, 0, 1))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(0.0, CesiumMath.PI_OVER_FOUR, 0.0, CesiumMath.PI_OVER_FOUR, 0.0), CesiumMath.EPSILON7);
});
it('throws if atan function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('atan()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('atan(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates radians function', function() {
var expression = new Expression('radians(180)');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(Math.PI, CesiumMath.EPSILON10);
expression = new Expression('radians(vec2(180, 90))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(Math.PI, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
expression = new Expression('radians(vec3(180, 90, 180))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(Math.PI, CesiumMath.PI_OVER_TWO, Math.PI), CesiumMath.EPSILON7);
expression = new Expression('radians(vec4(180, 90, 180, 90))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(Math.PI, CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO), CesiumMath.EPSILON7);
});
it('throws if radians function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('radians()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('radians(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates degrees function', function() {
var expression = new Expression('degrees(2 * Math.PI)');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(360, CesiumMath.EPSILON10);
expression = new Expression('degrees(vec2(2 * Math.PI, Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian2(360, 180), CesiumMath.EPSILON7);
expression = new Expression('degrees(vec3(2 * Math.PI, Math.PI, 2 * Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(360, 180, 360), CesiumMath.EPSILON7);
expression = new Expression('degrees(vec4(2 * Math.PI, Math.PI, 2 * Math.PI, Math.PI))');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian4(360, 180, 360, 180), CesiumMath.EPSILON7);
});
it('throws if degrees function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('degrees()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('degrees(1, 2)');
});
});
it('evaluates sqrt function', function() {
var expression = new Expression('sqrt(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('sqrt(4.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('sqrt(-1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(NaN);
expression = new Expression('sqrt(vec2(1.0, 4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, 2.0));
expression = new Expression('sqrt(vec3(1.0, 4.0, 9.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expression = new Expression('sqrt(vec4(1.0, 4.0, 9.0, 16.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1.0, 2.0, 3.0, 4.0));
});
it('throws if sqrt function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('sqrt()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('sqrt(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates sign function', function() {
var expression = new Expression('sign(5.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('sign(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('sign(-5.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(-1.0);
expression = new Expression('sign(vec2(5.0, -5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, -1.0));
expression = new Expression('sign(vec3(5.0, -5.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1.0, -1.0, 0.0));
expression = new Expression('sign(vec4(5.0, -5.0, 0.0, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1.0, -1.0, 0.0, 1.0));
});
it('throws if sign function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('sign()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('sign(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates floor function', function() {
var expression = new Expression('floor(5.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(5.0);
expression = new Expression('floor(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('floor(-1.2)');
expect(expression.evaluate(frameState, undefined)).toEqual(-2.0);
expression = new Expression('floor(vec2(5.5, -1.2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(5.0, -2.0));
expression = new Expression('floor(vec3(5.5, -1.2, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(5.0, -2.0, 0.0));
expression = new Expression('floor(vec4(5.5, -1.2, 0.0, -2.9))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(5.0, -2.0, 0.0, -3.0));
});
it('throws if floor function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('floor()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('floor(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates ceil function', function() {
var expression = new Expression('ceil(5.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(6.0);
expression = new Expression('ceil(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('ceil(-1.2)');
expect(expression.evaluate(frameState, undefined)).toEqual(-1.0);
expression = new Expression('ceil(vec2(5.5, -1.2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(6.0, -1.0));
expression = new Expression('ceil(vec3(5.5, -1.2, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(6.0, -1.0, 0.0));
expression = new Expression('ceil(vec4(5.5, -1.2, 0.0, -2.9))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(6.0, -1.0, 0.0, -2.0));
});
it('throws if ceil function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('ceil()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('ceil(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates round function', function() {
var expression = new Expression('round(5.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(6);
expression = new Expression('round(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0);
expression = new Expression('round(1.2)');
expect(expression.evaluate(frameState, undefined)).toEqual(1);
expression = new Expression('round(vec2(5.5, -1.2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(6.0, -1.0));
expression = new Expression('round(vec3(5.5, -1.2, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(6.0, -1.0, 0.0));
expression = new Expression('round(vec4(5.5, -1.2, 0.0, -2.9))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(6.0, -1.0, 0.0, -3.0));
});
it('throws if round function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('round()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('round(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates exp function', function() {
var expression = new Expression('exp(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(Math.E);
expression = new Expression('exp(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('exp(vec2(1.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(Math.E, 1.0));
expression = new Expression('exp(vec3(1.0, 0.0, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(Math.E, 1.0, Math.E));
expression = new Expression('exp(vec4(1.0, 0.0, 1.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(Math.E, 1.0, Math.E, 1.0));
});
it('throws if exp function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('exp()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('exp(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates exp2 function', function() {
var expression = new Expression('exp2(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('exp2(0.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('exp2(2.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
expression = new Expression('exp2(vec2(1.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(2.0, 1.0));
expression = new Expression('exp2(vec3(1.0, 0.0, 2.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(2.0, 1.0, 4.0));
expression = new Expression('exp2(vec4(1.0, 0.0, 2.0, 3.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(2.0, 1.0, 4.0, 8.0));
});
it('throws if exp2 function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('exp2()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('exp2(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates log function', function() {
var expression = new Expression('log(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('log(10.0)');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(2.302585092994046, CesiumMath.EPSILON7);
expression = new Expression('log(vec2(1.0, Math.E))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.0, 1.0));
expression = new Expression('log(vec3(1.0, Math.E, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.0, 1.0, 0.0));
expression = new Expression('log(vec4(1.0, Math.E, 1.0, Math.E))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0.0, 1.0, 0.0, 1.0));
});
it('throws if log function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('log()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('log(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates log2 function', function() {
var expression = new Expression('log2(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('log2(2.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('log2(4.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('log2(vec2(1.0, 2.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.0, 1.0));
expression = new Expression('log2(vec3(1.0, 2.0, 4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.0, 1.0, 2.0));
expression = new Expression('log2(vec4(1.0, 2.0, 4.0, 8.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0.0, 1.0, 2.0, 3.0));
});
it('throws if log2 function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('log2()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('log2(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates fract function', function() {
var expression = new Expression('fract(1.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('fract(2.25)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.25);
expression = new Expression('fract(-2.25)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.75);
expression = new Expression('fract(vec2(1.0, 2.25))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.0, 0.25));
expression = new Expression('fract(vec3(1.0, 2.25, -2.25))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.0, 0.25, 0.75));
expression = new Expression('fract(vec4(1.0, 2.25, -2.25, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0.0, 0.25, 0.75, 0.0));
});
it('throws if fract function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('fract()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('fract(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates length function', function() {
var expression = new Expression('length(-3.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('length(vec2(-3.0, 4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(5.0);
expression = new Expression('length(vec3(2.0, 3.0, 6.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(7.0);
expression = new Expression('length(vec4(2.0, 4.0, 7.0, 10.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(13.0);
});
it('throws if length function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('length()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('length(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates normalize function', function() {
var expression = new Expression('normalize(5.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('normalize(vec2(3.0, 4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0.6, 0.8));
expression = new Expression('normalize(vec3(2.0, 3.0, -4.0))');
var length = Math.sqrt(2 * 2 + 3 * 3 + 4 * 4);
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(new Cartesian3(2.0 / length, 3.0 / length, -4.0 / length), CesiumMath.EPSILON10);
expression = new Expression('normalize(vec4(-2.0, 3.0, -4.0, 5.0))');
length = Math.sqrt(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5);
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(-2.0 / length, 3.0 / length, -4.0 / length, 5.0/length), CesiumMath.EPSILON10);
});
it('throws if normalize function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('fract()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('fract(1, 2)');
}).toThrowRuntimeError();
});
it('evaluates clamp function', function() {
var expression = new Expression('clamp(50.0, 0.0, 100.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(50.0);
expression = new Expression('clamp(50.0, 0.0, 25.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(25.0);
expression = new Expression('clamp(50.0, 75.0, 100.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(75.0);
expression = new Expression('clamp(vec2(50.0,50.0), vec2(0.0,75.0), 100.0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(50.0, 75.0));
expression = new Expression('clamp(vec2(50.0,50.0), vec2(0.0,75.0), vec2(25.0,100.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(25.0, 75.0));
expression = new Expression('clamp(vec3(50.0, 50.0, 50.0), vec3(0.0, 0.0, 75.0), vec3(100.0, 25.0, 100.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(50.0, 25.0, 75.0));
expression = new Expression('clamp(vec4(50.0, 50.0, 50.0, 100.0), vec4(0.0, 0.0, 75.0, 75.0), vec4(100.0, 25.0, 100.0, 85.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(50.0, 25.0, 75.0, 85.0));
});
it('throws if clamp function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('clamp()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('clamp(1)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('clamp(1, 2)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('clamp(1, 2, 3, 4)');
}).toThrowRuntimeError();
});
it('throws if clamp function takes mismatching types', function() {
var expression = new Expression('clamp(0.0,vec2(0,1),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('clamp(vec2(0,1),vec3(0,1,2),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('clamp(vec2(0,1),vec2(0,1), vec3(1,2,3))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates mix function', function() {
var expression = new Expression('mix(0.0, 2.0, 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('mix(vec2(0.0,1.0), vec2(2.0,3.0), 0.5)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, 2.0));
expression = new Expression('mix(vec2(0.0,1.0), vec2(2.0,3.0), vec2(0.5,4.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, 9.0));
expression = new Expression('mix(vec3(0.0,1.0,2.0), vec3(2.0,3.0,4.0), vec3(0.5,4.0,5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1.0, 9.0, 12.0));
expression = new Expression('mix(vec4(0.0,1.0,2.0,1.5), vec4(2.0,3.0,4.0,2.5), vec4(0.5,4.0,5.0,3.5))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1.0, 9.0, 12.0, 5.0));
});
it('throws if mix function takes mismatching types', function() {
var expression = new Expression('mix(0.0,vec2(0,1),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('mix(vec2(0,1),vec3(0,1,2),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('mix(vec2(0,1),vec2(0,1), vec3(1,2,3))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws if mix function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('mix()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('mix(1)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('mix(1, 2)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('mix(1, 2, 3, 4)');
}).toThrowRuntimeError();
});
it('evaluates atan2 function', function() {
var expression = new Expression('atan2(0,1)');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(0.0, CesiumMath.EPSILON10);
expression = new Expression('atan2(1,0)');
expect(expression.evaluate(frameState, undefined)).toEqualEpsilon(0.5 * Math.PI, CesiumMath.EPSILON10);
expression = new Expression('atan2(vec2(0,1),vec2(1,0))');
expect(expression.evaluate(frameState, undefined))
.toEqualEpsilon(new Cartesian2(0.0, 0.5 * Math.PI), CesiumMath.EPSILON10);
expression = new Expression('atan2(vec3(0,1,0.5),vec3(1,0,0.5))');
expect(expression.evaluate(frameState, undefined))
.toEqualEpsilon(new Cartesian3(0.0, 0.5 * Math.PI, 0.25 * Math.PI), CesiumMath.EPSILON10);
expression = new Expression('atan2(vec4(0,1,0.5,1),vec4(1,0,0.5,0))');
expect(expression.evaluate(frameState, undefined))
.toEqualEpsilon(new Cartesian4(0.0, 0.5 * Math.PI, 0.25 * Math.PI, 0.5 * Math.PI), CesiumMath.EPSILON10);
});
it('throws if atan2 function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('atan2(0.0)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('atan2(1, 2, 0)');
}).toThrowRuntimeError();
});
it('throws if atan2 function takes mismatching types', function() {
var expression = new Expression('atan2(0.0,vec2(0,1))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('atan2(vec2(0,1),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('atan2(vec2(0,1),vec3(0,1,2))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates pow function', function() {
var expression = new Expression('pow(5,0)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('pow(4,2)');
expect(expression.evaluate(frameState, undefined)).toEqual(16.0);
expression = new Expression('pow(vec2(5,4),vec2(0,2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(1.0, 16.0));
expression = new Expression('pow(vec3(5,4,3),vec3(0,2,3))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(1.0, 16.0, 27.0));
expression = new Expression('pow(vec4(5,4,3,2),vec4(0,2,3,5))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(1.0, 16.0, 27.0, 32.0));
});
it('throws if pow function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('pow(0.0)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('pow(1, 2, 0)');
}).toThrowRuntimeError();
});
it('throws if pow function takes mismatching types', function() {
var expression = new Expression('pow(0.0, vec2(0,1))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('pow(vec2(0,1),0.0)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('pow(vec2(0,1),vec3(0,1,2))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates min function', function() {
var expression = new Expression('min(0,1)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('min(-1,0)');
expect(expression.evaluate(frameState, undefined)).toEqual(-1.0);
expression = new Expression('min(vec2(-1,1),0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(-1.0, 0));
expression = new Expression('min(vec2(-1,2),vec2(0,1))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(-1.0, 1.0));
expression = new Expression('min(vec3(-1,2,1),vec3(0,1,2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(-1.0, 1.0, 1.0));
expression = new Expression('min(vec4(-1,2,1,4),vec4(0,1,2,3))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(-1.0, 1.0, 1.0, 3.0));
});
it('throws if min function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('min(0.0)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('min(1, 2, 0)');
}).toThrowRuntimeError();
});
it('throws if min function takes mismatching types', function() {
var expression = new Expression('min(0.0, vec2(0,1))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('min(vec2(0,1),vec3(0,1,2))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates max function', function() {
var expression = new Expression('max(0,1)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('max(-1,0)');
expect(expression.evaluate(frameState, undefined)).toEqual(0.0);
expression = new Expression('max(vec2(-1,1),0)');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0, 1.0));
expression = new Expression('max(vec2(-1,2),vec2(0,1))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian2(0, 2.0));
expression = new Expression('max(vec3(-1,2,1),vec3(0,1,2))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0, 2.0, 2.0));
expression = new Expression('max(vec4(-1,2,1,4),vec4(0,1,2,3))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian4(0, 2.0, 2.0, 4.0));
});
it('throws if max function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('max(0.0)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('max(1, 2, 0)');
}).toThrowRuntimeError();
});
it('throws if max function takes mismatching types', function() {
var expression = new Expression('max(0.0, vec2(0,1))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('max(vec2(0,1),vec3(0,1,2))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates the distance function', function() {
var expression = new Expression('distance(0, 1)');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('distance(vec2(1.0, 0.0), vec2(0.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(1.0);
expression = new Expression('distance(vec3(3.0, 2.0, 1.0), vec3(1.0, 0.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(3.0);
expression = new Expression('distance(vec4(5.0, 5.0, 5.0, 5.0), vec4(0.0, 0.0, 0.0, 0.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(10.0);
});
it('throws if distance function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('distance(0.0)');
}) .toThrowRuntimeError();
expect(function() {
return new Expression('distance(1, 3, 0)');
}).toThrowRuntimeError();
});
it('throws if distance function takes mismatching types of arguments', function() {
expect(function() {
return new Expression('distance(1, vec2(3.0, 2.0)').evaluate(frameState, undefined);
}).toThrowRuntimeError();
expect(function() {
return new Expression('distance(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))').evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates the dot function', function() {
var expression = new Expression('dot(1, 2)');
expect(expression.evaluate(frameState, undefined)).toEqual(2.0);
expression = new Expression('dot(vec2(1.0, 1.0), vec2(2.0, 2.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(4.0);
expression = new Expression('dot(vec3(1.0, 2.0, 3.0), vec3(2.0, 2.0, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(9.0);
expression = new Expression('dot(vec4(5.0, 5.0, 2.0, 3.0), vec4(1.0, 2.0, 1.0, 1.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(20.0);
});
it('throws if dot function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('dot(0.0)');
}).toThrowRuntimeError();
expect(function() {
return new Expression('dot(1, 3, 0)');
}).toThrowRuntimeError();
});
it('throws if dot function takes mismatching types of arguments', function() {
expect(function() {
return new Expression('dot(1, vec2(3.0, 2.0)').evaluate(frameState, undefined);
}).toThrowRuntimeError();
expect(function() {
return new Expression('dot(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))').evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates the cross function', function() {
var expression = new Expression('cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(0.0, 0.0, 0.0));
expression = new Expression('cross(vec3(-1.0, -1.0, -1.0), vec3(0.0, -2.0, -5.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(3.0, -5.0, 2.0));
expression = new Expression('cross(vec3(5.0, -2.0, 1.0), vec3(-2.0, -6.0, -8.0))');
expect(expression.evaluate(frameState, undefined)).toEqual(new Cartesian3(22.0, 38.0, -34.0));
});
it('throws if cross function takes an invalid number of arguments', function() {
expect(function() {
return new Expression('cross(vec3(0.0, 0.0, 0.0))');
}) .toThrowRuntimeError();
expect(function() {
return new Expression('cross(vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))');
}).toThrowRuntimeError();
});
it('throws if cross function does not take vec3 arguments', function() {
expect(function() {
return new Expression('cross(vec2(1.0, 2.0), vec2(3.0, 2.0)').evaluate(frameState, undefined);
}).toThrowRuntimeError();
expect(function() {
return new Expression('cross(vec4(5.0, 2.0, 3.0, 1.0), vec3(4.0, 4.0, 4.0))').evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates ternary conditional', function() {
var expression = new Expression('true ? "first" : "second"');
expect(expression.evaluate(frameState, undefined)).toEqual('first');
expression = new Expression('false ? "first" : "second"');
expect(expression.evaluate(frameState, undefined)).toEqual('second');
expression = new Expression('(!(1 + 2 > 3)) ? (2 > 1 ? 1 + 1 : 0) : (2 > 1 ? -1 + -1 : 0)');
expect(expression.evaluate(frameState, undefined)).toEqual(2);
});
it('evaluates member expression with dot', function() {
var feature = new MockFeature();
feature.addProperty('height', 10);
feature.addProperty('width', 5);
feature.addProperty('string', 'hello');
feature.addProperty('boolean', true);
feature.addProperty('vector', Cartesian4.UNIT_X);
feature.addProperty('vector.x', 'something else');
feature.addProperty('feature.vector', Cartesian4.UNIT_Y);
feature.addProperty('feature', {
vector : Cartesian4.UNIT_Z
});
feature.addProperty('null', null);
feature.addProperty('undefined', undefined);
feature.addProperty('address', {
"street" : "Example Street",
"city" : "Example City"
});
var expression = new Expression('${vector.x}');
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
expression = new Expression('${vector.z}');
expect(expression.evaluate(frameState, feature)).toEqual(0.0);
expression = new Expression('${height.z}');
expect(expression.evaluate(frameState, feature)).toEqual(undefined);
expression = new Expression('${undefined.z}');
expect(expression.evaluate(frameState, feature)).toEqual(undefined);
expression = new Expression('${feature}');
expect(expression.evaluate(frameState, feature)).toEqual({
vector : Cartesian4.UNIT_Z
});
expression = new Expression('${feature.vector}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_X);
expression = new Expression('${feature.feature.vector}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Z);
expression = new Expression('${feature.vector.x}');
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
expression = new Expression('${address.street}');
expect(expression.evaluate(frameState, feature)).toEqual("Example Street");
expression = new Expression('${address.city}');
expect(expression.evaluate(frameState, feature)).toEqual("Example City");
});
it('evaluates member expression with brackets', function() {
var feature = new MockFeature();
feature.addProperty('height', 10);
feature.addProperty('width', 5);
feature.addProperty('string', 'hello');
feature.addProperty('boolean', true);
feature.addProperty('vector', Cartesian4.UNIT_X);
feature.addProperty('vector.x', 'something else');
feature.addProperty('feature.vector', Cartesian4.UNIT_Y);
feature.addProperty('feature', {
vector : Cartesian4.UNIT_Z
});
feature.addProperty('null', null);
feature.addProperty('undefined', undefined);
feature.addProperty('address.street', "Other Street");
feature.addProperty('address', {
"street" : "Example Street",
"city" : "Example City"
});
var expression = new Expression('${vector["x"]}');
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
expression = new Expression('${vector["z"]}');
expect(expression.evaluate(frameState, feature)).toEqual(0.0);
expression = new Expression('${height["z"]}');
expect(expression.evaluate(frameState, feature)).toEqual(undefined);
expression = new Expression('${undefined["z"]}');
expect(expression.evaluate(frameState, feature)).toEqual(undefined);
expression = new Expression('${feature["vector"]}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_X);
expression = new Expression('${feature.vector["x"]}');
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
expression = new Expression('${feature["vector"].x}');
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
expression = new Expression('${feature["vector.x"]}');
expect(expression.evaluate(frameState, feature)).toEqual('something else');
expression = new Expression('${feature.feature["vector"]}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Z);
expression = new Expression('${feature["feature.vector"]}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Y);
expression = new Expression('${address.street}');
expect(expression.evaluate(frameState, feature)).toEqual("Example Street");
expression = new Expression('${feature.address.street}');
expect(expression.evaluate(frameState, feature)).toEqual("Example Street");
expression = new Expression('${feature["address"].street}');
expect(expression.evaluate(frameState, feature)).toEqual("Example Street");
expression = new Expression('${feature["address.street"]}');
expect(expression.evaluate(frameState, feature)).toEqual("Other Street");
expression = new Expression('${address["street"]}');
expect(expression.evaluate(frameState, feature)).toEqual("Example Street");
expression = new Expression('${address["city"]}');
expect(expression.evaluate(frameState, feature)).toEqual("Example City");
});
it('member expressions throw without variable notation', function() {
expect(function() {
return new Expression('color.r');
}).toThrowRuntimeError();
expect(function() {
return new Expression('color["r"]');
}).toThrowRuntimeError();
});
it('member expression throws with variable property', function() {
var feature = new MockFeature();
feature.addProperty('vector', Cartesian4.UNIT_X);
feature.addProperty('vectorName', 'UNIT_X');
expect(function() {
return new Expression('${vector[${vectorName}]}');
}).toThrowRuntimeError();
});
it('evaluates feature property', function() {
var feature = new MockFeature();
feature.addProperty('feature', {
vector : Cartesian4.UNIT_X
});
var expression = new Expression('${feature}');
expect(expression.evaluate(frameState, feature)).toEqual({
vector : Cartesian4.UNIT_X
});
expression = new Expression('${feature} === ${feature.feature}');
expect(expression.evaluate(frameState, feature)).toEqual(true);
});
it('constructs regex', function() {
var feature = new MockFeature();
feature.addProperty('pattern', "[abc]");
var expression = new Expression('regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual(/a/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.LITERAL_REGEX);
expression = new Expression('regExp("\\w")');
expect(expression.evaluate(frameState, undefined)).toEqual(/\w/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.LITERAL_REGEX);
expression = new Expression('regExp(1 + 1)');
expect(expression.evaluate(frameState, undefined)).toEqual(/2/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.REGEX);
expression = new Expression('regExp(true)');
expect(expression.evaluate(frameState, undefined)).toEqual(/true/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.LITERAL_REGEX);
expression = new Expression('regExp()');
expect(expression.evaluate(frameState, undefined)).toEqual(/(?:)/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.LITERAL_REGEX);
expression = new Expression('regExp(${pattern})');
expect(expression.evaluate(frameState, feature)).toEqual(/[abc]/);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.REGEX);
});
it ('constructs regex with flags', function() {
var expression = new Expression('regExp("a", "i")');
expect(expression.evaluate(frameState, undefined)).toEqual(/a/i);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.LITERAL_REGEX);
expression = new Expression('regExp("a", "m" + "g")');
expect(expression.evaluate(frameState, undefined)).toEqual(/a/mg);
expect(expression._runtimeAst._type).toEqual(ExpressionNodeType.REGEX);
});
it('does not throw SyntaxError if regex constructor has invalid pattern', function() {
var expression = new Expression('regExp("(?<=\\s)" + ".")');
expect(function() {
expression.evaluate(frameState, undefined);
}).not.toThrowSyntaxError();
expect(function() {
return new Expression('regExp("(?<=\\s)")');
}).not.toThrowSyntaxError();
});
it('throws if regex constructor has invalid flags', function() {
var expression = new Expression('regExp("a" + "b", "q")');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expect(function() {
return new Expression('regExp("a", "q")');
}).toThrowRuntimeError();
});
it('evaluates regex test function', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('regExp("a").test("abc")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('regExp("a").test("bcd")');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('regExp("quick\\s(brown).+?(jumps)", "ig").test("The Quick Brown Fox Jumps Over The Lazy Dog")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('regExp("a").test()');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('regExp(${property}).test(${property})');
expect(expression.evaluate(frameState, feature)).toEqual(true);
});
it('throws if regex test function has invalid arguments', function() {
var expression = new Expression('regExp("1").test(1)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('regExp("a").test(regExp("b"))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates regex exec function', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
feature.addProperty('Name', 'Building 1');
var expression = new Expression('regExp("a(.)", "i").exec("Abc")');
expect(expression.evaluate(frameState, undefined)).toEqual('b');
expression = new Expression('regExp("a(.)").exec("qbc")');
expect(expression.evaluate(frameState, undefined)).toEqual(null);
expression = new Expression('regExp("a(.)").exec()');
expect(expression.evaluate(frameState, undefined)).toEqual(null);
expression = new Expression('regExp("quick\\s(b.*n).+?(jumps)", "ig").exec("The Quick Brown Fox Jumps Over The Lazy Dog")');
expect(expression.evaluate(frameState, undefined)).toEqual('Brown');
expression = new Expression('regExp("(" + ${property} + ")").exec(${property})');
expect(expression.evaluate(frameState, feature)).toEqual('abc');
expression = new Expression('regExp("Building\\s(\\d)").exec(${Name})');
expect(expression.evaluate(frameState, feature)).toEqual('1');
});
it('throws if regex exec function has invalid arguments', function() {
var expression = new Expression('regExp("1").exec(1)');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('regExp("a").exec(regExp("b"))');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates regex match operator', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('regExp("a") =~ "abc"');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('"abc" =~ regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('regExp("a") =~ "bcd"');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('"bcd" =~ regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('regExp("quick\\s(brown).+?(jumps)", "ig") =~ "The Quick Brown Fox Jumps Over The Lazy Dog"');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('regExp(${property}) =~ ${property}');
expect(expression.evaluate(frameState, feature)).toEqual(true);
});
it('throws if regex match operator has invalid arguments', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('regExp("a") =~ 1');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 =~ regExp("a")');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 =~ 1');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('evaluates regex not match operator', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('regExp("a") !~ "abc"');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('"abc" !~ regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('regExp("a") !~ "bcd"');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('"bcd" !~ regExp("a")');
expect(expression.evaluate(frameState, undefined)).toEqual(true);
expression = new Expression('regExp("quick\\s(brown).+?(jumps)", "ig") !~ "The Quick Brown Fox Jumps Over The Lazy Dog"');
expect(expression.evaluate(frameState, undefined)).toEqual(false);
expression = new Expression('regExp(${property}) !~ ${property}');
expect(expression.evaluate(frameState, feature)).toEqual(false);
});
it('throws if regex not match operator has invalid arguments', function() {
var expression = new Expression('regExp("a") !~ 1');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 !~ regExp("a")');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
expression = new Expression('1 !~ 1');
expect(function() {
expression.evaluate(frameState, undefined);
}).toThrowRuntimeError();
});
it('throws if test is not called with a RegExp', function() {
expect(function() {
return new Expression('color("blue").test()');
}).toThrowRuntimeError();
expect(function() {
return new Expression('"blue".test()');
}).toThrowRuntimeError();
});
it('evaluates regExp toString function', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('regExp().toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('/(?:)/');
expression = new Expression('regExp("\\d\\s\\d", "ig").toString()');
expect(expression.evaluate(frameState, undefined)).toEqual('/\\d\\s\\d/gi');
expression = new Expression('regExp(${property}).toString()');
expect(expression.evaluate(frameState, feature)).toEqual('/abc/');
});
it('throws when using toString on other type', function() {
var feature = new MockFeature();
feature.addProperty('property', 'abc');
var expression = new Expression('${property}.toString()');
expect(function() {
return expression.evaluate(frameState, feature);
}).toThrowRuntimeError();
});
it('evaluates array expression', function() {
var feature = new MockFeature();
feature.addProperty('property', 'value');
feature.addProperty('array', [Cartesian4.UNIT_X, Cartesian4.UNIT_Y, Cartesian4.UNIT_Z]);
feature.addProperty('complicatedArray', [{
'subproperty' : Cartesian4.UNIT_X,
'anotherproperty' : Cartesian4.UNIT_Y
}, {
'subproperty' : Cartesian4.UNIT_Z,
'anotherproperty' : Cartesian4.UNIT_W
}]);
feature.addProperty('temperatures', {
"scale" : "fahrenheit",
"values" : [70, 80, 90]
});
var expression = new Expression('[1, 2, 3]');
expect(expression.evaluate(frameState, undefined)).toEqual([1, 2, 3]);
expression = new Expression('[1+2, "hello", 2 < 3, color("blue"), ${property}]');
expect(expression.evaluate(frameState, feature)).toEqual([3, 'hello', true, Cartesian4.fromColor(Color.BLUE), 'value']);
expression = new Expression('${array[1]}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Y);
expression = new Expression('${complicatedArray[1].subproperty}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Z);
expression = new Expression('${complicatedArray[0]["anotherproperty"]}');
expect(expression.evaluate(frameState, feature)).toEqual(Cartesian4.UNIT_Y);
expression = new Expression('${temperatures["scale"]}');
expect(expression.evaluate(frameState, feature)).toEqual('fahrenheit');
expression = new Expression('${temperatures.values[0]}');
expect(expression.evaluate(frameState, feature)).toEqual(70);
expression = new Expression('${temperatures["values"][0]}');
expect(expression.evaluate(frameState, feature)).toEqual(70);
});
it('evaluates tiles3d_tileset_time expression', function() {
var feature = new MockFeature();
var expression = new Expression('${tiles3d_tileset_time}');
expect(expression.evaluate(frameState, feature)).toEqual(0.0);
feature.content.tileset.timeSinceLoad = 1.0;
expect(expression.evaluate(frameState, feature)).toEqual(1.0);
});
it('gets shader function', function() {
var expression = new Expression('true');
var shaderFunction = expression.getShaderFunction('getShow', '', {}, 'bool');
var expected = 'bool getShow() \n' +
'{ \n' +
' return true; \n' +
'} \n';
expect(shaderFunction).toEqual(expected);
});
it('gets shader expression for variable', function() {
var expression = new Expression('${property}');
var shaderExpression = expression.getShaderExpression('prefix_', {});
var expected = 'prefix_property';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for unary not', function() {
var expression = new Expression('!true');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '!true';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for unary negative', function() {
var expression = new Expression('-5.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '-5.0';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for unary positive', function() {
var expression = new Expression('+5.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '+5.0';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for converting to literal boolean', function() {
var expression = new Expression('Boolean(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'bool(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for converting to literal number', function() {
var expression = new Expression('Number(true)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'float(true)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary addition', function() {
var expression = new Expression('1.0 + 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 + 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary subtraction', function() {
var expression = new Expression('1.0 - 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 - 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary multiplication', function() {
var expression = new Expression('1.0 * 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 * 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary division', function() {
var expression = new Expression('1.0 / 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 / 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary modulus', function() {
var expression = new Expression('1.0 % 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'mod(1.0, 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary equals strict', function() {
var expression = new Expression('1.0 === 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 == 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary not equals strict', function() {
var expression = new Expression('1.0 !== 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 != 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary less than', function() {
var expression = new Expression('1.0 < 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 < 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary less than or equals', function() {
var expression = new Expression('1.0 <= 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 <= 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary greater than', function() {
var expression = new Expression('1.0 > 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 > 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for binary greater than or equals', function() {
var expression = new Expression('1.0 >= 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(1.0 >= 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for logical and', function() {
var expression = new Expression('true && false');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(true && false)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for logical or', function() {
var expression = new Expression('true || false');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(true || false)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for ternary conditional', function() {
var expression = new Expression('true ? 1.0 : 2.0');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(true ? 1.0 : 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for array indexing', function() {
var expression = new Expression('${property[0]}');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'property[0]';
expect(shaderExpression).toEqual(expected);
expression = new Expression('${property[4 / 2]}');
shaderExpression = expression.getShaderExpression('', {});
expected = 'property[int((4.0 / 2.0))]';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for array', function() {
var expression = new Expression('[1.0, 2.0]');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'vec2(1.0, 2.0)';
expect(shaderExpression).toEqual(expected);
expression = new Expression('[1.0, 2.0, 3.0]');
shaderExpression = expression.getShaderExpression('', {});
expected = 'vec3(1.0, 2.0, 3.0)';
expect(shaderExpression).toEqual(expected);
expression = new Expression('[1.0, 2.0, 3.0, 4.0]');
shaderExpression = expression.getShaderExpression('', {});
expected = 'vec4(1.0, 2.0, 3.0, 4.0)';
expect(shaderExpression).toEqual(expected);
});
it('throws when getting shader expression for array of invalid length', function() {
var expression = new Expression('[]');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
expression = new Expression('[1.0]');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
expression = new Expression('[1.0, 2.0, 3.0, 4.0, 5.0]');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('gets shader expression for boolean', function() {
var expression = new Expression('true || false');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(true || false)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for integer', function() {
var expression = new Expression('1');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '1.0';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for float', function() {
var expression = new Expression('1.02');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '1.02';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for color', function() {
var shaderState = {translucent : false};
var expression = new Expression('color()');
var shaderExpression = expression.getShaderExpression('', shaderState);
var expected = 'vec4(1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('color("red")');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(vec3(1.0, 0.0, 0.0), 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('color("#FFF")');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(vec3(1.0, 1.0, 1.0), 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('color("#FF0000")');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(vec3(1.0, 0.0, 0.0), 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('color("rgb(255, 0, 0)")');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(vec3(1.0, 0.0, 0.0), 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('color("red", 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(vec3(1.0, 0.0, 0.0), 0.5)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(true);
shaderState = {translucent : false};
expression = new Expression('rgb(255, 0, 0)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(1.0, 0.0, 0.0, 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('rgb(255, ${property}, 0)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(255.0 / 255.0, property / 255.0, 0.0 / 255.0, 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('rgba(255, 0, 0, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(1.0, 0.0, 0.0, 0.5)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(true);
shaderState = {translucent : false};
expression = new Expression('rgba(255, ${property}, 0, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(255.0 / 255.0, property / 255.0, 0.0 / 255.0, 0.5)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(true);
shaderState = {translucent : false};
expression = new Expression('hsl(1.0, 0.5, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(0.75, 0.25, 0.25, 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('hsla(1.0, 0.5, 0.5, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(0.75, 0.25, 0.25, 0.5)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(true);
shaderState = {translucent : false};
expression = new Expression('hsl(1.0, ${property}, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(czm_HSLToRGB(vec3(1.0, property, 0.5)), 1.0)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(false);
shaderState = {translucent : false};
expression = new Expression('hsla(1.0, ${property}, 0.5, 0.5)');
shaderExpression = expression.getShaderExpression('', shaderState);
expected = 'vec4(czm_HSLToRGB(vec3(1.0, property, 0.5)), 0.5)';
expect(shaderExpression).toEqual(expected);
expect(shaderState.translucent).toBe(true);
});
it('gets shader expression for color components', function() {
// .r, .g, .b, .a
var expression = new Expression('color().r + color().g + color().b + color().a');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(((vec4(1.0)[0] + vec4(1.0)[1]) + vec4(1.0)[2]) + vec4(1.0)[3])';
expect(shaderExpression).toEqual(expected);
// .x, .y, .z, .w
expression = new Expression('color().x + color().y + color().z + color().w');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual(expected);
// [0], [1], [2], [3]
expression = new Expression('color()[0] + color()[1] + color()[2] + color()[3]');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for vector', function() {
var expression = new Expression('vec4(1, 2, 3, 4)');
var shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual('vec4(1.0, 2.0, 3.0, 4.0)');
expression = new Expression('vec4(1) + vec4(2)');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual('(vec4(1.0) + vec4(2.0))');
expression = new Expression('vec4(1, ${property}, vec2(1, 2).x, 0)');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual('vec4(1.0, property, vec2(1.0, 2.0)[0], 0.0)');
expression = new Expression('vec4(vec3(2), 1.0)');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual('vec4(vec3(2.0), 1.0)');
});
it('gets shader expression for vector components', function() {
// .x, .y, .z, .w
var expression = new Expression('vec4(1).x + vec4(1).y + vec4(1).z + vec4(1).w');
var shaderExpression = expression.getShaderExpression('', {});
var expected = '(((vec4(1.0)[0] + vec4(1.0)[1]) + vec4(1.0)[2]) + vec4(1.0)[3])';
expect(shaderExpression).toEqual(expected);
// [0], [1], [2], [3]
expression = new Expression('vec4(1)[0] + vec4(1)[1] + vec4(1)[2] + vec4(1)[3]');
shaderExpression = expression.getShaderExpression('', {});
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for tiles3d_tileset_time', function() {
var expression = new Expression('${tiles3d_tileset_time}');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'u_tilesetTime';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for abs', function() {
var expression = new Expression('abs(-1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'abs(-1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for cos', function() {
var expression = new Expression('cos(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'cos(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for sin', function() {
var expression = new Expression('sin(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'sin(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for tan', function() {
var expression = new Expression('tan(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'tan(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for acos', function() {
var expression = new Expression('acos(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'acos(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for asin', function() {
var expression = new Expression('asin(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'asin(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for atan', function() {
var expression = new Expression('atan(0.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'atan(0.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for sqrt', function() {
var expression = new Expression('sqrt(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'sqrt(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for sign', function() {
var expression = new Expression('sign(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'sign(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for floor', function() {
var expression = new Expression('floor(1.5)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'floor(1.5)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for ceil', function() {
var expression = new Expression('ceil(1.2)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'ceil(1.2)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for round', function() {
var expression = new Expression('round(1.2)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'floor(1.2 + 0.5)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for exp', function() {
var expression = new Expression('exp(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'exp(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for exp2', function() {
var expression = new Expression('exp2(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'exp2(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for log', function() {
var expression = new Expression('log(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'log(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for log2', function() {
var expression = new Expression('log2(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'log2(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for fract', function() {
var expression = new Expression('fract(1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'fract(1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for clamp', function() {
var expression = new Expression('clamp(50.0, 0.0, 100.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'clamp(50.0, 0.0, 100.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for mix', function() {
var expression = new Expression('mix(0.0, 2.0, 0.5)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'mix(0.0, 2.0, 0.5)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for atan2', function() {
var expression = new Expression('atan2(0.0,1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'atan(0.0, 1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for pow', function() {
var expression = new Expression('pow(2.0,2.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'pow(2.0, 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for min', function() {
var expression = new Expression('min(3.0,5.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'min(3.0, 5.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for max', function() {
var expression = new Expression('max(3.0,5.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'max(3.0, 5.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for length', function() {
var expression = new Expression('length(3.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'length(3.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for normalize', function() {
var expression = new Expression('normalize(3.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'normalize(3.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for distance', function() {
var expression = new Expression('distance(0.0, 1.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'distance(0.0, 1.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for dot', function() {
var expression = new Expression('dot(1.0, 2.0)');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'dot(1.0, 2.0)';
expect(shaderExpression).toEqual(expected);
});
it('gets shader expression for cross', function() {
var expression = new Expression('cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))');
var shaderExpression = expression.getShaderExpression('', {});
var expected = 'cross(vec3(1.0, 1.0, 1.0), vec3(2.0, 2.0, 2.0))';
expect(shaderExpression).toEqual(expected);
});
it('throws when getting shader expression for regex', function() {
var expression = new Expression('regExp("a").test("abc")');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
expression = new Expression('regExp("a(.)", "i").exec("Abc")');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
expression = new Expression('regExp("a") =~ "abc"');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
expression = new Expression('regExp("a") !~ "abc"');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for member expression with dot', function() {
var expression = new Expression('${property.name}');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for string member expression with brackets', function() {
var expression = new Expression('${property["name"]}');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for String', function() {
var expression = new Expression('String(1.0)');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for toString', function() {
var expression = new Expression('color("red").toString()');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for literal string', function() {
var expression = new Expression('"name"');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for variable in string', function() {
var expression = new Expression('"${property}"');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for literal undefined', function() {
var expression = new Expression('undefined');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for literal null', function() {
var expression = new Expression('null');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for isNaN', function() {
var expression = new Expression('isNaN(1.0)');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for isFinite', function() {
var expression = new Expression('isFinite(1.0)');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for isExactClass', function() {
var expression = new Expression('isExactClass("door")');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for isClass', function() {
var expression = new Expression('isClass("door")');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
it('throws when getting shader expression for getExactClassName', function() {
var expression = new Expression('getExactClassName()');
expect(function() {
return expression.getShaderExpression('', {});
}).toThrowRuntimeError();
});
});
| emackey/cesium | Specs/Scene/ExpressionSpec.js | JavaScript | apache-2.0 | 154,029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.