text:
"""Core classes for firewall policy enforcement and calls to the compute API.

Simplifies the interface with the compute API for managing firewall policies.
"""

import hashlib
import httplib
import json
import operator
import socket
import ssl
import time

from googleapiclient import errors
import httplib2
from retrying import retry
from google.apputils import datelib
from google.cloud.security.common.util import log_util

# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc,missing-return-doc
# pylint: disable=missing-param-doc,missing-raises-doc

# The name of the GCE API.
API_NAME = 'compute'

# The root of the GCE API.
API_ROOT = 'https://www.googleapis.com/'

# The version of the GCE API to use.
API_VERSION = 'v1'

# The compute engine scope.
SCOPE = 'https://www.googleapis.com/auth/compute'

LOGGER = log_util.get_logger(__name__)

# What transient exceptions should be retried.
RETRY_EXCEPTIONS = (httplib.ResponseNotReady, httplib.IncompleteRead,
                    httplib2.ServerNotFoundError, socket.error, ssl.SSLError,)

# Allowed items in a firewall rule.
ALLOWED_RULE_ITEMS = set(('allowed', 'description', 'name', 'network',
                          'sourceRanges', 'sourceTags', 'targetTags'))

# Maximum time to allow an active API operation to wait for status=Done
OPERATION_TIMEOUT = 300.0

class Error(Exception):
    """Base error class for the module."""

class FirewallEnforcementFailedError(Error):
    """Updating firewall for project failed."""

class InvalidFirewallRuleError(Error):
    """Raised if a firewall rule doesn't look like a firewall rule should."""

class DuplicateFirewallRuleNameError(Error):
    """Raised if a rule name is reused in a policy, names must be unique."""

def http_retry(e):
    """retry_on_exception for retry. Returns True for exceptions to retry."""
    if isinstance(e, errors.HttpError):
        return e.resp.status in (429, 500, 502, 503)
    if isinstance(e, RETRY_EXCEPTIONS):
        return True
    return False

def get_network_name_from_url(network_url):
    """Given a network URL, return the name of the network.

    Args:
      network_url: str - the fully qualified network url, such as
        (https://www.googleapis.com/compute/v1/projects/'
        'my-proj/global/networks/my-network')

    Returns:
      str - the network name, my-network in the previous example
    """
    return network_url.split('/')[-1]

def build_network_url(project, network):
    """Render the network url from project and network names.

    Args:
      project: A str- The name of the GCE project to operate upon.
      network: A str- The name of the network to operate upon.

    Returns:
      The fully qualified network url for the given project/network.
    """
    return (u'%(root)s%(api_name)s/%(version)s/projects/%(project)s/global/'
            'networks/%(network)s') % {
                'api_name': API_NAME,
                'network': network,
                'project': project,
                'root': API_ROOT,
                'version': API_VERSION
            }

class ComputeFirewallAPI(object):
    """Wrap calls to the Google Compute Engine API.

    API calls are decorated with retry to ensure temporary network errors do not
    cause failures.

    If initialized in dry run mode, calls which could modify the compute project
    are no-ops and always return a successful result.
    """

    def __init__(self, gce_service, dry_run=False):
        """Constructor.

        Args:
          gce_service: A GCE service object built using the discovery API.
          dry_run: Bool - True to perform a dry run for reporting firewall
              changes.
        """
        self.gce_service = gce_service
        self._dry_run = dry_run

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    def list_networks(self, project, fields=None):
        """List the networks associated with a GCE project.

        Args:
          project: The id of the project to query.
          fields: If defined, limits the response to a subset of all fields.

        Returns:
          The GCE response.
        """
        LOGGER.debug('Listing networks...')
        return self.gce_service.networks().list(
            project=project, fields=fields).execute()

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    def list_firewalls(self, project, page_token=None):
        """List the firewalls of a given project.

        Args:
          project: The id of the project to query.
          page_token: A str or None- if set, then a pageToken
              to pass to the GCE api call.

        Returns:
          The GCE response.
        """
        LOGGER.debug('Listing firewalls...')
        return self.gce_service.firewalls().list(
            project=project, pageToken=page_token).execute()

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    def delete_firewall_rule(self, project, rule):
        """Delete firewall rules.

        Args:
          project: The id of the project to modify.
          rule: The firewall rule dict to delete.

        Returns:
          The GCE response.
        """
        LOGGER.info('Deleting firewall rule %s on project %s. Deleted rule: %s',
                    rule['name'], project, json.dumps(rule))
        if self._dry_run:
            return self._create_dry_run_response(rule['name'])
        return self.gce_service.firewalls().delete(
            firewall=rule['name'], project=project).execute()

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    def insert_firewall_rule(self, project, rule):
        """Insert a firewall rule.

        Args:
          project: The id of the project to modify.
          rule: The firewall rule dict to add.

        Returns:
          The GCE response.
        """
        LOGGER.info(
            'Inserting firewall rule %s on project %s. Inserted rule: %s',
            rule['name'], project, json.dumps(rule))
        if self._dry_run:
            return self._create_dry_run_response(rule['name'])
        return self.gce_service.firewalls().insert(
            body=rule, project=project).execute()

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    def update_firewall_rule(self, project, rule):
        """Update a firewall rule.

        Args:
          project: The id of the project to modify.
          rule: The firewall rule dict to update.

        Returns:
          The GCE response.
        """
        LOGGER.info('Updating firewall rule %s on project %s. Updated rule: %s',
                    rule['name'], project, json.dumps(rule))
        if self._dry_run:
            return self._create_dry_run_response(rule['name'])
        return self.gce_service.firewalls().update(
            body=rule, firewall=rule['name'], project=project).execute()

    @retry(
        retry_on_exception=http_retry,
        wait_exponential_multiplier=1000,
        stop_max_attempt_number=4)
    # TODO: Investigate improving so we can avoid the pylint disable.
    # pylint: disable=too-many-locals
    def wait_for_any_to_complete(self, project, responses, timeout=0):
        """Wait for one or more requests to complete.

        Args:
          project: The id of the project to query.
          responses: A list of Response objects from GCE for the operation.
          timeout: An optional maximum time in seconds to wait for an operation
              to complete. Operations that exceed the timeout are marked as
              Failed.

        Returns:
          A tuple of (completed, still_running) requests.
        """
        started_timestamp = time.time()

        while True:
            completed_operations = []
            running_operations = []
            for response in responses:
                status = response['status']
                if status == 'DONE':
                    completed_operations.append(response)
                    continue

                operation_name = response['name']
                LOGGER.debug('Checking on operation %s', operation_name)
                request = self.gce_service.globalOperations().get(
                    project=project, operation=operation_name)
                response = request.execute()
                status = response['status']
                LOGGER.info('status of %s is %s', operation_name, status)
                if response['status'] == 'DONE':
                    completed_operations.append(response)
                    continue

                if timeout and time.time() - started_timestamp > timeout:
                    # Add a timeout error to the response
                    LOGGER.error(
                        'Operation %s did not complete before timeout of %f, '
                        'marking operation as failed.', operation_name, timeout)
                    response.setdefault('error', {}).setdefault(
                        'errors', []).append({
                            'code':
                                'OPERATION_TIMEOUT',
                            'message': (
                                'Operation exceeded timeout for completion '
                                'of %0.2f seconds' % timeout)
                        })
                    completed_operations.append(response)
                else:
                    # Operation still running
                    running_operations.append(response)

            if completed_operations or not responses:
                break
            else:
                time.sleep(2)

        for response in completed_operations:
            try:
                op_insert_timestamp = datelib.Timestamp.FromString(
                    response.get('insertTime', '')).AsSecondsSinceEpoch()
                op_start_timestamp = datelib.Timestamp.FromString(
                    response.get('startTime', '')).AsSecondsSinceEpoch()
                op_end_timestamp = datelib.Timestamp.FromString(
                    response.get('endTime', '')).AsSecondsSinceEpoch()
            except ValueError:
                op_insert_timestamp = op_start_timestamp = op_end_timestamp = 0

            op_wait_time = op_end_timestamp - op_insert_timestamp
            op_exec_time = op_end_timestamp - op_start_timestamp
            LOGGER.info('Operation %s completed. Operation type: %s, '
                        'request time: %s, start time: %s, finished time: %s, '
                        'req->end seconds: %i, start->end seconds: %i.',
                        response.get('name', ''),
                        response.get('operationType', ''),
                        response.get('insertTime', ''),
                        response.get('startTime', ''),
                        response.get('endTime', ''), op_wait_time, op_exec_time)
            LOGGER.debug('Operation response object: %r', response)

        return (completed_operations, running_operations)

    def wait_for_all_to_complete(self, project, responses, timeout=0):
        """Wait for all requests to complete.

        Args:
          project: The id of the project to query.
          responses: A list of Response objects from GCE for the operation.
          timeout: An optional maximum time in seconds to wait for an operation
              to complete. Operations that exceed the timeout are marked as
              Failed.

        Returns:
          A list of completed requests.
        """
        completed_operations = []
        running_operations = responses

        while running_operations:
            (completed, running_operations) = (self.wait_for_any_to_complete(
                project, running_operations, timeout))
            completed_operations.extend(completed)

        return completed_operations

    # pylint: disable=no-self-use
    # TODO: Investigate fixing the pylint issue.
    def is_successful(self, response):
        """Checks if the operation finished with no errors.

        If the operation response contains an 'error' key, then the error code
        is checked. Any error code that is not ignored causes this to return
        False.

        Args:
          response: A GlobalOperations response object from an API call.

        Returns:
          True if there were no errors, or all errors are ignored, otherwise
          False.
        """
        success = True
        if 'error' in response:
            # 'error' should always contains an 'errors' list:
            if 'errors' in response['error']:
                for error in response['error']['errors']:
                    # TODO: Verify current codes.
                    # We ignore the following errors:
                    # RESOURCE_ALREADY_EXISTS: Because another program somewhere
                    #     else could have already added the rule.
                    # INVALID_FIELD_VALUE: Because the network probably
                    #     disappeared out from under us.
                    if error.get('code') in [
                            'RESOURCE_ALREADY_EXISTS', 'INVALID_FIELD_VALUE'
                    ]:
                        LOGGER.warn('Ignoring error: %s', error)
                    else:
                        LOGGER.error('Response has error: %s', error)
                        success = False
            else:
                LOGGER.error('Unknown error response: %s', response['error'])
                success = False
        return success

    # pylint: disable=no-self-use
    # TODO: Investigate fixing the pylint issue.
    def _create_dry_run_response(self, rule_name):
        """A fake successful completed response.

        This is used for dry run execution to prevent any changes to the
        existing firewall rules on a project.

        Args:
          rule_name: The name of the firewall rule this response is for.

        Returns:
          A fake successful completed response.
        """
        return {'status': 'DONE', 'name': rule_name}

class FirewallRules(object):
    """A collection of validated firewall rules."""

    def __init__(self, project, rules=None):
        """Constructor.

        Args:
          project: The GCE project id the rules apply to.
          rules: A list of rule dicts to add to the object.

        Raises:
          DuplicateFirewallRuleNameError: Two or more rules have the same name.
          InvalidFirewallRuleError: One or more rules failed validation.
        """
        self._project = project
        self.rules = {}
        if rules:
            self.add_rules(rules)

    def __eq__(self, other):
        """Equality."""
        return self.rules == other.rules

    def __ne__(self, other):
        """Not Equal."""
        return self.rules != other.rules

    def add_rules_from_api(self, firewall_api):
        """Loads rules from compute.firewalls().list().

        Args:
          firewall_api: A ComputeFirewallAPI instance for interfacing with GCE
              API.

        Raises:
          DuplicateFirewallRuleNameError: Two rules have the same name.
          InvalidFirewallRuleError: A rule failed validation.
        """
        if self.rules:
            LOGGER.warn(
                'Can not import rules from the API into a FirewallRules '
                'object with rules already added')
            return

        page_token = ''
        while True:
            if page_token:
                response = firewall_api.list_firewalls(
                    self._project, page_token=page_token)
            else:
                response = firewall_api.list_firewalls(self._project)

            for item in response.get('items', []):
                rule = dict([(key, item[key]) for key in ALLOWED_RULE_ITEMS
                             if key in item])
                self.add_rule(rule)

            # Are there additional pages of data?
            if 'nextPageToken' in response:
                page_token = response['nextPageToken']
            else:
                break

    def add_rules(self, rules, network_name=None):
        """Adds rules from a list of rule dicts.

        Args:
          rules: A list of rule dicts to add to the object
          network_name: If set, rules which have no network currently defined
              will have their network set to network_name, and network_name will
              be prepended to the rule name.

              Rules that do have a network defined have their network matched
              against network_name, and if they differ the rule is not added.

        Raises:
          DuplicateFirewallRuleNameError: Two or more rules have the same name.
          InvalidFirewallRuleError: One or more rules failed validation.
        """
        for rule in rules:
            self.add_rule(rule, network_name=network_name)

    def add_rule(self, rule, network_name=None):
        """Adds rule to the self.rules dictionary.

        Args:
          rule: A valid dict representing a GCE firewall rule
          network_name: If set, rules which have no network currently defined
              will have their network set to network_name, and network_name will
              be prepended to the rule name.

              Rules that do have a network defined have their network matched
              against network_name, and if they differ the rule is not added.

        Raises:
          DuplicateFirewallRuleNameError: Two or more rules have the same name.
          InvalidFirewallRuleError: One or more rules failed validation.
        """
        if not isinstance(rule, dict):
            raise InvalidFirewallRuleError(
                'Invalid rule type. Found %s expected %s', type(rule), dict)

        new_rule = self._order_lists_in_rule(rule)

        if network_name:
            if 'network' in new_rule:
                rule_network = get_network_name_from_url(new_rule['network'])
                if rule_network != network_name:
                    # Don't add the rule if it's network does not match
                    # network_name
                    LOGGER.info('Firewall rule does not apply to network %s, '
                                'skipping: %s', rule_network,
                                json.dumps(new_rule))
                    return
            else:
                new_rule['network'] = build_network_url(self._project,
                                                        network_name)

                # Update the rule name by prepending the network, so it is
                # unique. If the new rule does not have a name defined it will
                # fail the _check_rule_before_adding validation and an
                # InvalidFirewallRuleError exception will be raised.
                if 'name' in new_rule:
                    # Truncate network name if too long. This may result in
                    # duplicate rule names, which will cause the network name
                    # to be changed to a md5 hash representation.
                    new_name = '%s-%s' % (
                        network_name[:(62 - len(new_rule['name']))],
                        new_rule['name'])

                    while new_name in self.rules:
                        # Firewall rule names must start with [a-z], hashes
                        # could start with a number, so we prepend hn-
                        # (hashed network) to the name.
                        network_name = 'hn-' + hashlib.md5(
                            network_name).hexdigest()
                        new_name = '%s-%s' % (
                            network_name[:(62 - len(new_rule['name']))],
                            new_rule['name'])

                    new_rule['name'] = new_name

        if self._check_rule_before_adding(new_rule):
            self.rules[new_rule['name']] = new_rule

    def filtered_by_networks(self, networks):
        """Returns the subset of rules that apply to the specified network(s).

        Args:
          networks: A list of one or more network names to fetch rules for.

        Returns:
          A dictionary of rules that apply to the filtered networks.
        """
        filtered_rules = {}
        for rule_name, rule in self.rules.items():
            if get_network_name_from_url(rule['network']) in networks:
                filtered_rules[rule_name] = rule

        return filtered_rules

    def as_json(self):
        """Export rules to a json string.

        The JSON string should be an array of Firewall resource objects, see
        https://cloud.google.com/compute/docs/reference/latest/firewalls
        for details. Only the fields in ALLOWED_RULE_ITEMS are permitted.

        Returns:
          A JSON string with an array of rules sorted by network and name.
        """
        rules = sorted(
            self.rules.values(), key=operator.itemgetter('network', 'name'))
        return json.dumps(rules, sort_keys=True)

    def add_rules_from_json(self, json_rules):
        """Import rules from a json string as exported by as_json.

        The JSON string should be an array of Firewall resource objects, see
        https://cloud.google.com/compute/docs/reference/latest/firewalls
        for details. Only the fields in ALLOWED_RULE_ITEMS are permitted.

        The legacy format from older versions of GCE Enforcer is also supported.
        This format wraps the array of Firewall resources in a dictionary under
        the key 'items'.

        Args:
          json_rules: The JSON formatted string containing the rules to import.

        Raises:
          DuplicateFirewallRuleNameError: Two or more rules have the same name.
          InvalidFirewallRuleError: One or more rules failed validation.
        """
        if self.rules:
            LOGGER.warn('Can not import from JSON into a FirewallRules object '
                        'with rules already added')
            return

        rules = json.loads(json_rules)
        if isinstance(rules, list):
            for rule in rules:
                self.add_rule(rule)

        elif isinstance(rules, dict):
            if 'items' in rules:
                for item in rules['items']:
                    rule = dict([(key, item[key]) for key in ALLOWED_RULE_ITEMS
                                 if key in item])
                    self.add_rule(rule)

    def _order_lists_in_rule(self, unsorted_rule):
        """Recursively iterates a rule dictionary and sorts any lists.

        This ensures that two rule with the same polices, but with unordered
        lists will compare equal when tested.

        Args:
          unsorted_rule: A rule dictionary that has not been sorted.

        Returns:
          A new rule dictionary with the lists sorted
        """
        sorted_rule = {}
        for key, value in unsorted_rule.items():
            if isinstance(value, list):
                if value and isinstance(value[0], dict):  # List of dictionaries
                    for i, entry in enumerate(value):
                        value[i] = self._order_lists_in_rule(entry)

                sorted_rule[key] = sorted(value)
            elif isinstance(value, dict):
                sorted_rule[key] = self._order_lists_in_rule(value)
            else:
                sorted_rule[key] = value
        return sorted_rule

    def _check_rule_before_adding(self, rule):
        """Validates that a rule is valid and not a duplicate.

        Validation is based on reference:
        https://cloud.google.com/compute/docs/reference/latest/firewalls/insert

        Args:
          rule: The rule to validate.

        Returns:
          True if rule is valid.

        Raises:
          DuplicateFirewallRuleNameError: Two or more rules have the same name.
          InvalidFirewallRuleError: One or more rules failed validation.
        """
        unknown_keys = set(rule.keys()) - ALLOWED_RULE_ITEMS
        if unknown_keys:
            # This is probably the result of a API version upgrade that didn't
            # properly update this function (or a broken binary).
            raise InvalidFirewallRuleError(
                'An unexpected entry exists in a firewall rule dict: "%s".' %
                ','.join(list(unknown_keys)))

        for key in ['allowed', 'name', 'network']:
            if key not in rule:
                raise InvalidFirewallRuleError(
                    'Rule missing required field "%s": "%s".' % (key, rule))

        if 'sourceRanges' not in rule and 'sourceTags' not in rule:
            raise InvalidFirewallRuleError(
                'Rule missing required field oneof "sourceRanges" or '
                '"sourceTags": "%s".' % rule)

        for allow in rule['allowed']:
            if 'IPProtocol' not in allow:
                raise InvalidFirewallRuleError(
                    'Allow rule in %s missing required field '
                    '"IPProtocol": "%s".'
                    % (rule['name'], allow))

        if len(rule['name']) > 63:
            raise InvalidFirewallRuleError(
                'Rule name exceeds length limit of 63 chars: "%s".' %
                rule['name'])

        # TODO: Verify rule name matches regex of allowed
        # names from reference

        if rule['name'] in self.rules:
            raise DuplicateFirewallRuleNameError(
                'Rule %s already defined in rules: %s' %
                (rule['name'], ', '.join(sorted(self.rules.keys()))))

        return True

# pylint: disable=too-many-instance-attributes
# TODO: Investigate improving so we can avoid the pylint disable.
class FirewallEnforcer(object):
    """Enforce a set of firewall rules for use with GCE projects."""

    def __init__(self,
                 project,
                 firewall_api,
                 expected_rules,
                 current_rules=None,
                 project_sema=None,
                 operation_sema=None):
        """Constructor.

        Args:
          project: The id of the cloud project to enforce the firewall on.
          firewall_api: A ComputeFirewallAPI instance for interfacing with GCE
              API.
          expected_rules: A FirewallRules object with the expected rules to be
              enforced on the project.
          current_rules: A FirewallRules object with the current rules for the
              project. If not defined, the API will be queried and the existing
              rules imported into current_rules when apply_firewall is called
              for the project.
          project_sema: An optional semaphore object, used to limit the number
              of concurrent projects getting written to.
          operation_sema: An optional semaphore object, used to limit the number
              of concurrent write operations on project firewalls.
        """
        self.project = project
        self.firewall_api = firewall_api
        self.expected_rules = expected_rules

        if current_rules:
            self.current_rules = current_rules
        else:
            self.current_rules = None

        self.project_sema = project_sema
        self.operation_sema = operation_sema

        # Initialize private parameters
        self._rules_to_delete = []
        self._rules_to_insert = []
        self._rules_to_update = []

        self._deleted_rules = []
        self._inserted_rules = []
        self._updated_rules = []

    def apply_firewall(self,
                       prechange_callback=None,
                       networks=None,
                       allow_empty_ruleset=False):
        """Enforce the expected firewall rules on the project.

        Args:
          prechange_callback: An optional callback function that will get called
              if the firewall policy for a project does not match the expected
              policy, before any changes are actually applied. If the callback
              returns False then no changes will be made to the project. If it
              returns True then the changes will be pushed. If
              prechange_callback is set to None then the callback will be
              skipped and enforcement will continue as though it had returned
              True.

              The callback template is callback_func(project,
                                                     rules_to_delete,
                                                     rules_to_insert,
                                                     rules_to_update)

              The callback may be used to limit the kinds of firewall changes
              that are allowed to be pushed for a project, limit the number of
              rules that can get changed, to check if the project should have
              rules changed, etc.

              The callback may also raise FirewallEnforcementFailedError if it
              determines that the set of changes to the policy could result in
              an outage for an underlying service, or otherwise are inconsistent
              with business rules. This will cause the enforcement to fail.

          networks: A list of networks to limit rule changes to. Rules on
              networks not in the list will not be changed.

              Note- This can lead to duplicate rule name collisions since all
                    rules are not included when building the change set. The
                    change set will be validated before getting enforced and any
                    errors will cause a FirewallEnforcementFailedError exception
                    to be raised.

          allow_empty_ruleset: If set to true and expected_rules has no rules,
              all current firewall rules will be deleted from the project.

        Returns:
          The total number of firewall rules deleted, inserted and updated.

        Raises:
          FirewallEnforcementFailedError: An error occurred while updating the
              firewall. The calling code should validate the current state of
              the project firewall, and potentially revert to the old firewall
              rules.

              Any rules changed before the error occured can be retrieved by
              calling the Get(Deleted|Inserted|Updated)Rules methods.
        """
        # Reset change sets to empty lists
        self._rules_to_delete = []
        self._rules_to_insert = []
        self._rules_to_update = []

        if not self.current_rules:
            self.refresh_current_rules()

        if not self.expected_rules.rules and not allow_empty_ruleset:
            raise FirewallEnforcementFailedError(
                'No rules defined in the expected rules.')

        # Check if current rules match expected rules, so no changes are needed
        if networks:
            if (self.current_rules.filtered_by_networks(networks) ==
                    self.expected_rules.filtered_by_networks(networks)):
                LOGGER.info(
                    'Current and expected rules match for project %s on '
                    'network(s) "%s".', self.project, ','.join(networks))
                return 0
        elif self.current_rules == self.expected_rules:
            LOGGER.info('Current and expected rules match for project %s.',
                        self.project)
            return 0

        self._build_change_set(networks)
        self._validate_change_set(networks)

        if self.project_sema:
            self.project_sema.acquire()

        try:
            if prechange_callback:
                if not prechange_callback(self.project, self._rules_to_delete,
                                          self._rules_to_insert,
                                          self._rules_to_update):
                    LOGGER.warn(
                        'The callback returned False for project %s, changes '
                        'will not be applied.', self.project)
                    return 0
            changed_count = self._apply_change_set()
        finally:
            if self.project_sema:
                self.project_sema.release()

        return changed_count

    def refresh_current_rules(self):
        """Updates the current rules for the project using the compute API."""
        current_rules = FirewallRules(self.project)
        current_rules.add_rules_from_api(self.firewall_api)

        self.current_rules = current_rules

    def get_deleted_rules(self):
        """Returns the list of deleted rules."""
        return self._deleted_rules

    def get_inserted_rules(self):
        """Returns the list of inserted rules."""
        return self._inserted_rules

    def get_updated_rules(self):
        """Returns the list of updated rules."""
        return self._updated_rules

    def _build_change_set(self, networks=None):
        """Enumerate changes between the current and expected firewall rules."""
        if networks:
            # Build new firewall rules objects from the subset of rules for
            # networks
            current_rules = self.current_rules.filtered_by_networks(networks)
            expected_rules = self.expected_rules.filtered_by_networks(networks)
        else:
            current_rules = self.current_rules.rules
            expected_rules = self.expected_rules.rules

        for rule_name in current_rules:
            if rule_name not in expected_rules:
                self._rules_to_delete.append(rule_name)

        for rule_name in expected_rules:
            if rule_name not in current_rules:
                self._rules_to_insert.append(rule_name)

        for rule_name in expected_rules:
            if rule_name in current_rules:
                if expected_rules[rule_name] != current_rules[rule_name]:
                    self._rules_to_update.append(rule_name)

    def _validate_change_set(self, networks=None):
        """Validate the changeset will not leave the project in a bad state."""
        for rule_name in self._rules_to_insert:
            if (rule_name in self.current_rules.rules and
                    rule_name not in self._rules_to_delete):
                raise FirewallEnforcementFailedError(
                    'The rule %s is in the rules to insert set, but the same '
                    'rule name already exists on project %s. It may be used on'
                    ' a different network.' % (rule_name, self.project))

        if networks:
            for rule_name in self._rules_to_update:
                impacted_network = get_network_name_from_url(
                    self.current_rules.rules[rule_name]['network'])
                if impacted_network not in networks:
                    raise FirewallEnforcementFailedError(
                        'The rule %s is in the rules to update set, but it is '
                        'currently on a network, "%s", that is not in the '
                        'allowed networks list for project %s: "%s". Updating '
                        'the rule to %s would impact the wrong network.' %
                        (rule_name, impacted_network, self.project,
                         ', '.join(networks),
                         self.expected_rules.rules[rule_name]))

    def _apply_change_set(self):
        """Updates project firewall rules based on the generated changeset.

        Extends self._(deleted|inserted|updated)_rules with the rules changed by
        these operations.

        Returns:
          The total number of firewall rules deleted, inserted and updated.

        Raises:
          FirewallEnforcementFailedError: Raised if one or more changes fails.
        """
        change_count = 0

        if self._rules_to_insert:
            LOGGER.info('Inserting rules: %s', ', '.join(self._rules_to_insert))
            rules = [
                self.expected_rules.rules[rule_name]
                for rule_name in self._rules_to_insert
            ]
            insert_function = self.firewall_api.insert_firewall_rule
            (successes, failures, change_errors) = self._apply_change(
                insert_function, rules)
            self._inserted_rules.extend(successes)
            change_count += len(successes)
            if failures:
                raise FirewallEnforcementFailedError(
                    'Firewall enforcement failed while inserting new rules for'
                    ' project %s. The following rules had failures: '
                    '%s\nErrors: %s' %
                    (self.project, json.dumps(failures), str(change_errors)))

        if self._rules_to_delete:
            LOGGER.info('Deleting rules: %s', ', '.join(self._rules_to_delete))
            rules = [
                self.current_rules.rules[rule_name]
                for rule_name in self._rules_to_delete
            ]
            delete_function = self.firewall_api.delete_firewall_rule
            (successes, failures, change_errors) = self._apply_change(
                delete_function, rules)
            self._deleted_rules.extend(successes)
            change_count += len(successes)
            if failures:
                raise FirewallEnforcementFailedError(
                    'Firewall enforcement failed while deleting current rules '
                    'for project %s. The following rules had failures: '
                    '%s\nErrors: %s'
                    % (self.project, json.dumps(failures), str(errors)))

        if self._rules_to_update:
            LOGGER.info('Updating rules: %s', ', '.join(self._rules_to_update))
            rules = [
                self.expected_rules.rules[rule_name]
                for rule_name in self._rules_to_update
            ]
            update_function = self.firewall_api.update_firewall_rule
            (successes, failures, change_errors) = self._apply_change(
                update_function, rules)
            self._updated_rules.extend(successes)
            change_count += len(successes)
            if failures:
                raise FirewallEnforcementFailedError(
                    'Firewall enforcement failed while updating rules for '
                    'project %s. The following rules had failures: %s\nErrors:'
                    ' %s' %
                    (self.project, json.dumps(failures), change_errors))

        return change_count

    # pylint: disable=too-many-statements,too-many-branches,too-many-locals
    # TODO: Look at not having some of these disables.
    def _apply_change(self, firewall_function, rules):
        """Modify the firewall using the passed in function and rules.

        If self.operation_sema is defined, then the number of outstanding
        changes is limited to the number of semaphore locks that can be
        acquired.

        Args:
          firewall_function: The delete|insert|update function to call for this
              set of rules
          rules: A list of rules to pass to the firewall_function.

        Returns:
          A tuple with the rules successfully changed by this function and the
          rules that failed.
        """
        applied_rules = []
        failed_rules = []
        change_errors = []
        if not rules:
            return (applied_rules, failed_rules, change_errors)

        successes = []
        failures = []
        running_operations = []
        finished_operations = []
        operations = {}
        for rule in rules:
            if self.operation_sema:
                if not self.operation_sema.acquire(False):  # Non-blocking
                    # No semaphore available, wait for one or more ops to
                    # complete.
                    if running_operations:
                        (completed, running_operations) = (
                            self.firewall_api.wait_for_any_to_complete(
                                self.project, running_operations,
                                OPERATION_TIMEOUT))
                        finished_operations.extend(completed)
                        for response in completed:
                            self.operation_sema.release()

                    self.operation_sema.acquire(True)  # Blocking

            try:
                response = firewall_function(self.project, rule)
            except errors.HttpError as e:
                LOGGER.error(
                    'Error changing firewall rule %s for project %s: %s',
                    rule.get('name', ''), self.project, e)
                error_str = 'Rule: %s\nError: %s' % (rule, e)
                change_errors.append(error_str)
                failed_rules.append(rule)
                if self.operation_sema:
                    self.operation_sema.release()
                continue

            if 'name' in response:
                operations[response['name']] = rule
                running_operations.append(response)
            else:
                LOGGER.error('The response object returned by %r(%s, %s) is '
                             'invalid. It does not contain a "name" key: %s',
                             firewall_function, self.project,
                             json.dumps(rule), json.dumps(response))
                failed_rules.append(rule)
                if self.operation_sema:
                    self.operation_sema.release()

        responses = self.firewall_api.wait_for_all_to_complete(
            self.project, running_operations, OPERATION_TIMEOUT)
        finished_operations.extend(responses)

        if self.operation_sema:
            for response in responses:
                self.operation_sema.release()

        for response in finished_operations:
            if self.firewall_api.is_successful(response):
                successes.append(response)
            else:
                failures.append(response)

        for result in successes:
            operation_name = result.get('name', '')
            if operation_name in operations:
                applied_rules.append(operations[operation_name])
            else:
                LOGGER.warn(
                    'Successful result contained an unknown operation name, '
                    '"%s": %s', operation_name, json.dumps(result))

        for result in failures:
            operation_name = result.get('name', '')
            if operation_name in operations:
                LOGGER.error(
                    'The firewall rule %s for project %s received the '
                    'following error response during the last operation: %s',
                    operations[operation_name], self.project,
                    json.dumps(result))
                failed_rules.append(operations[operation_name])
            else:
                LOGGER.warn(
                    'Failure result contained an unknown operation name, '
                    '"%s": %s', operation_name, json.dumps(result))

        return (applied_rules, failed_rules, change_errors)


text:
UGameLiveStreamingFunctionLibrary::UGameLiveStreamingFunctionLibrary( const FObjectInitializer& ObjectInitializer )
	: Super(ObjectInitializer)
{
}

bool UGameLiveStreamingFunctionLibrary::IsBroadcastingGame()
{
	return IGameLiveStreaming::Get().IsBroadcastingGame();
}

void UGameLiveStreamingFunctionLibrary::StartBroadcastingGame(
		int32 FrameRate,
		float ScreenScaling,
		bool bEnableWebCam,
		int32 DesiredWebCamWidth,
		int32 DesiredWebCamHeight,
		bool bMirrorWebCamImage,
		bool bCaptureAudioFromComputer,
		bool bCaptureAudioFromMicrophone,
		bool bDrawSimpleWebCamVideo )
{
	FGameBroadcastConfig Config;
	Config.FrameRate = FrameRate;
	Config.ScreenScaling = ScreenScaling;
	Config.bEnableWebCam = bEnableWebCam;
	Config.DesiredWebCamWidth = DesiredWebCamWidth;
	Config.DesiredWebCamHeight = DesiredWebCamHeight;
	Config.bMirrorWebCamImage = bMirrorWebCamImage;
	Config.bCaptureAudioFromComputer = bCaptureAudioFromComputer;
	Config.bCaptureAudioFromMicrophone = bCaptureAudioFromMicrophone;
	Config.bDrawSimpleWebCamVideo = bDrawSimpleWebCamVideo;
	IGameLiveStreaming::Get().StartBroadcastingGame( Config );
}

void UGameLiveStreamingFunctionLibrary::StopBroadcastingGame()
{
	IGameLiveStreaming::Get().StopBroadcastingGame();
}

#undef LOCTEXT_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
@interface ZGTextField : UITextField

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Serialize a single value into a WDDX packet</title>

wddx_packet_start

wddx_serialize_vars

WDDX Functions

PHP Manual

wddx_serialize_value

(PHP 4, PHP 5)

wddx_serialize_value — Serialize a single value into a WDDX packet

Description

   string wddx_serialize_value
    ( mixed $var
   [, string $comment
  ] )

   Creates a WDDX packet from a single given value.

Parameters

var

       The value to be serialized

comment

       An optional comment string that appears in the packet header.

Return Values

   Returns the WDDX packet, or FALSE on error.

wddx_packet_start

wddx_serialize_vars

WDDX Functions

PHP Manual


text:
package monitor

import (
	"encoding/json"
	"hyperagent/log"
	"hyperagent/util"
	"io"
	"os"
)

const _MONITOR_JSON string = "monitor.json"

type Monitor struct {
	HostId            string `json:"hostId"`
	MonitorIp         string `json:"monitorIp"`
	EtcdIp            string `json:"etcdIp"`
	EtcdPort          string `json:"etcdPort"`
	HeartBeatInterval string `json:"heartBeatInterval"`
	HeartBeatTimeout  string `json:"heartBeatTimeout"`
	GuacdIp           string `json:"guacdIp"`
	GuacdPort         string `json:"guacdPort"`
}

var monitor *Monitor

func GetMonitor() *Monitor {
	return monitor
}

func SaveMonitor(m *Monitor) {
	file, err := os.OpenFile(_MONITOR_JSON, os.O_CREATE|os.O_TRUNC, 0666) //打开文件
	if err != nil {
		log.Error("Error while open monitor.json to write")
		return
	}
	_, err = io.WriteString(file, util.ToJson(m)) //写入文件(字符串)
	if err != nil {
		log.Error("Error while write monitor.json")
		return
	}
	LoadMonitorConfig()
}

func RemoveMonitor() {
	log.Info("Delete monitor.json ..")
	os.Remove(_MONITOR_JSON)
	monitor = nil
}

func LoadMonitorConfig() {
	log.Info("Start load monitor config ....")
	if _, err := os.Stat(_MONITOR_JSON); os.IsNotExist(err) {
		log.Warn("Monitor.json is not exists.")
		return
	}

	log.Debug("Open monitor file ....")
	file, err := os.Open(_MONITOR_JSON)
	if err != nil {
		log.Error("Error while open monitor.json")
		return
	}
	defer file.Close()

	decoder := json.NewDecoder(file)
	var m Monitor
	err = decoder.Decode(&m)
	if err != nil {
		log.Error("Error while decode monitor.json")
		return
	}
	log.Debug("Load monitor config = %s", util.ToJson(m))
	monitor = &m
}


text:
THREE.OculusShader = {
  uniforms: {
    "texid": { type: "t", value: new THREE.Texture() },
    "scale": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
    "scaleIn": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
    "lensCenter": { type: "v2", value: new THREE.Vector2(0.0,0.0) },
    "hmdWarpParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) },
    "chromAbParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) }
  },
  vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
    " vUv = uv;",
    "	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
  ].join("\n"),

  fragmentShader: [
    "uniform vec2 scale;",
    "uniform vec2 scaleIn;",
    "uniform vec2 lensCenter;",
    "uniform vec4 hmdWarpParam;",
    'uniform vec4 chromAbParam;',
    "uniform sampler2D texid;",
    "varying vec2 vUv;",
    "void main()",
    "{",
    "  vec2 uv = (vUv*2.0)-1.0;", // range from [0,1] to [-1,1]
    "  vec2 theta = (uv-lensCenter)*scaleIn;",
    "  float rSq = theta.x*theta.x + theta.y*theta.y;",
    "  vec2 rvector = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq);",
    '  vec2 rBlue = rvector * (chromAbParam.z + chromAbParam.w * rSq);',
    "  vec2 tcBlue = (lensCenter + scale * rBlue);",
    "  tcBlue = (tcBlue+1.0)/2.0;", // range from [-1,1] to [0,1]
    "  if (any(bvec2(clamp(tcBlue, vec2(0.0,0.0), vec2(1.0,1.0))-tcBlue))) {",
    "    gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);",
    "    return;}",
    "  vec2 tcGreen = lensCenter + scale * rvector;",
    "  tcGreen = (tcGreen+1.0)/2.0;", // range from [-1,1] to [0,1]
    "  vec2 rRed = rvector * (chromAbParam.x + chromAbParam.y * rSq);",
    "  vec2 tcRed = lensCenter + scale * rRed;",
    "  tcRed = (tcRed+1.0)/2.0;", // range from [-1,1] to [0,1]
    "  gl_FragColor = vec4(texture2D(texid, tcRed).r, texture2D(texid, tcGreen).g, texture2D(texid, tcBlue).b, 1);",
    "}"
  ].join("\n")
};

THREE.OculusRenderPass = function(scene, camera, options, overrideMaterial, clearColor, clearAlpha) {
  this.scene = scene;
  this.camera = camera;
  this.overrideMaterial = overrideMaterial;
  this.clearColor = clearColor;
  this.clearAlpha = (clearAlpha !== undefined) ? clearAlpha: 1;
  this.oldClearColor = new THREE.Color();
  this.oldClearAlpha = 1;
  this.enabled = true;
  this.clear = true;
  this.needsSwap = false;
  this.worldFactor = (options && options['worldFactor']) ? options['worldFactor'] : 1.0;
  this.HMD = (options && options.HMD) ? options.HMD : {
    hResolution           : 1920,
    vResolution           : 1080,
    hScreenSize           : 0.12576,
    vScreenSize           : 0.07074,
    interpupillaryDistance: 0.0635,
    lensSeparationDistance: 0.0635,
    eyeToScreenDistance   : 0.041,
    distortionK           : [1.0, 0.22, 0.24, 0.0],
    chromaAbParameter     : [0.996, -0.004, 1.014, 0.0]
  };
  this.pCamera = new THREE.PerspectiveCamera();
  this.pCamera.matrixAutoUpdate = false;
  this.pCamera.target = new THREE.Vector3();
  this.oCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 1000);
  this.oCamera.position.z = 1;
  this.preLeftRender = function () {};
  this.preRightRender = function () {};
  this.RTParams = {
    minFilter: THREE.LinearFilter,
    magFilter: THREE.NearestFilter,
    format   : THREE.RGBAFormat
  };
  this.renderTarget = new THREE.WebGLRenderTarget(window.innerWidth / 2, window.innerHeight, this.RTParams);
  this.RTMaterial = new THREE.ShaderMaterial(THREE.OculusShader);
  var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), this.RTMaterial);
  this.finalScene = new THREE.Scene();
  this.finalScene.add(this.oCamera);
  this.finalScene.add(mesh);
  this.left = {};
  this.right = {};
  this.distScale = 1.0;
  this.setHMD(this.HMD);
};

THREE.OculusRenderPass.prototype = {
  setHMD : function (v) {
    this.HMD = v;
    var aspect = this.HMD.hResolution / (2 * this.HMD.vResolution);
    var r = -1.0 - (4 * (this.HMD.hScreenSize / 4 - this.HMD.lensSeparationDistance / 2) / this.HMD.hScreenSize);
    this.distScale = (this.HMD.distortionK[0] + this.HMD.distortionK[1] * Math.pow(r, 2) + this.HMD.distortionK[2] * Math.pow(r, 4) + this.HMD.distortionK[3] * Math.pow(r, 6));
    var fov = THREE.Math.radToDeg(2 * Math.atan2(this.HMD.vScreenSize * this.distScale, 2 * this.HMD.eyeToScreenDistance));
    var proj = (new THREE.Matrix4()).makePerspective(fov, aspect, 0.3, 10000);
    var h = 4 * (this.HMD.hScreenSize / 4 - this.HMD.interpupillaryDistance / 2) / this.HMD.hScreenSize;
    this.left.proj = ((new THREE.Matrix4()).makeTranslation(h, 0.0, 0.0)).multiply(proj);
    this.right.proj = ((new THREE.Matrix4()).makeTranslation(-h, 0.0, 0.0)).multiply(proj);
    this.left.tranform = (new THREE.Matrix4()).makeTranslation(-this.worldFactor * this.HMD.interpupillaryDistance / 2, 0.0, 0.0);
    this.right.tranform = (new THREE.Matrix4()).makeTranslation(this.worldFactor * this.HMD.interpupillaryDistance / 2, 0.0, 0.0);
    this.left.viewport = [0, 0, this.HMD.hResolution / 2, this.HMD.vResolution];
    this.right.viewport = [this.HMD.hResolution / 2, 0, this.HMD.hResolution / 2, this.HMD.vResolution];
    var lensShift = 4 * (this.HMD.hScreenSize / 4 - this.HMD.lensSeparationDistance / 2) / this.HMD.hScreenSize;
    this.left.lensCenter = new THREE.Vector2(lensShift, 0.0);
    this.right.lensCenter = new THREE.Vector2(-lensShift, 0.0);
    this.RTMaterial.uniforms['hmdWarpParam'].value = new THREE.Vector4(this.HMD.distortionK[0], this.HMD.distortionK[1], this.HMD.distortionK[2], this.HMD.distortionK[3]);
    this.RTMaterial.uniforms['chromAbParam'].value = new THREE.Vector4(this.HMD.chromaAbParameter[0], this.HMD.chromaAbParameter[1], this.HMD.chromaAbParameter[2], this.HMD.chromaAbParameter[3]);
    this.RTMaterial.uniforms['scaleIn'].value = new THREE.Vector2(1.0, 1.0 / aspect);
    this.RTMaterial.uniforms['scale'].value = new THREE.Vector2(1.0 / this.distScale, aspect / this.distScale);
  },
  setSize: function (width, height) {
    this.left.viewport = [width / 2 - this.HMD.hResolution / 2, height / 2 - this.HMD.vResolution / 2, this.HMD.hResolution / 2, this.HMD.vResolution];
    this.right.viewport = [width / 2, height / 2 - this.HMD.vResolution / 2, this.HMD.hResolution / 2, this.HMD.vResolution];
  },

  render: function (renderer, writeBuffer, readBuffer) {
    renderer.autoClear = false;
    if(this.renderTarget) this.renderTarget.dispose();
    this.renderTarget = new THREE.WebGLRenderTarget((this.HMD.hResolution * this.distScale / 2) * renderer.devicePixelRatio, (this.HMD.vResolution * this.distScale) * renderer.devicePixelRatio, this.RTParams);
    this.RTMaterial.uniforms["texid"].value = this.renderTarget;
    this.scene.overrideMaterial = this.overrideMaterial;
    if(camera.matrixAutoUpdate) camera.updateMatrix();
    if(this.clearColor) {
      this.oldClearColor.copy(renderer.getClearColor());
      this.oldClearAlpha = renderer.getClearAlpha();
      renderer.setClearColor(this.clearColor, this.clearAlpha);
    }
    if(this.clear) {
      renderer.clear();
    }
    // Render left
    this.preLeftRender();
    this.pCamera.projectionMatrix.copy(this.left.proj);
    this.pCamera.matrix.copy(this.camera.matrix).multiply(this.left.tranform);
    this.pCamera.matrixWorldNeedsUpdate = true;
    renderer.setViewport(this.left.viewport[0], this.left.viewport[1], this.left.viewport[2], this.left.viewport[3]);
    this.RTMaterial.uniforms['lensCenter'].value = this.left.lensCenter;
    renderer.render(this.scene, this.pCamera, this.renderTarget, true);
    renderer.render(this.finalScene, this.oCamera, readBuffer, true);

    // Render right
    this.preRightRender();
    this.pCamera.projectionMatrix.copy(this.right.proj);
    this.pCamera.matrix.copy(this.camera.matrix).multiply(this.right.tranform);
    this.pCamera.matrixWorldNeedsUpdate = true;
    renderer.setViewport(this.right.viewport[0], this.right.viewport[1], this.right.viewport[2], this.right.viewport[3]);
    this.RTMaterial.uniforms['lensCenter'].value = this.right.lensCenter;
    renderer.render(this.scene, this.pCamera, this.renderTarget, true);
    renderer.render(this.finalScene, this.oCamera, readBuffer, false);
    if(this.clearColor) {
      renderer.setClearColor(this.oldClearColor, this.oldClearAlpha);
    }
    this.scene.overrideMaterial = null;
  }
};


text: module.exports = require('./lib/identity');


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2019-2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import android.app.Activity;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.LineData;

/**
 * Base class for handling the UI (view) of the Line-based Charts
 * for the Chart component
 * @see com.google.appinventor.components.runtime.ChartView
 */
public abstract class LineChartViewBase extends PointChartView<LineChart, LineData> {
  /**
   * Creates a new Line Chart Base View with the specified Chart component
   * instance as the parent of the View.
   *
   * @param chartComponent  Chart component to link View to
   */
  protected LineChartViewBase(Chart chartComponent) {
    super(chartComponent);

    chart = new LineChart(this.form);

    data = new LineData();
    chart.setData(data);

    initializeDefaultSettings();
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/**
 * @var yii\web\View $this
 * @var bariew\userModule\models\User $model
 * @var yii\widgets\ActiveForm $form
 */
?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?php echo $form->field($model, 'file')->fileInput() ?>

        <?php echo Html::submitButton(Yii::t('modules/theme', 'Save'), ['class' => 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
// $Id: AgillaAckOpStackMsgJ.java,v 1.3 2005/11/17 15:37:35 chien-liang Exp $

package edu.wustl.mobilab.agilla.messages;

import edu.wustl.mobilab.agilla.*;
import edu.wustl.mobilab.agilla.variables.*;
import net.tinyos.message.*;

public class AgillaAckOpStackMsgJ implements MessageJ, AgillaConstants {
	private AgillaAgentID aID;
	private short accept, startAddr;

	public AgillaAckOpStackMsgJ() {
	}

	public AgillaAckOpStackMsgJ(AgillaAgentID aID, short accept, short startAddr) {
		this.aID = aID;
		this.accept = accept;
		this.startAddr = startAddr;
	}

	public AgillaAckOpStackMsgJ(AgillaAckOpStackMsg msg) {
		aID = new AgillaAgentID(msg.get_id_id());
		accept = msg.get_accept();
		startAddr = msg.get_startAddr();
	}

	public AgillaAgentID getID() {
		return aID;
	}

	public short getAccept() {
		return accept;
	}

	public short getStartAddr() {
		return startAddr;
	}

	public int getType() {
		return AgillaAckOpStackMsg.AM_TYPE;
	}

	public Message toTOSMsg() {
		AgillaAckOpStackMsg msg = new AgillaAckOpStackMsg();
		msg.set_id_id(aID.getID());
		msg.set_accept(accept);
		msg.set_startAddr(startAddr);
		return msg;
	}

	public String toString() {
		return "ACK OPSTACK MESSAGE: " + aID.toString() + " accept = " + accept + " startAddr = " + startAddr;
	}
}


text:
var http = require('http');
var iconv = require('iconv-lite');
var jsdom = require('jsdom');

var _url = require('url');

var features = {

    // @todo
    // @Important Feature
    // 添加 features , 执行页面中的 js

    FetchExternalResources: ["script", "frame", "iframe", "link"],
    ProcessExternalResources: ["script"],
    SkipExternalResources: false
};

function request(url) {
    var parsed = _url.parse(url);

    function transferEncoding(response, data) {
        var contentType = response.headers['content-type'].split(';');
        var charset;
        contentType.forEach(item=> {
            var match = /\s*charset=(.*?)$/.exec(item);
            if (match) {
                charset = match[1];
            }
        });

        if (charset && iconv.encodingExists(charset)) {
            return iconv.decode(data, charset);
        }
        return data.toString();
    }

    return new Promise((resolve, reject)=> {
        var r = http.request({
            hostname: parsed.hostname,
            path: parsed.path,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36'
            }
        });

        r.on('response', res=> {
            if (res.statusCode === 301 || res.statusCode === 302) {
                request(res.headers['location'])
                    .then(data=> {
                        resolve(data);
                    }, err=> {
                        console.log(err);
                        reject(err);
                    })
            }
            else {
                var buf = new Buffer(0);
                res.on('data', data=>buf = Buffer.concat([buf, data]));
                res.on('end', ()=> {
                    resolve(transferEncoding(res, buf));
                });
            }
        });

        r.on('error', e=> {
            reject(e);
        });

        r.end();

    });
}

request('http://163.com').then(function (buf) {
    jsdom.env(buf.toString(), Object.assign({}, {features}), function (err, window) {
        Array.prototype.forEach.call(window.document.querySelectorAll('meta'), ele=>console.log(ele.outerHTML));
    });
});


text:
using System;
using Thinktecture.IdentityModel.Http.Hawk.Core.Helpers;

namespace Thinktecture.IdentityModel.Http.Hawk.Core
{
    /// <summary>
    /// Hawk credential
    /// </summary>
    public class Credential
    {
        /// <summary>
        /// Identifier that can be used by a client to uniquely identify an entity (user).
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Shared symmetric key that is exchanged out-of-band between the service and the client.
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// Owner of the credential. If the owner is a human user, user name can be stored here.
        /// Else, the application name.
        /// </summary>
        public string User { get; set; }

        /// <summary>
        /// The hashing algorithm that the client and the service have agreed to use to create the
        /// payload hash as well as HMAC of the request and timestamp.
        /// </summary>
        public SupportedAlgorithms Algorithm { get; set; }

        /// <summary>
        /// Returns true, if the identifier is not empty, the shared secret key is not empty, and
        /// the hashing algorithm is one of the algorithms defined in the SupportedAlgorithms enum.
        /// </summary>
        public bool IsValid
        {
            get
            {
                bool isIdValid = !String.IsNullOrWhiteSpace(this.Id);
                bool isKeyValid = !String.IsNullOrWhiteSpace(this.Key);
                bool isAlogorithmValid = Enum.IsDefined(typeof(SupportedAlgorithms), this.Algorithm);

                return isIdValid && isKeyValid && isAlogorithmValid;
            }
        }
    }
}


text:
package org.apache.rocketmq.iot.protocol.mqtt.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.rocketmq.iot.connection.client.Client;
import org.apache.rocketmq.iot.connection.client.ClientManager;
import org.apache.rocketmq.iot.protocol.mqtt.data.MqttClient;
import org.apache.rocketmq.iot.protocol.mqtt.event.DisconnectChannelEvent;
import org.apache.rocketmq.iot.storage.subscription.SubscriptionStore;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class MqttConnectionHandlerTest {
    private MqttConnectionHandler handler;
    private ClientManager clientManager;
    private SubscriptionStore subscriptionStore;
    private Client client;
    private Channel channel;
    private ChannelHandlerContext ctx;

    @Before
    public void setup() {
        clientManager = Mockito.mock(ClientManager.class);
        subscriptionStore = Mockito.mock(SubscriptionStore.class);
        handler = new MqttConnectionHandler(clientManager, subscriptionStore);
        client = Mockito.spy(new MqttClient());
        channel = Mockito.mock(Channel.class);
        ctx = Mockito.mock(ChannelHandlerContext.class);

        Mockito.when(
            clientManager.get(channel)
        ).thenReturn(client);

        Mockito.when(
            ctx.channel()
        ).thenReturn(channel);
    }

    @After
    public void teardown() {

    }

    @Test
    public void testHandleDisconnectChannelEvent() throws Exception {
        DisconnectChannelEvent event = new DisconnectChannelEvent(channel);
        handler.userEventTriggered(ctx, event);

        Mockito.verify(clientManager).remove(channel);
        Mockito.verify(channel).close();
    }

    @Test
    public void testHandleIdleStateEvent() throws Exception {
        IdleStateEvent idleStateEvent = IdleStateEvent.ALL_IDLE_STATE_EVENT;

        handler.userEventTriggered(ctx, idleStateEvent);
        Mockito.verify(clientManager, Mockito.times(1)).remove(channel);
        Mockito.verify(channel, Mockito.times(1)).close();
    }
}