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

<TITLE>
DefaultAdvisorAdapterRegistry (Spring Framework)
</TITLE>

<META NAME="keywords" CONTENT="org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.springframework.aop.framework.adapter

Class DefaultAdvisorAdapterRegistry

java.lang.Object
  org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry

All Implemented Interfaces:
AdvisorAdapterRegistry

public class DefaultAdvisorAdapterRegistry
extends java.lang.Object
implements AdvisorAdapterRegistry

Default implementation of the AdvisorAdapterRegistry interface.

Author:

Rod Johnson

Constructor Summary

DefaultAdvisorAdapterRegistry()

Method Summary

 org.aopalliance.intercept.Interceptor
getInterceptor(Advisor advisor)

          Return an AOP Alliance Interceptor to allow use of the given
 Advisor in an interception-based framework.

 void
registerAdvisorAdapter(AdvisorAdapter adapter)

          Register the given AdvisorAdapter.

 Advisor
wrap(java.lang.Object adviceObject)

          Return an Advisor wrapping the given advice

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DefaultAdvisorAdapterRegistry

public DefaultAdvisorAdapterRegistry()

Method Detail

wrap

public Advisor wrap(java.lang.Object adviceObject)
             throws UnknownAdviceTypeException

Description copied from interface: AdvisorAdapterRegistry

Return an Advisor wrapping the given advice

Specified by:
wrap in interface AdvisorAdapterRegistry

Parameters:
adviceObject - object that should be an advice, such as
 BeforeAdvice or ThrowsAdvice.

Returns:
an Advisor wrapping the given advice. Never
 returns null. If the advice parameter is an Advisor, return
 it.

Throws:

UnknownAdviceTypeException - if no registered AdvisorAdapter
 can wrap the supposed advice

getInterceptor

public org.aopalliance.intercept.Interceptor getInterceptor(Advisor advisor)
                                                     throws UnknownAdviceTypeException

Description copied from interface: AdvisorAdapterRegistry

Return an AOP Alliance Interceptor to allow use of the given
 Advisor in an interception-based framework.
 Don't worry about the pointcut associated with the Advisor,
 if it's a PointcutAdvisor: just return an interceptor

Specified by:
getInterceptor in interface AdvisorAdapterRegistry

Parameters:
advisor - Advisor to find an interceptor for

Returns:
an Interceptor to expose this Advisor's behaviour

Throws:

UnknownAdviceTypeException - if the Advisor type is
 not understood by any registered AdvisorAdapter.

registerAdvisorAdapter

public void registerAdvisorAdapter(AdvisorAdapter adapter)

Description copied from interface: AdvisorAdapterRegistry

Register the given AdvisorAdapter. Note that it is not necessary to register
 adapters for InterceptionAroundAdvice or AOP Alliance Interceptors:
 these must be automatically recognized by an AdvisorAdapterRegistry
 implementation.

Specified by:
registerAdvisorAdapter in interface AdvisorAdapterRegistry

Parameters:
adapter - AdvisorAdapter that understands particular Advisor
 and Advice types.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (C) 2003-2004 The Spring Framework Project.


text:
describe('uiStateRef', function() {

  var timeoutFlush, el, el2, template, scope, document, _locationProvider;

  beforeEach(module('ui.router'));

  beforeEach(module(function($stateProvider, $locationProvider) {
    _locationProvider = $locationProvider;
    $stateProvider.state('top', {
      url: ''
    }).state('contacts', {
      url: '/contacts',
      template: 'Person <ui-view></ui-view>'
    }).state('contacts.item', {
      url: '/:id',
      template: 'Detail | Parent | <ui-view></ui-view>'
    }).state('contacts.item.detail', {
      template: '
Detail
 | Item'
    });
  }));

  beforeEach(inject(function($document) {
    document = $document[0];
  }));

  function triggerClick(el, options) {
    options = angular.extend({
      metaKey:  false,
      ctrlKey:  false,
      shiftKey: false,
      altKey:   false,
      button:   0
    }, options || {});

    var e = document.createEvent("MouseEvents");
    e.initMouseEvent(
      "click", // typeArg of type DOMString, Specifies the event type.
      true, // canBubbleArg of type boolean, Specifies whether or not the event can bubble.
      true, // cancelableArg of type boolean, Specifies whether or not the event's default action can be prevented.
      undefined, // viewArg of type views::AbstractView, Specifies the Event's AbstractView.
      0, // detailArg of type long, Specifies the Event's mouse click count.
      0, // screenXArg of type long, Specifies the Event's screen x coordinate
      0, // screenYArg of type long, Specifies the Event's screen y coordinate
      0, // clientXArg of type long, Specifies the Event's client x coordinate
      0, // clientYArg of type long, Specifies the Event's client y coordinate
      options.ctrlKey, // ctrlKeyArg of type boolean, Specifies whether or not control key was depressed during the Event.
      options.altKey, // altKeyArg of type boolean, Specifies whether or not alt key was depressed during the Event.
      options.shiftKey, // shiftKeyArg of type boolean, Specifies whether or not shift key was depressed during the Event.
      options.metaKey, // metaKeyArg of type boolean, Specifies whether or not meta key was depressed during the Event.
      options.button, // buttonArg of type unsigned short, Specifies the Event's mouse button.
      null // relatedTargetArg of type EventTarget
    );
    el[0].dispatchEvent(e);
  }

  describe('links with promises', function() {

    it('should update the href when promises on parameters change before scope is applied', inject(function($rootScope, $compile, $q) {
      var defer = $q.defer();
      el = angular.element('Details');

      $rootScope.contact = defer.promise;
      defer.resolve({ id: 6 });

      $compile(el)($rootScope);
      $rootScope.$digest();

      // HACK: Promises no longer auto-unwrap in 1.2.x+
      if ($rootScope.contact.$$resolved && $rootScope.contact.$$resolved.value) {
        $rootScope.contact = $rootScope.contact.$$resolved.value;
        $rootScope.$digest();
      }

      expect(el.attr('href')).toBe('#/contacts/6');
    }));
  });

  function buildDOM($rootScope, $compile, $timeout) {
    el = angular.element('Details');
    el2 = angular.element('Top');
    scope = $rootScope;
    scope.contact = { id: 5 };
    scope.$apply();

    $compile(el)(scope);
    $compile(el2)(scope);
    scope.$digest();

    timeoutFlush = function () {
      try {
        $timeout.flush();
      } catch (e) {
        // Angular 1.0.8 throws 'No deferred tasks to be flushed' if there is nothing in queue.
        // Behave as Angular >=1.1.5 and do nothing in such case.
      }
    }
  };

  describe('links', function() {
    beforeEach(inject(buildDOM));

    it('should generate the correct href', function() {
      expect(el.attr('href')).toBe('#/contacts/5');
      expect(el2.attr('href')).toBe('#');
    });

    it('should update the href when parameters change', function() {
      expect(el.attr('href')).toBe('#/contacts/5');
      scope.contact.id = 6;
      scope.$apply();
      expect(el.attr('href')).toBe('#/contacts/6');
    });

    it('should allow multi-line attribute values', inject(function($compile, $rootScope) {
      el = angular.element("Details");
      $rootScope.$index = 3;
      $rootScope.$apply();

      $compile(el)($rootScope);
      $rootScope.$digest();
      expect(el.attr('href')).toBe('#/contacts/3');
    }));

    it('should transition states when left-clicked', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');

      triggerClick(el);
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('contacts.item.detail');
      expect($stateParams).toEqual({ id: "5" });
    }));

    it('should transition when given a click that contains no data (fake-click)', inject(function($state, $stateParams, $q) {
      expect($state.current.name).toEqual('top');

      triggerClick(el, {
        metaKey:  undefined,
        ctrlKey:  undefined,
        shiftKey: undefined,
        altKey:   undefined,
        button:   undefined
      });
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('contacts.item.detail');
      expect($stateParams).toEqual({ id: "5" });
    }));

    it('should not transition states when ctrl-clicked', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');
      triggerClick(el, { ctrlKey: true });

      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({ });
    }));

    it('should not transition states when meta-clicked', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');

      triggerClick(el, { metaKey: true });
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));

    it('should not transition states when shift-clicked', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');

      triggerClick(el, { shiftKey: true });
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));

    it('should not transition states when middle-clicked', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');

      triggerClick(el, { button: 1 });
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));

    it('should not transition states when element has target specified', inject(function($state, $stateParams, $q) {
      el.attr('target', '_blank');
      expect($state.$current.name).toEqual('top');

      triggerClick(el);
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));

    it('should not transition states if preventDefault() is called in click handler', inject(function($state, $stateParams, $q) {
      expect($state.$current.name).toEqual('top');
      el.bind('click', function(e) {
        e.preventDefault();
      });

      triggerClick(el);
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));

    it('should allow passing params to current state', inject(function($compile, $rootScope, $state) {
      $state.current.name = 'contacts.item.detail';

      el = angular.element("Details");
      $rootScope.$index = 3;
      $rootScope.$apply();

      $compile(el)($rootScope);
      $rootScope.$digest();
      expect(el.attr('href')).toBe('#/contacts/3');
    }));

    it('should allow multi-line attribute values when passing params to current state', inject(function($compile, $rootScope, $state) {
      $state.current.name = 'contacts.item.detail';

      el = angular.element("Details");
      $rootScope.$index = 3;
      $rootScope.$apply();

      $compile(el)($rootScope);
      $rootScope.$digest();
      expect(el.attr('href')).toBe('#/contacts/3');
    }));

    it('should take an object as a parameter and update properly on digest churns', inject(function($rootScope, $q, $compile, $state) {

      el = angular.element('
Contacts
');
      template = $compile(el)($rootScope);

      $rootScope.urlParams = { id:1 };
      $rootScope.$digest();
      expect(angular.element(template[0].querySelector('a')).attr('href')).toBe('#/contacts/1');

      $rootScope.urlParams.id = 2;
      $rootScope.$digest();
      expect(angular.element(template[0].querySelector('a')).attr('href')).toBe('#/contacts/2');
    }));
  });

  describe('links in html5 mode', function() {
    beforeEach(function() {
      _locationProvider.html5Mode(true);
    });

    beforeEach(inject(buildDOM));

    it('should generate the correct href', function() {
      expect(el.attr('href')).toBe('/contacts/5');
      expect(el2.attr('href')).toBe('');
    });

    it('should update the href when parameters change', function() {
      expect(el.attr('href')).toBe('/contacts/5');
      scope.contact.id = 6;
      scope.$apply();
      expect(el.attr('href')).toBe('/contacts/6');
    });

    it('should transition states when the url is empty', inject(function($state, $stateParams, $q) {
      // Odd, in html5Mode, the initial state isn't matching on empty url, but does match if top.url is "/".
//      expect($state.$current.name).toEqual('top');

      triggerClick(el2);
      timeoutFlush();
      $q.flush();

      expect($state.current.name).toEqual('top');
      expect($stateParams).toEqualData({});
    }));
  });

  describe('forms', function() {
    var el, scope;

    beforeEach(inject(function($rootScope, $compile) {
      el = angular.element('<form ui-sref="contacts.item.detail({ id: contact.id })"></form>');
      scope = $rootScope;
      scope.contact = { id: 5 };
      scope.$apply();

      $compile(el)(scope);
      scope.$digest();
    }));

    it('should generate the correct action', function() {
      expect(el.attr('action')).toBe('#/contacts/5');
    });
  });

  describe('relative transitions', function() {

    beforeEach(inject(function($rootScope, $compile, $state) {
      $state.transitionTo("contacts.item", { id: 5 });
      el = angular.element('Details');
      scope = $rootScope;
      scope.$apply();

      $compile(el)(scope);
      template = $compile(angular.element('
<ui-view></ui-view>
'))(scope);
      scope.$digest();
    }));

    it('should work', inject(function ($state, $stateParams, $q, $timeout) {
      triggerClick(el);
      $timeout.flush();
      $q.flush();

      expect($state.$current.name).toBe("contacts.item.detail");
      expect($state.params).toEqual({ id: "5" });
    }));

    it('should resolve states from parent uiView', inject(function ($state, $stateParams, $q, $timeout) {
      $state.transitionTo('contacts');
      $q.flush();

      var parentToChild = angular.element(template[0].querySelector('a.item'));
      triggerClick(parentToChild);
      $timeout.flush();
      $q.flush();

      var childToGrandchild = angular.element(template[0].querySelector('a.item-detail'));
      var childToParent = angular.element(template[0].querySelector('a.item-parent'));

      triggerClick(childToGrandchild);
      $timeout.flush();
      $q.flush();

      var grandchildToParent = angular.element(template[0].querySelector('a.item-parent2'));
      expect($state.$current.name).toBe("contacts.item.detail")

      triggerClick(grandchildToParent);
      $timeout.flush();
      $q.flush();
      expect($state.$current.name).toBe("contacts.item");

      $state.transitionTo("contacts.item.detail", { id: 3 });
      triggerClick(childToParent);
      $timeout.flush();
      $q.flush();
      expect($state.$current.name).toBe("contacts");
    }));
  });

  describe('transition options', function() {

    beforeEach(inject(function($rootScope, $compile, $state) {
      el = angular.element('Details');
      scope = $rootScope;
      scope.contact = { id: 5 };

      $compile(el)(scope);
      scope.$digest();
    }));

    it('uses allowed transition options', inject(function($q, $timeout, $state) {
      var transitionOptions;

      spyOn($state, 'go').andCallFake(function(state, params, options) {
        transitionOptions = options;
      });

      triggerClick(el);
      $timeout.flush();

      expect(transitionOptions.reload).toEqual(true);
      expect(transitionOptions.absolute).toEqual(true);
      expect(transitionOptions.notify).toBeUndefined();
    }));
  });
});

describe('uiSrefActive', function() {
  var el, template, scope, document, _stateProvider;

  beforeEach(module('ui.router'));

  beforeEach(module(function($stateProvider) {
    _stateProvider = $stateProvider;
    $stateProvider.state('top', {
      url: ''
    }).state('contacts', {
      url: '/contacts',
      views: {
        '@': {
          template: 'Contacts'
        }
      }
    }).state('contacts.item', {
      url: '/:id',
    }).state('contacts.item.detail', {
      url: '/detail/:foo'
    }).state('contacts.item.edit', {
      url: '/edit'
    });
  }));

  beforeEach(inject(function($document) {
    document = $document[0];
  }));

  it('should update class for sibling uiSref', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
ContactsContacts
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');
    $state.transitionTo('contacts.item', { id: 1 });
    $q.flush();

    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('active');

    $state.transitionTo('contacts.item', { id: 2 });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');
  }));

  it('should match state\'s parameters', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
Contacts
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');
    $state.transitionTo('contacts.item.detail', { id: 5, foo: 'bar' });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('active');

    $state.transitionTo('contacts.item.detail', { id: 5, foo: 'baz' });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');
  }));

  it('should match on child states', inject(function($rootScope, $q, $compile, $state) {
    template = $compile('
Contacts
')($rootScope);
    $rootScope.$digest();
    var a = angular.element(template[0].getElementsByTagName('a')[0]);

    $state.transitionTo('contacts.item.edit', { id: 1 });
    $q.flush();
    expect(a.attr('class')).toMatch(/active/);

    $state.transitionTo('contacts.item.edit', { id: 4 });
    $q.flush();
    expect(a.attr('class')).not.toMatch(/active/);
  }));

  it('should NOT match on child states when active-equals is used', inject(function($rootScope, $q, $compile, $state) {
    template = $compile('
Contacts
')($rootScope);
    $rootScope.$digest();
    var a = angular.element(template[0].getElementsByTagName('a')[0]);

    $state.transitionTo('contacts.item', { id: 1 });
    $q.flush();
    expect(a.attr('class')).toMatch(/active/);

    $state.transitionTo('contacts.item.edit', { id: 1 });
    $q.flush();
    expect(a.attr('class')).not.toMatch(/active/);
  }));

  it('should resolve relative state refs', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('

');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    $state.transitionTo('contacts');
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('ng-scope');

    $state.transitionTo('contacts.item', { id: 6 });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('ng-scope active');

    $state.transitionTo('contacts.item', { id: 5 });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('ng-scope');
  }));

  it('should match on any child state refs', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
ContactsContacts
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    expect(angular.element(template[0]).attr('class')).toBe('ng-scope');

    $state.transitionTo('contacts.item', { id: 1 });
    $q.flush();
    expect(angular.element(template[0]).attr('class')).toBe('ng-scope active');

    $state.transitionTo('contacts.item', { id: 2 });
    $q.flush();
    expect(angular.element(template[0]).attr('class')).toBe('ng-scope active');
  }));

  it('should match fuzzy on lazy loaded states', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
Lazy Contact
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    $rootScope.$on('$stateNotFound', function () {
      _stateProvider.state('contacts.lazy', {});
    });

    $state.transitionTo('contacts.item', { id: 1 });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');

    $state.transitionTo('contacts.lazy');
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('active');
  }));

  it('should match exactly on lazy loaded states', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
Lazy Contact
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    $rootScope.$on('$stateNotFound', function () {
      _stateProvider.state('contacts.lazy', {});
    });

    $state.transitionTo('contacts.item', { id: 1 });
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');

    $state.transitionTo('contacts.lazy');
    $q.flush();
    expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('active');
  }));
});

describe('uiView controllers or onEnter handlers', function() {
  var el, template, scope, document, count;

  beforeEach(module('ui.router'));

  beforeEach(module(function($stateProvider) {
    count = 0;
    $stateProvider
      .state('aside',         { url: '/aside', template: '

' })
      .state('A',           { url: '/A', template: '

' })
      .state('A.fwd', {
        url: '/fwd', views: { 'fwd@A': {
          template: '
',
          controller: function($state) { if (count++ < 20 && $state.current.name == 'A.fwd') $state.go(".nest"); }
        }}
      })
      .state('A.fwd.nest',  { url: '/nest', template: '

' });
  }));

  beforeEach(inject(function($document) {
    document = $document[0];
  }));

  it('should not go into an infinite loop when controller uses $state.go', inject(function($rootScope, $q, $compile, $state) {
    el = angular.element('
<ui-view></ui-view>
');
    template = $compile(el)($rootScope);
    $rootScope.$digest();

    $state.transitionTo('aside');
    $q.flush();
    expect(template[0].querySelector('.aside')).toBeDefined();
    expect(template[0].querySelector('.fwd')).toBeNull();

    $state.transitionTo('A');
    $q.flush();
    expect(template[0].querySelector('.A')).not.toBeNull();
    expect(template[0].querySelector('.fwd')).toBeNull();

    $state.transitionTo('A.fwd');
    $q.flush();
    expect(template[0].querySelector('.A')).not.toBeNull();
    expect(template[0].querySelector('.fwd')).not.toBeNull();
    expect(template[0].querySelector('.nest')).not.toBeNull();
    expect(count).toBe(1);
  }));
});

redpajama_set_name: RedPajamaGithub


text:
/* global WavesApp: readonly */
(() => {
    'use strict';

    const { libs } = require('@waves/waves-transactions');
    const {
        encryptSeed,
        decryptSeed,
        base58Encode,
        base58Decode,
        base64Encode,
        blake2b,
        stringToBytes,
        address: buildAddress,
        publicKey: buildPublicKey,
        sharedKey,
        messageEncrypt
    } = libs.crypto;

    let _password;
    let _rounds;
    let _users = {};

    class MultiAccount {

        get isSignedIn() {
            return !!_password;
        }

        signUp(password, rounds) {
            _password = password;
            _rounds = rounds;
            _users = {};

            const str = JSON.stringify(_users);
            const multiAccountHash = base58Encode(blake2b(stringToBytes(str)));
            const multiAccountData = encryptSeed(str, _password, _rounds);

            return Promise.resolve({
                multiAccountData,
                multiAccountHash
            });
        }

        signIn(encryptedAccount, password, rounds, hash) {
            try {
                const str = decryptSeed(encryptedAccount, password, rounds);

                if (base58Encode(blake2b(stringToBytes(str))) !== hash) {
                    throw new Error('hash does not match');
                }

                _password = password;
                _rounds = rounds;
                _users = JSON.parse(str);

                return Promise.resolve();
            } catch (e) {
                return Promise.reject(e);
            }
        }

        signOut() {
            _password = undefined;
            _rounds = undefined;
            _users = {};
        }

        changePassword(encryptedAccount, oldPassword, newPassword, rounds, hash) {
            try {
                const str = decryptSeed(encryptedAccount, oldPassword, rounds);

                if (base58Encode(blake2b(stringToBytes(str))) !== hash) {
                    throw new Error('hash does not match');
                }

                _password = newPassword;
                _rounds = rounds;
                _users = JSON.parse(str);

                const multiAccountData = encryptSeed(str, _password, _rounds);

                return Promise.resolve({
                    multiAccountData,
                    multiAccountHash: hash
                });
            } catch (e) {
                return Promise.reject(e);
            }
        }

        addUser({ userType, networkByte, seed, id, privateKey, publicKey }) {
            const _publicKey = publicKey || buildPublicKey(seed || { privateKey });
            const userHash = this.hash(networkByte + _publicKey);

            _users[userHash] = {
                userType,
                networkByte,
                seed,
                id,
                privateKey,
                publicKey: _publicKey
            };

            const str = JSON.stringify(_users);
            const multiAccountHash = base58Encode(blake2b(stringToBytes(str)));
            const multiAccountData = encryptSeed(str, _password, _rounds);

            return Promise.resolve({
                multiAccountData,
                multiAccountHash,
                userHash
            });
        }

        deleteUser(userHash) {
            delete _users[userHash];

            const str = JSON.stringify(_users);
            const multiAccountHash = base58Encode(blake2b(stringToBytes(str)));
            const multiAccountData = encryptSeed(str, _password, _rounds);

            return Promise.resolve({
                multiAccountData,
                multiAccountHash,
                userHash
            });
        }

        toList(multiAccountUsers) {
            return this.isSignedIn ?
                Object.entries(multiAccountUsers || {}).map(([userHash, user]) => {
                    const _user = _users[userHash];
                    if (!_user) {
                        return null;
                    }
                    return {
                        ...user,
                        userType: _user.userType,
                        networkByte: _user.networkByte,
                        id: _user.id,
                        seed: _user.seed,
                        privateKey: _user.privateKey,
                        publicKey: _user.publicKey,
                        address: buildAddress({ publicKey: _user.publicKey }, String.fromCharCode(_user.networkByte)),
                        hash: userHash
                    };
                }).filter(Boolean).sort((a, b) => b.lastLogin - a.lastLogin) :
                [];
        }

        /**
         * @param {string} str
         * @returns {string}
         */
        hash(str) {
            return base58Encode(blake2b(base58Decode(str)));
        }

        /**
         * @param {string} privateKeyFrom
         * @param {string} publicKeyTo
         * @param {Object} storageData
         * @returns {string}
         */
        export(privateKeyFrom, publicKeyTo, storageData) {
            return base64Encode(
                messageEncrypt(
                    sharedKey(privateKeyFrom, publicKeyTo, 'waves_migration_token'),
                    JSON.stringify({
                        password: _password,
                        storageData
                    })
                )
            );
        }

    }

    angular.module('app').service('multiAccount', MultiAccount);
})();


text:
<?php

class CiiPHPMessageSource extends CPhpMessageSource
{
	/**
	 * An array of files
	 * @var array
	 */
	private $_files = array();

	/**
	 * Where the extension path is located at
	 * @var array
	 */
	public $extensionPaths = array();

	/**
	 * Constructor
	 * Sets the default basePath to webroot.themes.{{themename}}
	 */
	public function init()
	{
        Yii::app()->language = Cii::setApplicationLanguage();
        parent::init();
		if (isset(Yii::app()->theme) && isset(Yii::app()->theme->name))
			$this->basePath = Yii::getPathOfAlias('base.themes.' . Yii::app()->theme->name . '.messages');
        else if (isset(Yii::app()->controller->module->id))
            $this->basePath = Yii::getPathOfAlias('application.modules.' . Yii::app()->controller->module->id);
		else
			$this->basePath = Yii::getPathOfAlias('application.modules.install');
	}

	/**
	 * Direct overload of getMessageFile
	 *
	 * This method is overloaded to allow modules, themes, and CiiMS Core to have their own unique message sources
	 * instead of having everything grouped together in protected/messages
	 *
	 * Modules and Themes now should have their own /messages folder to store translations
	 *
	 * @param string $category   The category we want to work with
	 * @param string $language   The language we want the string translated to
	 * @return string            File path to the message translation source
	 */
	protected function getMessageFile($category,$language)
	{
	    if(!isset($this->_files[$category][$language]))
	    {
	        if(($pos=strpos($category,'.'))!==false && strpos($category,'ciims') === false)
	        {
	            $extensionClass=substr($category,0,$pos);
	            $extensionCategory=substr($category,$pos+1);

	            // First check if there's an extension registered for this class.
	            if(isset($this->extensionPaths[$extensionClass]))
	                $this->_files[$category][$language]=Yii::getPathOfAlias($this->extensionPaths[$extensionClass]).DS.$language.DS.$extensionCategory.'.php';
	            else
	            {
                    if (strpos($extensionClass, 'themes') !== false)
                    {
                    	$baseClass = explode('.', $extensionCategory);
                    	$theme = $baseClass[0];
                    	unset($baseClass[0]);
                    	$baseClass = implode('.', $baseClass);
                    	$this->_files[$category][$language] = Yii::getPathOfAlias("base.themes.$theme.messages").DS.$language.DS.$baseClass.'.php';
                    }
                    else
                    {
                        // No extension registered, need to find it.
                        if (isset(Yii::app()->controller->module->id))
                            $extensionClass .= 'Module';

                        $class=new ReflectionClass($extensionClass);
                        $this->_files[$category][$language]=dirname($class->getFileName()).DS.'messages'.DS.$language.DS.$extensionCategory.'.php';
                    }
	            }
	        }
	        else
	        {
	        	if (strpos($category,'ciims.') !== false)
	        	{
	        		$this->basePath = Yii::getPathOfAlias('application.messages.');
	        		$this->_files[$category][$language]=$this->basePath.DS.$language.DS.str_replace('.', '/', str_replace('ciims.', '', $category)).'.php';
	        	}
	        	else
					$this->_files[$category][$language]=$this->basePath.DS.$language.DS.$category.'.php';
	        }
	    }

	    return $this->_files[$category][$language];
	}
}


text:
package uk.kludje.experimental.collect.array;

import java.util.Map;
import java.util.Objects;

/**
 * Created by user on 28/12/15.
 */
abstract class AbstractMapEntry<K, V> implements Map.Entry<K, V> {
  protected final K key;
  protected V value;

  protected AbstractMapEntry(K key, V value) {
    this.key = key;
    this.value = value;
  }

  @Override
  public K getKey() {
    return key;
  }

  @Override
  public V getValue() {
    return value;
  }

  @Override
  public boolean equals(Object obj) {
    return (obj instanceof Map.Entry)
        && isEqual((Map.Entry<?, ?>) obj);
  }

  private boolean isEqual(Map.Entry<?, ?> that) {
    if (that == this) {
      return true;
    }

    return Objects.equals(key, that.getKey())
        && Objects.equals(value, that.getValue());
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(key) ^ Objects.hashCode(value);
  }

  @Override
  public String toString() {
    return key + "=" + getValue();
  }
}


text:
/**
 * Created by ran.styr on 17/11/2016.
 */

import { Component, OnInit, Input, ElementRef, ViewChild, EventEmitter } from '@angular/core';
import { DataService } from "../../../../pages/dashboard/data.service";

@Component({
  selector: 'sources-chart',
  template: `

    `
})
export class SourcesChartComponent {
  options: Highcharts.ChartOptions;
  _modelRef: any;

  @Input('dataUpdated') dataUpdated: EventEmitter<any>;
  @ViewChild('chart') el: ElementRef;

  constructor( private _dataService: DataService ) {

  }

  ngAfterViewInit() {
    this.dataUpdated.subscribe(
      ( res ) => {
        if (res.data.propertiesFilterdData) {
          this.renderChart(res.data.propertiesFilterdData, res.data.xAxisDate);
        }
      });
  }

  private calculateData( propertiesFilterdData ) {
    let consolidatedCashReserves = this._dataService.getSumBankAccountsMetrics(propertiesFilterdData);
    let netCashIncome = this._dataService.getSumNetCashIncomeMetrics(propertiesFilterdData);
    let cashInfusion = this._dataService.getSumCashInfusionMetrics(propertiesFilterdData);

    let data = [ {
      name: 'Cash Reserves',
      y: consolidatedCashReserves
    }, {
      name: 'Property Net Income',
      y: netCashIncome
    }, {
      name: 'Refinancing',
      y: cashInfusion
    } ];

    return data;

  }

  public renderChart( propertiesFilterdData, xAxisDate ) {
    if (this.el.nativeElement && this._dataService.getCurrentTab()==='cash') {
      let data = this.calculateData(propertiesFilterdData);
      Highcharts.setOptions({
        lang: {
          thousandsSep: ','
        }
      });
      Highcharts.chart('sourcesChartContainer', {
        chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie',
          backgroundColor: null
        },
        title: {
          align: 'center',
          text: 'Cash Sources'
        },
        labels: {
          formatter: function() {
            return '$' + Highcharts.numberFormat(this.value,0);
          }
        },
        tooltip: {
          pointFormat: '${point.y:.2f} Share: {point.percentage:.1f}%'
        },
        plotOptions: {
          pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
              enabled: false,
              style: {
                fontWeight: 'bold',
                color: '#0F1A36'
              }
            },
            showInLegend: true
          }
        },
        navigation: {
          buttonOptions: {
            theme: {
              fill: "#71B0D9",
              states: {
                hover: {
                  fill: '#5585C0'
                },
                select: {
                  stroke: '#039',
                  fill: '#5585C0'
                }
              }
            }
          }
        },
        series: [ {
          innerSize: '80%',
          name: 'Source',
          colorByPoint: true,
          data: data
        } ]
      });
    }
  }

}


text:
<?php
/**
 * FieldNameSearchListenerTest class file
 */

namespace Graviton\DocumentBundle\Tests\Listener;

use Doctrine\ODM\MongoDB\Query\Builder;
use Graviton\DocumentBundle\Listener\FieldNameSearchListener;
use Graviton\Rql\Event\VisitNodeEvent;
use Graviton\Rql\Node\ElemMatchNode;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Graviton\RqlParser\AbstractNode;
use Graviton\RqlParser\Node\Query\ScalarOperator\EqNode;
use Graviton\RqlParser\Node\Query\AbstractScalarOperatorNode;

/**
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  https://opensource.org/licenses/MIT MIT License
 * @link     http://swisscom.ch
 */
class FieldNameSearchListenerTest extends TestCase
{

    /**
     * Create listener
     *
     * @param array $fields Field mapping
     * @return FieldNameSearchListener
     */
    private function createListener(array $fields)
    {
        return new FieldNameSearchListener($fields);
    }

    /**
     * Test FieldNameSearchListener::onVisitNode() with not query node
     *
     * @return void
     */
    public function testOnVisitNodeWithNotQueryNode()
    {
        $fieldMapping = [];

        $node = $this->getMockBuilder(AbstractNode::class)
            ->disableOriginalConstructor()
            ->getMock();
        $builder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = new VisitNodeEvent($node, $builder, new \SplStack());
        $listener = $this->createListener($fieldMapping);
        $listener->onVisitNode($event);

        $this->assertSame($node, $event->getNode());
        $this->assertSame($builder, $event->getBuilder());
    }

    /**
     * Test FieldNameSearchListener::onVisitNode() with not mapped route
     *
     * @return void
     */
    public function testOnVisitNodeWithNotMappedRoute()
    {
        $fieldMapping = [];
        $this->expectException(\LogicException::class);

        $node = $this->getMockBuilder(AbstractScalarOperatorNode::class)
            ->disableOriginalConstructor()
            ->getMock();
        $node->expects($this->once())
            ->method('getField')
            ->willReturn('field');
        $node->expects($this->never())
            ->method('getValue');

        $builder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = new VisitNodeEvent($node, $builder, new \SplStack());
        $listener = $this->createListener($fieldMapping);
        $listener->onVisitNode($event);
    }

    /**
     * Test FieldNameSearchListener::onVisitNode() with not mapped field
     *
     * @return void
     */
    public function testOnVisitNodeWithNotMappedField()
    {
        $mapping = ['Hans\Class' => []];

        $node = $this->getMockBuilder(AbstractScalarOperatorNode::class)
            ->disableOriginalConstructor()
            ->getMock();
        $node->expects($this->once())
            ->method('getField')
            ->willReturn('field');
        $node->expects($this->never())
            ->method('getValue');

        $builder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = new VisitNodeEvent($node, $builder, new \SplStack(), false, 'Hans\Class');
        $listener = $this->createListener($mapping);
        $listener->onVisitNode($event);

        $this->assertSame($node, $event->getNode());
        $this->assertSame($builder, $event->getBuilder());
    }

    /**
     * Test ExtReferenceSearchListener::onVisitNode() simple
     *
     * @return void
     */
    public function testOnVisitNodeSimple()
    {
        $mapping = ['Hans\Class' => ['field' => '$field']];
        $fieldValue = 'field-value';

        $node = new EqNode('$field', $fieldValue);

        $builder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = new VisitNodeEvent($node, $builder, new \SplStack(), false, 'Hans\Class');
        $listener = $this->createListener($mapping);
        $listener->onVisitNode($event);

        $this->assertNotSame($node, $event->getNode());
        $this->assertSame($builder, $event->getBuilder());

        $this->assertEquals(
            new EqNode('field', $fieldValue),
            $event->getNode()
        );
    }

    /**
     * Test FieldNameSearchListener::onVisitNode() with context
     *
     * @return void
     */
    public function testOnVisitNodeWithContext()
    {
        $mapping = [
            'Hans\Class' => [
                'array'             => '$array',
                'array.0'           => '$array.0',
                'array.0.field'     => '$array.0.$field',
                'array.0.field.ref' => '$array.0.$field.$ref',
            ],
        ];
        $fieldValue = 'field-value';

        $node = new EqNode('$field.$ref', $fieldValue);
        $context = new \SplStack();
        $context->push(new ElemMatchNode('$array', $node));

        $builder = $this->getMockBuilder(Builder::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = new VisitNodeEvent($node, $builder, $context, false, 'Hans\Class');
        $listener = $this->createListener($mapping);
        $listener->onVisitNode($event);

        $this->assertNotSame($node, $event->getNode());
        $this->assertSame($builder, $event->getBuilder());

        $this->assertEquals(
            new EqNode('field.ref', $fieldValue),
            $event->getNode()
        );
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<checkstyle version="6.11.2">
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-rabbitmq/src/main/java/org/apache/flink/streaming/connectors/rabbitmq/common/RMQConnectionConfig.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-rabbitmq/src/main/java/org/apache/flink/streaming/connectors/rabbitmq/RMQSink.java">
</file>
<file name="/Users/oscar/myapps/flink-1.3.2/flink-connectors/flink-connector-rabbitmq/src/main/java/org/apache/flink/streaming/connectors/rabbitmq/RMQSource.java">
</file>
</checkstyle>


text:
package com.aspose.slides.cloud.examples.text;

import android.content.Context;

import java.io.Console;
import java.io.File;
import com.aspose.slides.api.SlidesApi;
import com.aspose.slides.cloud.examples.R;
import com.aspose.slides.cloud.examples.common.Configuration;
import com.aspose.slides.cloud.examples.common.Utils;
import com.aspose.slides.model.SlideStringReplaceResponse;
import com.aspose.storage.api.StorageApi;

public class ReplaceAllInstancesInSlide {

	public static void   execute(Context context)  throws Exception {
		//ExStart: 1
		String fileName = "sampleinput.pptx";
		int slideIndex = 1;
		String oldValue = "aspose";
		String newValue = "apose2";
		boolean ignoreCase = true;
		String folder = "";
		String storage = "";

		File inputFile = Utils.stream2file("sample-input","pptx", context.getResources().openRawResource(R.raw.sampleinput));

		try
		{
			SlidesApi slidesApi = new SlidesApi(Configuration.apiKey, Configuration.appSID);
			StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);

		    // Upload source file to aspose cloud storage
		    storageApi.PutCreate(fileName, "", "",inputFile);

		    // Invoke Aspose.Slides Cloud SDK API to replace all text instances in a slide
		    SlideStringReplaceResponse apiResponse = slidesApi.PostSlidesSlideReplaceText(fileName, slideIndex, oldValue, newValue, ignoreCase, folder, storage);

		    if (apiResponse != null && apiResponse.getStatus().equals("OK"))
		    {
		        // Download updated presentation from cloud storage
		        System.out.println("Replace All Text Instances in a Slide, Done!");

		    }
		}
		catch (Exception ex)
		{
		    ex.printStackTrace();

		}
		//ExEnd: 1
	}

}


text:
namespace intel_x64
{
namespace vtd
{

namespace context_entry
{
	constexpr const auto name = "context_entry";

	using value_type = struct value_type { uint64_t data[2]{0}; };

	namespace p
	{
		constexpr const auto mask = 0x1ULL;
		constexpr const auto index = 0ULL;
		constexpr const auto from = 0ULL;
		constexpr const auto name = "present";

		inline auto is_enabled(const value_type &context_entry) noexcept
		{ return is_bit_set(context_entry.data[index], from); }

		inline auto is_disabled(const value_type &context_entry) noexcept
		{ return !is_bit_set(context_entry.data[index], from); }

		inline void enable(value_type &context_entry) noexcept
		{ context_entry.data[index] = set_bit(context_entry.data[index], from); }

		inline void disable(value_type &context_entry) noexcept
		{ context_entry.data[index] = clear_bit(context_entry.data[index], from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subbool(level, name, is_enabled(context_entry), msg); }
	}

	namespace fpd
	{
		constexpr const auto mask = 0x2ULL;
		constexpr const auto index = 0ULL;
		constexpr const auto from = 1ULL;
		constexpr const auto name = "fault_processing_disable";

		inline auto is_enabled(const value_type &context_entry) noexcept
		{ return is_bit_set(context_entry.data[index], from); }

		inline auto is_disabled(const value_type &context_entry) noexcept
		{ return !is_bit_set(context_entry.data[index], from); }

		inline void enable(value_type &context_entry) noexcept
		{ context_entry.data[index] = set_bit(context_entry.data[index], from); }

		inline void disable(value_type &context_entry) noexcept
		{ context_entry.data[index] = clear_bit(context_entry.data[index], from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subbool(level, name, is_enabled(context_entry), msg); }
	}

	namespace t
	{
		constexpr const auto mask = 0xCULL;
		constexpr const auto index = 0ULL;
		constexpr const auto from = 2ULL;
		constexpr const auto name = "translation_type";

		inline auto get(const value_type &context_entry) noexcept
		{ return get_bits(context_entry.data[index], mask) >> from; }

		inline void set(value_type &context_entry, uint64_t val) noexcept
		{ context_entry.data[index] = set_bits(context_entry.data[index], mask, val << from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subnhex(level, name, get(context_entry), msg); }
	}

	namespace slptptr
	{
		constexpr const auto mask = 0xFFFFFFFFF000ULL;
		constexpr const auto index = 0ULL;
		constexpr const auto from = 12ULL;
		constexpr const auto name = "second_level_page_translation_pointer";

		inline auto get(const value_type &context_entry) noexcept
		{ return get_bits(context_entry.data[index], mask) >> from; }

		inline void set(value_type &context_entry, uint64_t val) noexcept
		{ context_entry.data[index] = set_bits(context_entry.data[index], mask, val << from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subnhex(level, name, get(context_entry), msg); }
	}

	namespace aw
	{
		constexpr const auto mask = 0x7ULL;
		constexpr const auto index = 1ULL;
		constexpr const auto from = 0ULL;
		constexpr const auto name = "address_width";

		inline auto get(const value_type &context_entry) noexcept
		{ return get_bits(context_entry.data[index], mask) >> from; }

		inline void set(value_type &context_entry, uint64_t val) noexcept
		{ context_entry.data[index] = set_bits(context_entry.data[index], mask, val << from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subnhex(level, name, get(context_entry), msg); }
	}

	namespace did
	{
		constexpr const auto mask = 0xFFFF00ULL;
		constexpr const auto index = 1ULL;
		constexpr const auto from = 8ULL;
		constexpr const auto name = "domain_identifier";

		inline auto get(const value_type &context_entry) noexcept
		{ return get_bits(context_entry.data[index], mask) >> from; }

		inline void set(value_type &context_entry, uint64_t val) noexcept
		{ context_entry.data[index] = set_bits(context_entry.data[index], mask, val << from); }

		inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
		{ bfdebug_subnhex(level, name, get(context_entry), msg); }
	}

	inline void dump(int level, const value_type &context_entry, std::string *msg = nullptr)
	{
		bfdebug_nhex(level, "context_entry[63:0]", context_entry.data[0], msg);
		bfdebug_nhex(level, "context_entry[127:64]", context_entry.data[1], msg);

		p::dump(level, context_entry, msg);
		fpd::dump(level, context_entry, msg);
		t::dump(level, context_entry, msg);
		slptptr::dump(level, context_entry, msg);
		aw::dump(level, context_entry, msg);
		did::dump(level, context_entry, msg);
	}
}

}
}

// *INDENT-ON*

#endif


text:
/* @flow */

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getSelectedBlocksMetadata, setBlockData } from 'draftjs-utils';

import LayoutComponent from './Component';

export default class TextAlign extends Component {

  static propTypes = {
    editorState: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    modalHandler: PropTypes.object,
    config: PropTypes.object,
  };

  state = {
    currentTextAlignment: undefined,
  }

  componentWillMount(): void {
    const { modalHandler } = this.props;
    modalHandler.registerCallBack(this.expandCollapse);
  }

  componentWillReceiveProps(properties) {
    if (properties.editorState !== this.props.editorState) {
      this.setState({
        currentTextAlignment: getSelectedBlocksMetadata(properties.editorState).get('text-align'),
      });
    }
  }

  componentWillUnmount(): void {
    const { modalHandler } = this.props;
    modalHandler.deregisterCallBack(this.expandCollapse);
  }

  expandCollapse: Function = (): void => {
    this.setState({
      expanded: this.signalExpanded,
    });
    this.signalExpanded = false;
  }

  onExpandEvent: Function = (): void => {
    this.signalExpanded = !this.state.expanded;
  };

  doExpand: Function = (): void => {
    this.setState({
      expanded: true,
    });
  };

  doCollapse: Function = (): void => {
    this.setState({
      expanded: false,
    });
  };

  addBlockAlignmentData:Function = (value: string) => {
    const { editorState, onChange } = this.props;
    const { currentTextAlignment } = this.state;
    if (currentTextAlignment !== value) {
      onChange(setBlockData(editorState, { 'text-align': value }));
    } else {
      onChange(setBlockData(editorState, { 'text-align': undefined }));
    }
  }

  render(): Object {
    const { config } = this.props;
    const { expanded, currentTextAlignment } = this.state
    const TextAlignmentComponent = config.component || LayoutComponent;
    return (
      <TextAlignmentComponent
        config={config}
        expanded={expanded}
        onExpandEvent={this.onExpandEvent}
        doExpand={this.doExpand}
        doCollapse={this.doCollapse}
        currentState={{ textAlignment: currentTextAlignment }}
        onChange={this.addBlockAlignmentData}
      />
    );
  }
}


text:
package org.apache.hadoop.hdfs.web;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.ws.rs.core.MediaType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.DelegationTokenRenewer;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.HAUtil;
import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
import org.apache.hadoop.hdfs.web.resources.AccessTimeParam;
import org.apache.hadoop.hdfs.web.resources.AclPermissionParam;
import org.apache.hadoop.hdfs.web.resources.BlockSizeParam;
import org.apache.hadoop.hdfs.web.resources.BufferSizeParam;
import org.apache.hadoop.hdfs.web.resources.ConcatSourcesParam;
import org.apache.hadoop.hdfs.web.resources.CreateParentParam;
import org.apache.hadoop.hdfs.web.resources.DelegationParam;
import org.apache.hadoop.hdfs.web.resources.DeleteOpParam;
import org.apache.hadoop.hdfs.web.resources.DestinationParam;
import org.apache.hadoop.hdfs.web.resources.DoAsParam;
import org.apache.hadoop.hdfs.web.resources.GetOpParam;
import org.apache.hadoop.hdfs.web.resources.GroupParam;
import org.apache.hadoop.hdfs.web.resources.HttpOpParam;
import org.apache.hadoop.hdfs.web.resources.LengthParam;
import org.apache.hadoop.hdfs.web.resources.ModificationTimeParam;
import org.apache.hadoop.hdfs.web.resources.OffsetParam;
import org.apache.hadoop.hdfs.web.resources.OverwriteParam;
import org.apache.hadoop.hdfs.web.resources.OwnerParam;
import org.apache.hadoop.hdfs.web.resources.Param;
import org.apache.hadoop.hdfs.web.resources.PermissionParam;
import org.apache.hadoop.hdfs.web.resources.PostOpParam;
import org.apache.hadoop.hdfs.web.resources.PutOpParam;
import org.apache.hadoop.hdfs.web.resources.RecursiveParam;
import org.apache.hadoop.hdfs.web.resources.RenameOptionSetParam;
import org.apache.hadoop.hdfs.web.resources.RenewerParam;
import org.apache.hadoop.hdfs.web.resources.ReplicationParam;
import org.apache.hadoop.hdfs.web.resources.TokenArgumentParam;
import org.apache.hadoop.hdfs.web.resources.UserParam;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.retry.RetryPolicies;
import org.apache.hadoop.io.retry.RetryPolicy;
import org.apache.hadoop.io.retry.RetryUtils;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.Progressable;
import org.mortbay.util.ajax.JSON;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;

/** A FileSystem for HDFS over the web. */
public class WebHdfsFileSystem extends FileSystem
    implements DelegationTokenRenewer.Renewable, TokenAspect.TokenManagementDelegator {
  public static final Log LOG = LogFactory.getLog(WebHdfsFileSystem.class);
  /** File System URI: {SCHEME}://namenode:port/path/to/file */
  public static final String SCHEME = "webhdfs";
  /** WebHdfs version. */
  public static final int VERSION = 1;
  /** Http URI: http://namenode:port/{PATH_PREFIX}/path/to/file */
  public static final String PATH_PREFIX = "/" + SCHEME + "/v" + VERSION;

  /** Default connection factory may be overridden in tests to use smaller timeout values */
  protected URLConnectionFactory connectionFactory;

  /** Delegation token kind */
  public static final Text TOKEN_KIND = new Text("WEBHDFS delegation");
  protected TokenAspect<? extends WebHdfsFileSystem> tokenAspect;

  private UserGroupInformation ugi;
  private URI uri;
  private Token<?> delegationToken;
  protected Text tokenServiceName;
  private RetryPolicy retryPolicy = null;
  private Path workingDir;
  private InetSocketAddress nnAddrs[];
  private int currentNNAddrIndex;

  /**
   * Return the protocol scheme for the FileSystem.
   *

   *
   * @return webhdfs
   */
  @Override
  public String getScheme() {
    return SCHEME;
  }

  /**
   * return the underlying transport protocol (http / https).
   */
  protected String getTransportScheme() {
    return "http";
  }

  /**
   * Initialize tokenAspect. This function is intended to
   * be overridden by SWebHdfsFileSystem.
   */
  protected synchronized void initializeTokenAspect() {
    tokenAspect = new TokenAspect<WebHdfsFileSystem>(this, tokenServiceName,
        TOKEN_KIND);
  }

  @Override
  public synchronized void initialize(URI uri, Configuration conf
      ) throws IOException {
    super.initialize(uri, conf);
    setConf(conf);
    /** set user pattern based on configuration file */
    UserParam.setUserPattern(conf.get(
        DFSConfigKeys.DFS_WEBHDFS_USER_PATTERN_KEY,
        DFSConfigKeys.DFS_WEBHDFS_USER_PATTERN_DEFAULT));

    connectionFactory = URLConnectionFactory
        .newDefaultURLConnectionFactory(conf);

    ugi = UserGroupInformation.getCurrentUser();
    this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
    this.nnAddrs = DFSUtil.resolveWebHdfsUri(this.uri, conf);

    boolean isHA = HAUtil.isLogicalUri(conf, this.uri);
    // In non-HA case, the code needs to call getCanonicalUri() in order to
    // handle the case where no port is specified in the URI
    this.tokenServiceName = isHA ? HAUtil.buildTokenServiceForLogicalUri(uri)
        : SecurityUtil.buildTokenService(getCanonicalUri());
    initializeTokenAspect();

    if (!isHA) {
      this.retryPolicy =
          RetryUtils.getDefaultRetryPolicy(
              conf,
              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY,
              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT,
              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY,
              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT,
              SafeModeException.class);
    } else {

      int maxFailoverAttempts = conf.getInt(
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY,
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT);
      int maxRetryAttempts = conf.getInt(
          DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_MAX_ATTEMPTS_KEY,
          DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_MAX_ATTEMPTS_DEFAULT);
      int failoverSleepBaseMillis = conf.getInt(
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY,
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT);
      int failoverSleepMaxMillis = conf.getInt(
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT);

      this.retryPolicy = RetryPolicies
          .failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL,
              maxFailoverAttempts, maxRetryAttempts, failoverSleepBaseMillis,
              failoverSleepMaxMillis);
    }

    this.workingDir = getHomeDirectory();

    if (UserGroupInformation.isSecurityEnabled()) {
      tokenAspect.initDelegationToken(ugi);
    }
  }

  @Override
  public URI getCanonicalUri() {
    return super.getCanonicalUri();
  }

  /** Is WebHDFS enabled in conf? */
  public static boolean isEnabled(final Configuration conf, final Log log) {
    final boolean b = conf.getBoolean(DFSConfigKeys.DFS_WEBHDFS_ENABLED_KEY,
        DFSConfigKeys.DFS_WEBHDFS_ENABLED_DEFAULT);
    return b;
  }

  protected synchronized Token<?> getDelegationToken() throws IOException {
    tokenAspect.ensureTokenInitialized();
    return delegationToken;
  }

  @Override
  protected int getDefaultPort() {
    return getConf().getInt(DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_KEY,
        DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_DEFAULT);
  }

  @Override
  public URI getUri() {
    return this.uri;
  }

  @Override
  protected URI canonicalizeUri(URI uri) {
    return NetUtils.getCanonicalUri(uri, getDefaultPort());
  }

  /** @return the home directory. */
  public static String getHomeDirectoryString(final UserGroupInformation ugi) {
    return "/user/" + ugi.getShortUserName();
  }

  @Override
  public Path getHomeDirectory() {
    return makeQualified(new Path(getHomeDirectoryString(ugi)));
  }

  @Override
  public synchronized Path getWorkingDirectory() {
    return workingDir;
  }

  @Override
  public synchronized void setWorkingDirectory(final Path dir) {
    String result = makeAbsolute(dir).toUri().getPath();
    if (!DFSUtil.isValidName(result)) {
      throw new IllegalArgumentException("Invalid DFS directory name " +
                                         result);
    }
    workingDir = makeAbsolute(dir);
  }

  private Path makeAbsolute(Path f) {
    return f.isAbsolute()? f: new Path(workingDir, f);
  }

  static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
      ) throws IOException {
    if (c.getContentLength() == 0) {
      return null;
    }
    final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
    if (in == null) {
      throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
    }
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    return (Map<?, ?>)JSON.parse(new InputStreamReader(in, Charsets.UTF_8));
  }

  private static Map<?, ?> validateResponse(final HttpOpParam.Op op,
      final HttpURLConnection conn, boolean unwrapException) throws IOException {
    final int code = conn.getResponseCode();
    // server is demanding an authentication we don't support
    if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
      throw new IOException(
          new AuthenticationException(conn.getResponseMessage()));
    }
    if (code != op.getExpectedHttpResponseCode()) {
      final Map<?, ?> m;
      try {
        m = jsonParse(conn, true);
      } catch(Exception e) {
        throw new IOException("Unexpected HTTP response: code=" + code + " != "
            + op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
            + ", message=" + conn.getResponseMessage(), e);
      }

      if (m == null) {
        throw new IOException("Unexpected HTTP response: code=" + code + " != "
            + op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
            + ", message=" + conn.getResponseMessage());
      } else if (m.get(RemoteException.class.getSimpleName()) == null) {
        return m;
      }

      final RemoteException re = JsonUtil.toRemoteException(m);
      throw unwrapException? toIOException(re): re;
    }
    return null;
  }

  /**
   * Covert an exception to an IOException.
   *
   * For a non-IOException, wrap it with IOException.
   * For a RemoteException, unwrap it.
   * For an IOException which is not a RemoteException, return it.
   */
  private static IOException toIOException(Exception e) {
    if (!(e instanceof IOException)) {
      return new IOException(e);
    }

    final IOException ioe = (IOException)e;
    if (!(ioe instanceof RemoteException)) {
      return ioe;
    }

    return ((RemoteException)ioe).unwrapRemoteException();
  }

  private synchronized InetSocketAddress getCurrentNNAddr() {
    return nnAddrs[currentNNAddrIndex];
  }

  /**
   * Reset the appropriate state to gracefully fail over to another name node
   */
  private synchronized void resetStateToFailOver() {
    currentNNAddrIndex = (currentNNAddrIndex + 1) % nnAddrs.length;
    delegationToken = null;
    tokenAspect.reset();
  }

  /**
   * Return a URL pointing to given path on the namenode.
   *
   * @param path to obtain the URL for
   * @param query string to append to the path
   * @return namenode URL referring to the given path
   * @throws IOException on error constructing the URL
   */
  private URL getNamenodeURL(String path, String query) throws IOException {
    InetSocketAddress nnAddr = getCurrentNNAddr();
    final URL url = new URL(getTransportScheme(), nnAddr.getHostName(),
          nnAddr.getPort(), path + '?' + query);
    if (LOG.isTraceEnabled()) {
      LOG.trace("url=" + url);
    }
    return url;
  }

  Param<?,?>[] getAuthParameters(final HttpOpParam.Op op) throws IOException {
    List<Param<?,?>> authParams = Lists.newArrayList();
    // Skip adding delegation token for token operations because these
    // operations require authentication.
    Token<?> token = null;
    if (UserGroupInformation.isSecurityEnabled() && !op.getRequireAuth()) {
      token = getDelegationToken();
    }
    if (token != null) {
      authParams.add(new DelegationParam(token.encodeToUrlString()));
    } else {
      UserGroupInformation userUgi = ugi;
      UserGroupInformation realUgi = userUgi.getRealUser();
      if (realUgi != null) { // proxy user
        authParams.add(new DoAsParam(userUgi.getShortUserName()));
        userUgi = realUgi;
      }
      authParams.add(new UserParam(userUgi.getShortUserName()));
    }
    return authParams.toArray(new Param<?,?>[0]);
  }

  URL toUrl(final HttpOpParam.Op op, final Path fspath,
      final Param<?,?>... parameters) throws IOException {
    //initialize URI path and query
    final String path = PATH_PREFIX
        + (fspath == null? "/": makeQualified(fspath).toUri().getRawPath());
    final String query = op.toQueryString()
        + Param.toSortedString("&", getAuthParameters(op))
        + Param.toSortedString("&", parameters);
    final URL url = getNamenodeURL(path, query);
    if (LOG.isTraceEnabled()) {
      LOG.trace("url=" + url);
    }
    return url;
  }

  /**
   * Run a http operation.
   * Connect to the http server, validate response, and obtain the JSON output.
   *
   * @param op http operation
   * @param fspath file system path
   * @param parameters parameters for the operation
   * @return a JSON object, e.g. Object[], Map<?, ?>, etc.
   * @throws IOException
   */
  private Map<?, ?> run(final HttpOpParam.Op op, final Path fspath,
      final Param<?,?>... parameters) throws IOException {
    return new FsPathRunner(op, fspath, parameters).run().json;
  }

  /**
   * This class is for initialing a HTTP connection, connecting to server,
   * obtaining a response, and also handling retry on failures.
   */
  abstract class AbstractRunner {
    abstract protected URL getUrl() throws IOException;

    protected final HttpOpParam.Op op;
    private final boolean redirected;

    private boolean checkRetry;
    protected HttpURLConnection conn = null;
    private Map<?, ?> json = null;

    protected AbstractRunner(final HttpOpParam.Op op, boolean redirected) {
      this.op = op;
      this.redirected = redirected;
    }

    AbstractRunner run() throws IOException {
      UserGroupInformation connectUgi = ugi.getRealUser();
      if (connectUgi == null) {
        connectUgi = ugi;
      }
      if (op.getRequireAuth()) {
        connectUgi.checkTGTAndReloginFromKeytab();
      }
      try {
        // the entire lifecycle of the connection must be run inside the
        // doAs to ensure authentication is performed correctly
        return connectUgi.doAs(
            new PrivilegedExceptionAction<AbstractRunner>() {
              @Override
              public AbstractRunner run() throws IOException {
                return runWithRetry();
              }
            });
      } catch (InterruptedException e) {
        throw new IOException(e);
      }
    }

    private void init() throws IOException {
      checkRetry = !redirected;
      URL url = getUrl();
      conn = (HttpURLConnection) connectionFactory.openConnection(url);
    }

    private void connect() throws IOException {
      connect(op.getDoOutput());
    }

    private void connect(boolean doOutput) throws IOException {
      conn.setRequestMethod(op.getType().toString());
      conn.setDoOutput(doOutput);
      conn.setInstanceFollowRedirects(false);
      conn.connect();
    }

    private void disconnect() {
      if (conn != null) {
        conn.disconnect();
        conn = null;
      }
    }

    private AbstractRunner runWithRetry() throws IOException {
      /**
       * Do the real work.
       *
       * There are three cases that the code inside the loop can throw an
       * IOException:
       *
       *

       *
The connection has failed (e.g., ConnectException,
       * @see FailoverOnNetworkExceptionRetry for more details)

       *
The namenode enters the standby state (i.e., StandbyException).

       *
The server returns errors for the command (i.e., RemoteException)

       *

       *
       * The call to shouldRetry() will conduct the retry policy. The policy
       * examines the exception and swallows it if it decides to rerun the work.
       */
      for(int retry = 0; ; retry++) {
        try {
          init();
          if (op.getDoOutput()) {
            twoStepWrite();
          } else {
            getResponse(op != GetOpParam.Op.OPEN);
          }
          return this;
        } catch(IOException ioe) {
          Throwable cause = ioe.getCause();
          if (cause != null && cause instanceof AuthenticationException) {
            throw ioe; // no retries for auth failures
          }
          shouldRetry(ioe, retry);
        }
      }
    }

    private void shouldRetry(final IOException ioe, final int retry
        ) throws IOException {
      InetSocketAddress nnAddr = getCurrentNNAddr();
      if (checkRetry) {
        try {
          final RetryPolicy.RetryAction a = retryPolicy.shouldRetry(
              ioe, retry, 0, true);

          boolean isRetry = a.action == RetryPolicy.RetryAction.RetryDecision.RETRY;
          boolean isFailoverAndRetry =
              a.action == RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY;

          if (isRetry || isFailoverAndRetry) {
            LOG.info("Retrying connect to namenode: " + nnAddr
                + ". Already tried " + retry + " time(s); retry policy is "
                + retryPolicy + ", delay " + a.delayMillis + "ms.");

            if (isFailoverAndRetry) {
              resetStateToFailOver();
            }

            Thread.sleep(a.delayMillis);
            return;
          }
        } catch(Exception e) {
          LOG.warn("Original exception is ", ioe);
          throw toIOException(e);
        }
      }
      throw toIOException(ioe);
    }

    /**
     * Two-step Create/Append:
     * Step 1) Submit a Http request with neither auto-redirect nor data.
     * Step 2) Submit another Http request with the URL from the Location header with data.
     *
     * The reason of having two-step create/append is for preventing clients to
     * send out the data before the redirect. This issue is addressed by the
     * "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
     * Unfortunately, there are software library bugs (e.g. Jetty 6 http server
     * and Java 6 http client), which do not correctly implement "Expect:
     * 100-continue". The two-step create/append is a temporary workaround for
     * the software library bugs.
     */
    HttpURLConnection twoStepWrite() throws IOException {
      //Step 1) Submit a Http request with neither auto-redirect nor data.
      connect(false);
      validateResponse(HttpOpParam.TemporaryRedirectOp.valueOf(op), conn, false);
      final String redirect = conn.getHeaderField("Location");
      disconnect();
      checkRetry = false;

      //Step 2) Submit another Http request with the URL from the Location header with data.
      conn = (HttpURLConnection) connectionFactory.openConnection(new URL(
          redirect));
      conn.setRequestProperty("Content-Type",
          MediaType.APPLICATION_OCTET_STREAM);
      conn.setChunkedStreamingMode(32 << 10); //32kB-chunk
      connect();
      return conn;
    }

    FSDataOutputStream write(final int bufferSize) throws IOException {
      return WebHdfsFileSystem.this.write(op, conn, bufferSize);
    }

    void getResponse(boolean getJsonAndDisconnect) throws IOException {
      try {
        connect();
        final int code = conn.getResponseCode();
        if (!redirected && op.getRedirect()
            && code != op.getExpectedHttpResponseCode()) {
          final String redirect = conn.getHeaderField("Location");
          json = validateResponse(HttpOpParam.TemporaryRedirectOp.valueOf(op),
              conn, false);
          disconnect();

          checkRetry = false;
          conn = (HttpURLConnection) connectionFactory.openConnection(new URL(
              redirect));
          connect();
        }

        json = validateResponse(op, conn, false);
        if (json == null && getJsonAndDisconnect) {
          json = jsonParse(conn, false);
        }
      } finally {
        if (getJsonAndDisconnect) {
          disconnect();
        }
      }
    }
  }

  final class FsPathRunner extends AbstractRunner {
    private final Path fspath;
    private final Param<?, ?>[] parameters;

    FsPathRunner(final HttpOpParam.Op op, final Path fspath, final Param<?,?>... parameters) {
      super(op, false);
      this.fspath = fspath;
      this.parameters = parameters;
    }

    @Override
    protected URL getUrl() throws IOException {
      return toUrl(op, fspath, parameters);
    }
  }

  final class URLRunner extends AbstractRunner {
    private final URL url;
    @Override
    protected URL getUrl() {
      return url;
    }

    protected URLRunner(final HttpOpParam.Op op, final URL url, boolean redirected) {
      super(op, redirected);
      this.url = url;
    }
  }

  private FsPermission applyUMask(FsPermission permission) {
    if (permission == null) {
      permission = FsPermission.getDefault();
    }
    return permission.applyUMask(FsPermission.getUMask(getConf()));
  }

  private HdfsFileStatus getHdfsFileStatus(Path f) throws IOException {
    final HttpOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
    final Map<?, ?> json = run(op, f);
    final HdfsFileStatus status = JsonUtil.toFileStatus(json, true);
    if (status == null) {
      throw new FileNotFoundException("File does not exist: " + f);
    }
    return status;
  }

  @Override
  public FileStatus getFileStatus(Path f) throws IOException {
    statistics.incrementReadOps(1);
    return makeQualified(getHdfsFileStatus(f), f);
  }

  private FileStatus makeQualified(HdfsFileStatus f, Path parent) {
    return new FileStatus(f.getLen(), f.isDir(), f.getReplication(),
        f.getBlockSize(), f.getModificationTime(), f.getAccessTime(),
        f.getPermission(), f.getOwner(), f.getGroup(),
        f.isSymlink() ? new Path(f.getSymlink()) : null,
        f.getFullPath(parent).makeQualified(getUri(), getWorkingDirectory()));
  }

  @Override
  public AclStatus getAclStatus(Path f) throws IOException {
    final HttpOpParam.Op op = GetOpParam.Op.GETACLSTATUS;
    final Map<?, ?> json = run(op, f);
    AclStatus status = JsonUtil.toAclStatus(json);
    if (status == null) {
      throw new FileNotFoundException("File does not exist: " + f);
    }
    return status;
  }

  @Override
  public boolean mkdirs(Path f, FsPermission permission) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.MKDIRS;
    final Map<?, ?> json = run(op, f,
        new PermissionParam(applyUMask(permission)));
    return (Boolean)json.get("boolean");
  }

  /**
   * Create a symlink pointing to the destination path.
   * @see org.apache.hadoop.fs.Hdfs#createSymlink(Path, Path, boolean)
   */
  public void createSymlink(Path destination, Path f, boolean createParent
      ) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.CREATESYMLINK;
    run(op, f, new DestinationParam(makeQualified(destination).toUri().getPath()),
        new CreateParentParam(createParent));
  }

  @Override
  public boolean rename(final Path src, final Path dst) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.RENAME;
    final Map<?, ?> json = run(op, src,
        new DestinationParam(makeQualified(dst).toUri().getPath()));
    return (Boolean)json.get("boolean");
  }

  @SuppressWarnings("deprecation")
  @Override
  public void rename(final Path src, final Path dst,
      final Options.Rename... options) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.RENAME;
    run(op, src, new DestinationParam(makeQualified(dst).toUri().getPath()),
        new RenameOptionSetParam(options));
  }

  @Override
  public void setOwner(final Path p, final String owner, final String group
      ) throws IOException {
    if (owner == null && group == null) {
      throw new IOException("owner == null && group == null");
    }

    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.SETOWNER;
    run(op, p, new OwnerParam(owner), new GroupParam(group));
  }

  @Override
  public void setPermission(final Path p, final FsPermission permission
      ) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.SETPERMISSION;
    run(op, p, new PermissionParam(permission));
  }

  @Override
  public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
      throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.MODIFYACLENTRIES;
    run(op, path, new AclPermissionParam(aclSpec));
  }

  @Override
  public void removeAclEntries(Path path, List<AclEntry> aclSpec)
      throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.REMOVEACLENTRIES;
    run(op, path, new AclPermissionParam(aclSpec));
  }

  @Override
  public void removeDefaultAcl(Path path) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.REMOVEDEFAULTACL;
    run(op, path);
  }

  @Override
  public void removeAcl(Path path) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.REMOVEACL;
    run(op, path);
  }

  @Override
  public void setAcl(final Path p, final List<AclEntry> aclSpec)
      throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.SETACL;
    run(op, p, new AclPermissionParam(aclSpec));
  }

  @Override
  public boolean setReplication(final Path p, final short replication
     ) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.SETREPLICATION;
    final Map<?, ?> json = run(op, p, new ReplicationParam(replication));
    return (Boolean)json.get("boolean");
  }

  @Override
  public void setTimes(final Path p, final long mtime, final long atime
      ) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PutOpParam.Op.SETTIMES;
    run(op, p, new ModificationTimeParam(mtime), new AccessTimeParam(atime));
  }

  @Override
  public long getDefaultBlockSize() {
    return getConf().getLongBytes(DFSConfigKeys.DFS_BLOCK_SIZE_KEY,
        DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
  }

  @Override
  public short getDefaultReplication() {
    return (short)getConf().getInt(DFSConfigKeys.DFS_REPLICATION_KEY,
        DFSConfigKeys.DFS_REPLICATION_DEFAULT);
  }

  FSDataOutputStream write(final HttpOpParam.Op op,
      final HttpURLConnection conn, final int bufferSize) throws IOException {
    return new FSDataOutputStream(new BufferedOutputStream(
        conn.getOutputStream(), bufferSize), statistics) {
      @Override
      public void close() throws IOException {
        try {
          super.close();
        } finally {
          try {
            validateResponse(op, conn, true);
          } finally {
            conn.disconnect();
          }
        }
      }
    };
  }

  @Override
  public void concat(final Path trg, final Path [] srcs) throws IOException {
    statistics.incrementWriteOps(1);
    final HttpOpParam.Op op = PostOpParam.Op.CONCAT;

    ConcatSourcesParam param = new ConcatSourcesParam(srcs);
    run(op, trg, param);
  }

  @Override
  public FSDataOutputStream create(final Path f, final FsPermission permission,
      final boolean overwrite, final int bufferSize, final short replication,
      final long blockSize, final Progressable progress) throws IOException {
    statistics.incrementWriteOps(1);

    final HttpOpParam.Op op = PutOpParam.Op.CREATE;
    return new FsPathRunner(op, f,
        new PermissionParam(applyUMask(permission)),
        new OverwriteParam(overwrite),
        new BufferSizeParam(bufferSize),
        new ReplicationParam(replication),
        new BlockSizeParam(blockSize))
      .run()
      .write(bufferSize);
  }

  @Override
  public FSDataOutputStream append(final Path f, final int bufferSize,
      final Progressable progress) throws IOException {
    statistics.incrementWriteOps(1);

    final HttpOpParam.Op op = PostOpParam.Op.APPEND;
    return new FsPathRunner(op, f, new BufferSizeParam(bufferSize))
      .run()
      .write(bufferSize);
  }

  @Override
  public boolean delete(Path f, boolean recursive) throws IOException {
    final HttpOpParam.Op op = DeleteOpParam.Op.DELETE;
    final Map<?, ?> json = run(op, f, new RecursiveParam(recursive));
    return (Boolean)json.get("boolean");
  }

  @Override
  public FSDataInputStream open(final Path f, final int buffersize
      ) throws IOException {
    statistics.incrementReadOps(1);
    final HttpOpParam.Op op = GetOpParam.Op.OPEN;
    final URL url = toUrl(op, f, new BufferSizeParam(buffersize));
    return new FSDataInputStream(new OffsetUrlInputStream(
        new OffsetUrlOpener(url), new OffsetUrlOpener(null)));
  }

  @Override
  public void close() throws IOException {
    super.close();
    synchronized (this) {
      tokenAspect.removeRenewAction();
    }
  }

  class OffsetUrlOpener extends ByteRangeInputStream.URLOpener {
    OffsetUrlOpener(final URL url) {
      super(url);
    }

    /** Setup offset url and connect. */
    @Override
    protected HttpURLConnection connect(final long offset,
        final boolean resolved) throws IOException {
      final URL offsetUrl = offset == 0L? url
          : new URL(url + "&" + new OffsetParam(offset));
      return new URLRunner(GetOpParam.Op.OPEN, offsetUrl, resolved).run().conn;
    }
  }

  private static final String OFFSET_PARAM_PREFIX = OffsetParam.NAME + "=";

  /** Remove offset parameter, if there is any, from the url */
  static URL removeOffsetParam(final URL url) throws MalformedURLException {
    String query = url.getQuery();
    if (query == null) {
      return url;
    }
    final String lower = query.toLowerCase();
    if (!lower.startsWith(OFFSET_PARAM_PREFIX)
        && !lower.contains("&" + OFFSET_PARAM_PREFIX)) {
      return url;
    }

    //rebuild query
    StringBuilder b = null;
    for(final StringTokenizer st = new StringTokenizer(query, "&");
        st.hasMoreTokens();) {
      final String token = st.nextToken();
      if (!token.toLowerCase().startsWith(OFFSET_PARAM_PREFIX)) {
        if (b == null) {
          b = new StringBuilder("?").append(token);
        } else {
          b.append('&').append(token);
        }
      }
    }
    query = b == null? "": b.toString();

    final String urlStr = url.toString();
    return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
  }

  static class OffsetUrlInputStream extends ByteRangeInputStream {
    OffsetUrlInputStream(OffsetUrlOpener o, OffsetUrlOpener r) {
      super(o, r);
    }

    /** Remove offset parameter before returning the resolved url. */
    @Override
    protected URL getResolvedUrl(final HttpURLConnection connection
        ) throws MalformedURLException {
      return removeOffsetParam(connection.getURL());
    }
  }

  @Override
  public FileStatus[] listStatus(final Path f) throws IOException {
    statistics.incrementReadOps(1);

    final HttpOpParam.Op op = GetOpParam.Op.LISTSTATUS;
    final Map<?, ?> json  = run(op, f);
    final Map<?, ?> rootmap = (Map<?, ?>)json.get(FileStatus.class.getSimpleName() + "es");
    final Object[] array = (Object[])rootmap.get(FileStatus.class.getSimpleName());

    //convert FileStatus
    final FileStatus[] statuses = new FileStatus[array.length];
    for(int i = 0; i < array.length; i++) {
      final Map<?, ?> m = (Map<?, ?>)array[i];
      statuses[i] = makeQualified(JsonUtil.toFileStatus(m, false), f);
    }
    return statuses;
  }

  @Override
  public Token<DelegationTokenIdentifier> getDelegationToken(
      final String renewer) throws IOException {
    final HttpOpParam.Op op = GetOpParam.Op.GETDELEGATIONTOKEN;
    final Map<?, ?> m = run(op, null, new RenewerParam(renewer));
    final Token<DelegationTokenIdentifier> token = JsonUtil.toDelegationToken(m);
    token.setService(tokenServiceName);
    return token;
  }

  @Override
  public synchronized Token<?> getRenewToken() {
    return delegationToken;
  }

  @Override
  public <T extends TokenIdentifier> void setDelegationToken(
      final Token<T> token) {
    synchronized (this) {
      delegationToken = token;
    }
  }

  @Override
  public synchronized long renewDelegationToken(final Token<?> token
      ) throws IOException {
    final HttpOpParam.Op op = PutOpParam.Op.RENEWDELEGATIONTOKEN;
    TokenArgumentParam dtargParam = new TokenArgumentParam(
        token.encodeToUrlString());
    final Map<?, ?> m = run(op, null, dtargParam);
    return (Long) m.get("long");
  }

  @Override
  public synchronized void cancelDelegationToken(final Token<?> token
      ) throws IOException {
    final HttpOpParam.Op op = PutOpParam.Op.CANCELDELEGATIONTOKEN;
    TokenArgumentParam dtargParam = new TokenArgumentParam(
        token.encodeToUrlString());
    run(op, null, dtargParam);
  }

  @Override
  public BlockLocation[] getFileBlockLocations(final FileStatus status,
      final long offset, final long length) throws IOException {
    if (status == null) {
      return null;
    }
    return getFileBlockLocations(status.getPath(), offset, length);
  }

  @Override
  public BlockLocation[] getFileBlockLocations(final Path p,
      final long offset, final long length) throws IOException {
    statistics.incrementReadOps(1);

    final HttpOpParam.Op op = GetOpParam.Op.GET_BLOCK_LOCATIONS;
    final Map<?, ?> m = run(op, p, new OffsetParam(offset),
        new LengthParam(length));
    return DFSUtil.locatedBlocks2Locations(JsonUtil.toLocatedBlocks(m));
  }

  @Override
  public ContentSummary getContentSummary(final Path p) throws IOException {
    statistics.incrementReadOps(1);

    final HttpOpParam.Op op = GetOpParam.Op.GETCONTENTSUMMARY;
    final Map<?, ?> m = run(op, p);
    return JsonUtil.toContentSummary(m);
  }

  @Override
  public MD5MD5CRC32FileChecksum getFileChecksum(final Path p
      ) throws IOException {
    statistics.incrementReadOps(1);

    final HttpOpParam.Op op = GetOpParam.Op.GETFILECHECKSUM;
    final Map<?, ?> m = run(op, p);
    return JsonUtil.toMD5MD5CRC32FileChecksum(m);
  }

  @Override
  public String getCanonicalServiceName() {
    return tokenServiceName == null ? super.getCanonicalServiceName()
        : tokenServiceName.toString();
  }

  @VisibleForTesting
  InetSocketAddress[] getResolvedNNAddr() {
    return nnAddrs;
  }
}


text:
local Stack = require 'stack'

describe('Stack', function()
  describe(':push', function()
    it('adds an element to the stack', function()
      local stack = Stack:new()
      stack:push(1)

      assert.are.equal(1, #stack._stack)
    end)

    it('records minimum values when inserted', function()
      local stack = Stack:new()
      stack:push(1)

      assert.are.equal(1, stack:min())
    end)
  end)

  describe(':pop', function()
    it('removes and returns the top element', function()
      local stack = Stack:new()
      stack:push(1)

      local top = stack:pop()

      assert.are.equal(1, top)
      assert.are.equal(0, #stack._stack)
    end)

    it('returns nil for an empty stack', function()
      local stack = Stack:new()
      local top = stack:pop()

      assert.is_nil(top)
    end)

    it('removes min from stack if the top element was minimal', function()
      local stack = Stack:new()
      stack:push(1)
      stack:pop()

      assert.is_nil(stack:min())
    end)
  end)

  describe(':min', function()
    it('returns the minimum value in the stack', function()
      local stack = Stack:new()
      stack:push(1)
      stack:push(2)
      local min = stack:min()

      assert.are.equal(1, min)
    end)

    it('returns nil for an empty stack', function()
      local stack = Stack:new()
      local min = stack:min()

      assert.is_nil(min)
    end)

    it('resets min after a minimum value was popped', function()
      local stack = Stack:new()
      stack:push(2)
      stack:push(1)
      stack:pop()

      assert.are.equal(2, stack:min())
    end)
  end)

  describe(':max', function()
    it('returns the maximum value in the stack', function()
      local stack = Stack:new()
      stack:push(1)
      stack:push(2)
      local max = stack:max()

      assert.are.equal(2, max)
    end)

    it('returns nil for an empty stack', function()
      local stack = Stack:new()
      local max = stack:max()

      assert.is_nil(max)
    end)

    it('resets min after a minimum value was popped', function()
      local stack = Stack:new()
      stack:push(1)
      stack:push(2)
      stack:pop()

      assert.are.equal(1, stack:max())
    end)
  end)
end)


text:
static OGRSpatialReferenceH srsFromWkt(const std::string &wkt)
{
    // horrific gdal design for import from wkt
    // it will change pointer(should not destroy any data)
    // it also asks for pointer to non-const data (std::string without const cast won't do)
    if (wkt.size() > 1024)
    {
        return NULL;
    }
    char **fromSRSWkt = new char*[2];
    fromSRSWkt[0] = new char[wkt.size()+1];
    strcpy(fromSRSWkt[0], wkt.c_str()); fromSRSWkt[wkt.size()] = 0;
    fromSRSWkt[1] = NULL;
    OGRSpatialReferenceH srs = OSRNewSpatialReference(NULL);
    OGRErr err = OSRImportFromWkt(srs, fromSRSWkt);
    delete fromSRSWkt[0];
    delete fromSRSWkt;
    if (OGRERR_NONE != err)
    {
        std::cout << "Failed to create Spatial Reference fron wkt: " << wkt << std::endl;
        OSRDestroySpatialReference(srs);
        return NULL;
    }
    return srs;
}

static OGRSpatialReferenceH srsFromEpsg(const int epsg)
{
    OGRSpatialReferenceH srs = OSRNewSpatialReference(NULL);
    OGRErr err = OSRImportFromEPSG(srs, epsg);
    if (OGRERR_NONE != err)
    {
        std::cout << "Failed to create Spatial Reference fron epsg: " << epsg << std::endl;
        OSRDestroySpatialReference(srs);
        return NULL;
    }
    return srs;
}

static void srsDestroy(OGRSpatialReferenceH srs)
{
    if (srs)
        OSRDestroySpatialReference(srs);
}

static bool transformPoints(double *__restrict x,
                            double *__restrict y,
                            int count,
                            OGRSpatialReferenceH __restrict fromSRS,
                            OGRSpatialReferenceH __restrict toSRS)
{
    if (!fromSRS||!toSRS)
        return false;
    if (fromSRS==toSRS)
        return true;

    OGRCoordinateTransformationH warp = OCTNewCoordinateTransformation(fromSRS, toSRS);
    if (!warp)
    {
        std::cout << "Failed to create Coordinate Transformation" << std::endl;
        return false;
    }

    bool result = (TRUE == OCTTransform(warp, count, x, y, NULL));
    OCTDestroyCoordinateTransformation(warp);

    return result;
}

#endif // GDALTRANSFORM_H


text:
'use strict'

const Handler = require('./handler')

const Routes = [
  {
    method: 'GET',
    path: '/',
    config: Handler.index
  },
  {
    method: 'GET',
    path: '/auth/gitlab',
    config: Handler.connect
  },
  {
    method: 'GET',
    path: '/logout',
    config: Handler.logout
  }
]

module.exports = Routes