text:
package network::cisco::firepower::fmc::restapi::mode::devices;

use base qw(centreon::plugins::templates::counter);

use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold_ng);

sub custom_device_status_output {
    my ($self, %options) = @_;

    return 'status: ' . $self->{result_values}->{status};
}

sub domain_long_output {
    my ($self, %options) = @_;

    return "checking domain '" . $options{instance_value}->{name} . "'";
}

sub prefix_domain_output {
    my ($self, %options) = @_;

    return "Domain '" . $options{instance_value}->{name} . "' ";
}

sub prefix_device_output {
    my ($self, %options) = @_;

    return "device '" . $options{instance_value}->{name} . "' ";
}

sub prefix_global_output {
    my ($self, %options) = @_;

    return 'Devices ';
}

sub set_counters {
    my ($self, %options) = @_;

    $self->{maps_counters_type} = [
        { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output', skipped_code => { -10 => 1 } },
        { name => 'domains', type => 3, cb_prefix_output => 'prefix_domain_output', cb_long_output => 'domain_long_output', indent_long_output => '    ', message_multiple => 'All domains are ok',
            group => [
                { name => 'devices', display_long => 1, cb_prefix_output => 'prefix_device_output', message_multiple => 'devices are ok', type => 1, skipped_code => { -10 => 1 } },
            ]
        }
    ];

    $self->{maps_counters}->{global} = [
        { label => 'devices-total', nlabel => 'devices.total.count', display_ok => 0, set => {
                key_values => [ { name => 'devices_total' } ],
                output_template => 'total: %s',
                perfdatas => [
                    { template => '%s', min => 0 }
                ]
            }
        }
    ];
    foreach (('green', 'black', 'blue', 'red', 'yellow')) {
        push @{$self->{maps_counters}->{global}},
            { label => 'devices-status-' . $_, nlabel => 'devices.status.' . $_ .  '.count', display_ok => 0, set => {
                    key_values => [ { name => 'devices_' . $_ }, { name => 'devices_total' } ],
                    output_template => $_ . ': %s',
                    perfdatas => [
                        { template => '%s', min => 0, max => 'devices_total' }
                    ]
                }
            };
    }

    $self->{maps_counters}->{devices} = [
        {
            label => 'device-status',
            type => 2,
            warning_default => '%{status} =~ /yellow/i',
            critical_default => '%{status} =~ /red|black/i',
            set => {
                key_values => [ { name => 'status' }, { name => 'name' } ],
                closure_custom_output => $self->can('custom_device_status_output'),
                closure_custom_perfdata => sub { return 0; },
                closure_custom_threshold_check => \&catalog_status_threshold_ng
            }
        }
    ];
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {
        'filter-domain-name:s' => { name => 'filter_domain_name' },
        'filter-device-name:s' => { name => 'filter_device_name' }
    });

    return $self;
}

sub manage_selection {
    my ($self, %options) = @_;

    my $domains = $options{custom}->request_api(
        endpoint_domain => 'fmc_platform',
        endpoint => '/info/domain'
    );

    $self->{global} = {
        devices_total => 0, devices_black => 0,
        devices_red => 0, devices_yellow => 0,
        devices_green => 0, devices_blue => 0
    };
    $self->{domains} = {};

    foreach my $domain (@{$domains->{items}}) {
        if (defined($self->{option_results}->{filter_domain_name}) && $self->{option_results}->{filter_domain_name} ne '' &&
            $domain->{name} !~ /$self->{option_results}->{filter_domain_name}/) {
            $self->{output}->output_add(long_msg => "skipping domain '" . $domain->{name} . "': no matching filter.", debug => 1);
            next;
        }

        $self->{domains}->{ $domain->{name} } = {
            name => $domain->{name},
            devices => {}
        };

        my $devices = $options{custom}->request_api(
            endpoint_domain => 'fmc_config',
            endpoint => '/domain/' . $domain->{uuid} . '/devices/devicerecords',
            get_param => ['expanded=true']
        );

        foreach my $device (@{$devices->{items}}) {
            if (defined($self->{option_results}->{filter_device_name}) && $self->{option_results}->{filter_device_name} ne '' &&
                $device->{name} !~ /$self->{option_results}->{filter_device_name}/) {
                $self->{output}->output_add(long_msg => "skipping device '" . $device->{name} . "': no matching filter.", debug => 1);
                next;
            }

            $self->{domains}->{ $domain->{name} }->{devices}->{ $device->{name} } = {
                name => $device->{name},
                status => $device->{healthStatus}
            };
            $self->{global}->{'devices_' . lc($device->{healthStatus})}++
                if (defined($self->{global}->{'devices_' . lc($device->{healthStatus})}));
            $self->{global}->{devices_total}++;
        }
    }
}

1;

__END__

=head1 MODE

Check devices.

=over 8

=item B<--filter-domain-name>

Filter devices by domain name (Can be a regexp).

=item B<--filter-device-name>

Filter devices by name (Can be a regexp).

=item B<--unknown-device-status>

Set unknown threshold for status.
Can used special variables like: %{status}, %{name}

=item B<--warning-device-status>

Set warning threshold for status (Default: '%{status} =~ /yellow/i').
Can used special variables like: %{status}, %{name}

=item B<--critical-device-status>

Set critical threshold for status (Default: '%{status} =~ /red|black/i').
Can used special variables like: %{status}, %{name}

=item B<--warning-*> B<--critical-*>

Thresholds.
Can be: 'devices-total', 'devices-status-green', 'devices-status-black', 'devices-status-blue',
'devices-status-red', 'devices-status-yellow'.

=back

=cut


text:
<?php

namespace NilPortugues\Sql\QueryBuilder\Manipulation;

use NilPortugues\Sql\QueryBuilder\Syntax\Where;

/**
 * Class QueryFactory.
 */
final class QueryFactory
{
    /**
     * @param string $table
     * @param array  $columns
     *
     * @return Select
     */
    public static function createSelect($table = null, array $columns = null)
    {
        return new Select($table, $columns);
    }

    /**
     * @param string $table
     * @param array  $values
     *
     * @return Insert
     */
    public static function createInsert($table = null, array $values = null)
    {
        return new Insert($table, $values);
    }

    /**
     * @param string $table
     * @param array  $values
     *
     * @return Update
     */
    public static function createUpdate($table = null, array $values = null)
    {
        return new Update($table, $values);
    }

    /**
     * @param string $table
     *
     * @return Delete
     */
    public static function createDelete($table = null)
    {
        return new Delete($table);
    }

    /**
     * @param QueryInterface $query
     *
     * @return Where
     */
    public static function createWhere(QueryInterface $query)
    {
        return new Where($query);
    }

    /**
     * @return Intersect
     */
    public static function createIntersect()
    {
        return new Intersect();
    }

    /**
     * @param Select $first
     * @param Select $second
     *
     * @return Minus
     */
    public static function createMinus(Select $first, Select $second)
    {
        return new Minus($first, $second);
    }

    /**
     * @return Union
     */
    public static function createUnion()
    {
        return new Union();
    }

    /**
     * @return UnionAll
     */
    public static function createUnionAll()
    {
        return new UnionAll();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Concrete\Core\Permission\Response;

use User;
use FileSet;

class FileFolderResponse extends TreeNodeResponse
{

    public function canViewTreeNode()
    {
        return $this->validate('search_file_folder');
    }

    /**
     * @deprecated
     */
    public function canAccessFileManager()
    {
        return $this->canSearchFiles();
    }

    public function canSearchFiles()
    {
        return $this->validate('search_file_folder');
    }

    public function canDeleteTreeNode()
    {
        return $this->validate('delete_file_folder');
    }

    public function canAddTreeSubNode()
    {
        return $this->validate('add_file');
    }

    public function canDuplicateTreeNode()
    {
        return false;
    }

    public function canEditTreeNode()
    {
        return $this->validate('edit_file_folder');
    }

    public function canEditTreeNodePermissions()
    {
        return $this->validate('edit_file_folder_permissions');
    }

    public function canAddFiles()
    {
        return $this->validate('add_file');
    }

    /**
     * Returns all file extensions this user can add.
     */
    public function getAllowedFileExtensions()
    {
        $pk = $this->category->getPermissionKeyByHandle('add_file');
        $pk->setPermissionObject($this->object);
        $r = $pk->getAllowedFileExtensions();

        return $r;
    }

    public function canAddFileType($ext)
    {
        $pk = $this->category->getPermissionKeyByHandle('add_file');
        $pk->setPermissionObject($this->object);

        return $pk->validate($ext);
    }

    public function canDeleteFileSet()
    {
        $fs = $this->getPermissionObject();
        $u = new User();
        if ($fs->getFileSetType() == FileSet::TYPE_PRIVATE && $fs->getFileSetUserID() == $u->getUserID()) {
            return true;
        }

        return $this->validate('delete_file_set');
    }
}


text:
		<meta charset="utf-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
		<meta name="author" content="jdcoffre"/>
		<meta name="description" content="License Resource Documentation"/>

		<title>License API Documentation</title>

		<link href="/assets/libs/twitter-bootstrap-2.3.2/css/bootstrap.css" rel="stylesheet"/>
		<link href="/assets/libs/twitter-bootstrap-2.3.2/css/bootstrap-responsive.css" rel="stylesheet"/>
		<link href="/assets/libs/twitter-bootstrap-2.3.2/css/docs.css" rel="stylesheet"/>

        <link rel="shortcut icon" type="image/x-icon" href="assets/img/grapes_small.gif"/>

                        Grapes

                                Documentations

Online Documentation

Organization API

Product API

Module API

Artifact API

License API

                                    Report an issue

License REST API Documentation

 Resource documentation

 Add/update a license

 Get all license names

 Get a license

 Remove a license

 Validate/unvalidate license

@ /license

GET

Get License resource documentation

Returns HTML

POST

Add/update license

Expects a JSON license in the request content

Return status 201 if ok 400 if the Json does not suits the model

Json License example:

${getLicenseJsonModel()}

@ /license/names

GET

Get all license names

Returns HTML view or a Json list of string

                                Optional parameters:

                                        Parameter
                                        Default Value
                                        Description

                                        approved
                                        null
                                        Filter licenses regarding if the "approve" field is true/false

                                        toBeValidated
                                        null
                                        Filter licenses regarding if the "approve" field is null or not

@ /license/{name}

GET

Get a license

                                Returns HTML view or a Json license

${getLicenseJsonModel()}

DELETE

Remove a license

Return status 200 if ok

POST

Validate or un validate a license

Return status 200 if ok

                                Mandatory parameter:

                                        Parameter
                                        Description

                                        approved
                                        Boolean to approve or reject the license

Grapes ${programVersion!?html}


text:
package org.elasticsearch.xpack.security.authc.ldap;

import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.FailoverServerSet;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPURL;
import com.unboundid.ldap.sdk.SingleServerSet;
import com.unboundid.ldap.sdk.schema.Schema;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.MockSecureSettings;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.license.TestUtils;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.mustache.MustacheScriptEngine;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.core.security.authc.AuthenticationResult;
import org.elasticsearch.xpack.core.security.authc.RealmConfig;
import org.elasticsearch.xpack.core.security.authc.RealmSettings;
import org.elasticsearch.xpack.core.security.authc.ldap.ActiveDirectorySessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.ldap.LdapRealmSettings;
import org.elasticsearch.xpack.core.security.authc.ldap.PoolingSessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.ldap.support.LdapLoadBalancingSettings;
import org.elasticsearch.xpack.core.security.authc.ldap.support.LdapMetadataResolverSettings;
import org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings;
import org.elasticsearch.xpack.core.security.authc.support.CachingUsernamePasswordRealmSettings;
import org.elasticsearch.xpack.core.security.authc.support.DnRoleMapperSettings;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.xpack.core.security.authc.support.mapper.ExpressionRoleMapping;
import org.elasticsearch.xpack.core.security.authc.support.mapper.TemplateRoleName;
import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.core.ssl.SSLConfigurationSettings;
import org.elasticsearch.xpack.core.ssl.SSLService;
import org.elasticsearch.xpack.core.ssl.VerificationMode;
import org.elasticsearch.xpack.security.authc.ldap.ActiveDirectorySessionFactory.DownLevelADAuthenticator;
import org.elasticsearch.xpack.security.authc.ldap.ActiveDirectorySessionFactory.UpnADAuthenticator;
import org.elasticsearch.xpack.security.authc.support.DnRoleMapper;
import org.elasticsearch.xpack.security.authc.support.mapper.NativeRoleMappingStore;
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;

import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey;
import static org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings.URLS_SETTING;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Active Directory Realm tests that use the UnboundID In Memory Directory Server
 *

 * AD is not LDAPv3 compliant so a workaround is needed
 * AD realm binds with userPrincipalName but this is not a valid DN, so we have to add a second userPrincipalName to the
 * users in the ldif in the form of CN=user@domain.com or a set the sAMAccountName to CN=user when testing authentication
 * with the sAMAccountName field.
 *

 * The username used to authenticate then has to be in the form of CN=user. Finally the username needs to be added as an
 * additional bind DN with a password in the test setup since it really is not a DN in the ldif file
 */
public class ActiveDirectoryRealmTests extends ESTestCase {

    private static final String PASSWORD = "password";

    static int numberOfLdapServers;
    InMemoryDirectoryServer[] directoryServers;

    private ResourceWatcherService resourceWatcherService;
    private ThreadPool threadPool;
    private Settings globalSettings;
    private SSLService sslService;
    private XPackLicenseState licenseState;

    @BeforeClass
    public static void setNumberOfLdapServers() {
        numberOfLdapServers = randomIntBetween(1, 4);
    }

    @Before
    public void start() throws Exception {
        InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=ad,dc=test,dc=elasticsearch,dc=com");
        // Get the default schema and overlay with the AD changes
        config.setSchema(Schema.mergeSchemas(Schema.getDefaultStandardSchema(),
                Schema.getSchema(getDataPath("ad-schema.ldif").toString())));

        // Add the bind users here since AD is not LDAPv3 compliant
        config.addAdditionalBindCredentials("CN=ironman@ad.test.elasticsearch.com", PASSWORD);
        config.addAdditionalBindCredentials("CN=Thor@ad.test.elasticsearch.com", PASSWORD);

        directoryServers = new InMemoryDirectoryServer[numberOfLdapServers];
        for (int i = 0; i < numberOfLdapServers; i++) {
            InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config);
            directoryServer.add("dc=ad,dc=test,dc=elasticsearch,dc=com", new Attribute("dc", "UnboundID"),
                    new Attribute("objectClass", "top", "domain", "extensibleObject"));
            directoryServer.importFromLDIF(false, getDataPath("ad.ldif").toString());
            // Must have privileged access because underlying server will accept socket connections
            AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
                directoryServer.startListening();
                return null;
            });
            directoryServers[i] = directoryServer;
        }
        threadPool = new TestThreadPool("active directory realm tests");
        resourceWatcherService = new ResourceWatcherService(Settings.EMPTY, threadPool);
        globalSettings = Settings.builder().put("path.home", createTempDir()).build();
        sslService = new SSLService(TestEnvironment.newEnvironment(globalSettings));
        licenseState = new TestUtils.UpdatableLicenseState();
    }

    @After
    public void stop() throws InterruptedException {
        resourceWatcherService.close();
        terminate(threadPool);
        for (int i = 0; i < numberOfLdapServers; i++) {
            directoryServers[i].shutDown(true);
        }
    }

    @Override
    public boolean enableWarningsCheck() {
        return false;
    }

    /**
     * Creates a realm with the provided settings, rebuilds the SSL Service to be aware of the new realm, and then returns
     * the RealmConfig
     */
    private RealmConfig setupRealm(RealmConfig.RealmIdentifier realmIdentifier, Settings localSettings) {
        final Settings mergedSettings = Settings.builder().put(globalSettings).put(localSettings)
            .put(getFullSettingKey(realmIdentifier, RealmSettings.ORDER_SETTING), "0").build();
        final Environment env = TestEnvironment.newEnvironment(mergedSettings);
        this.sslService = new SSLService(env);
        return new RealmConfig(
            realmIdentifier,
            mergedSettings,
            env, new ThreadContext(mergedSettings)
        );
    }

    public void testAuthenticateUserPrincipleName() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testAuthenticateUserPrincipleName");
        Settings settings = settings(realmIdentifier);
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
        final AuthenticationResult result = future.actionGet();
        assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
        final User user = result.getUser();
        assertThat(user, is(notNullValue()));
        assertThat(user.roles(), arrayContaining(containsString("Avengers")));
    }

    public void testAuthenticateSAMAccountName() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testAuthenticateSAMAccountName");
        Settings settings = settings(realmIdentifier);
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        // Thor does not have a UPN of form CN=Thor@ad.test.elasticsearch.com
        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=Thor", new SecureString(PASSWORD)), future);
        User user = future.actionGet().getUser();
        assertThat(user, is(notNullValue()));
        assertThat(user.roles(), arrayContaining(containsString("Avengers")));
    }

    protected String[] ldapUrls() throws LDAPException {
        List<String> urls = new ArrayList<>(numberOfLdapServers);
        for (int i = 0; i < numberOfLdapServers; i++) {
            LDAPURL url = new LDAPURL("ldap", "localhost", directoryServers[i].getListenPort(), null, null, null, null);
            urls.add(url.toString());
        }
        return urls.toArray(Strings.EMPTY_ARRAY);
    }

    public void testAuthenticateCachesSuccessfulAuthentications() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testAuthenticateCachesSuccesfulAuthentications");
        Settings settings = settings(realmIdentifier);
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = spy(new ActiveDirectorySessionFactory(config, sslService, threadPool));
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        int count = randomIntBetween(2, 10);
        for (int i = 0; i < count; i++) {
            PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
            realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
            future.actionGet();
        }

        // verify one and only one session as further attempts should be returned from cache
        verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class));
    }

    public void testAuthenticateCachingCanBeDisabled() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testAuthenticateCachingCanBeDisabled");
        final Settings settings = settings(realmIdentifier, Settings.builder()
                .put(getFullSettingKey(realmIdentifier, CachingUsernamePasswordRealmSettings.CACHE_TTL_SETTING), -1)
                .build());
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = spy(new ActiveDirectorySessionFactory(config, sslService, threadPool));
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        int count = randomIntBetween(2, 10);
        for (int i = 0; i < count; i++) {
            PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
            realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
            future.actionGet();
        }

        // verify one and only one session as second attempt should be returned from cache
        verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class));
    }

    public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testAuthenticateCachingClearsCacheOnRoleMapperRefresh");
        Settings settings = settings(realmIdentifier);
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = spy(new ActiveDirectorySessionFactory(config, sslService, threadPool));
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        int count = randomIntBetween(2, 10);
        for (int i = 0; i < count; i++) {
            PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
            realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
            future.actionGet();
        }

        // verify one and only one session as further attempts should be returned from cache
        verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class));

        // Refresh the role mappings
        roleMapper.notifyRefresh();

        for (int i = 0; i < count; i++) {
            PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
            realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
            future.actionGet();
        }

        verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class));
    }

    public void testUnauthenticatedLookupWithConnectionPool() throws Exception {
        doUnauthenticatedLookup(true);
    }

    public void testUnauthenticatedLookupWithoutConnectionPool() throws Exception {
        doUnauthenticatedLookup(false);
    }

    private void doUnauthenticatedLookup(boolean pooled) throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testUnauthenticatedLookupWithConnectionPool");

        final Settings.Builder builder = Settings.builder()
                .put(getFullSettingKey(realmIdentifier.getName(), ActiveDirectorySessionFactorySettings.POOL_ENABLED), pooled)
                .put(getFullSettingKey(realmIdentifier, PoolingSessionFactorySettings.BIND_DN), "CN=ironman@ad.test.elasticsearch.com");
        final boolean useLegacyBindPassword = randomBoolean();
        if (useLegacyBindPassword) {
            builder.put(getFullSettingKey(realmIdentifier, PoolingSessionFactorySettings.LEGACY_BIND_PASSWORD), PASSWORD);
        } else {
            final MockSecureSettings secureSettings = new MockSecureSettings();
            secureSettings.setString(getFullSettingKey(realmIdentifier, PoolingSessionFactorySettings.SECURE_BIND_PASSWORD), PASSWORD);
            builder.setSecureSettings(secureSettings);
        }
        Settings settings = settings(realmIdentifier, builder.build());
        RealmConfig config = setupRealm(realmIdentifier, settings);
        try (ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool)) {
            DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
            LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
            realm.initialize(Collections.singleton(realm), licenseState);

            PlainActionFuture<User> future = new PlainActionFuture<>();
            realm.lookupUser("CN=Thor", future);
            final User user = future.actionGet();
            assertThat(user, notNullValue());
            assertThat(user.principal(), equalTo("CN=Thor"));
        }
    }

    public void testRealmMapsGroupsToRoles() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testRealmMapsGroupsToRoles");
        Settings settings = settings(realmId, Settings.builder()
                .put(getFullSettingKey(realmId, DnRoleMapperSettings.ROLE_MAPPING_FILE_SETTING), getDataPath("role_mapping.yml"))
                .build());
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
        User user = future.actionGet().getUser();
        assertThat(user, is(notNullValue()));
        assertThat(user.roles(), arrayContaining(equalTo("group_role")));
    }

    public void testRealmMapsUsersToRoles() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testRealmMapsGroupsToRoles");
        Settings settings = settings(realmId, Settings.builder()
                .put(getFullSettingKey(realmId, DnRoleMapperSettings.ROLE_MAPPING_FILE_SETTING), getDataPath("role_mapping.yml"))
                .build());
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=Thor", new SecureString(PASSWORD)), future);
        User user = future.actionGet().getUser();
        assertThat(user, is(notNullValue()));
        assertThat(user.roles(), arrayContainingInAnyOrder(equalTo("group_role"), equalTo("user_role")));
    }

    /**
     * This tests template role mappings (see
     * {@link TemplateRoleName}) with an LDAP realm, using a additional
     * metadata field (see {@link LdapMetadataResolverSettings#ADDITIONAL_METADATA_SETTING}).
     */
    public void testRealmWithTemplatedRoleMapping() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testRealmWithTemplatedRoleMapping");
        Settings settings = settings(realmId, Settings.builder()
                .put(getFullSettingKey(realmId, LdapMetadataResolverSettings.ADDITIONAL_METADATA_SETTING), "departmentNumber")
                .build());
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);

        SecurityIndexManager mockSecurityIndex = mock(SecurityIndexManager.class);
        when(mockSecurityIndex.isAvailable()).thenReturn(true);
        when(mockSecurityIndex.isIndexUpToDate()).thenReturn(true);
        when(mockSecurityIndex.isMappingUpToDate()).thenReturn(true);

        Client mockClient = mock(Client.class);
        when(mockClient.threadPool()).thenReturn(threadPool);

        final ScriptService scriptService = new ScriptService(settings, Collections.singletonMap(MustacheScriptEngine.NAME,
                new MustacheScriptEngine()), ScriptModule.CORE_CONTEXTS);
        NativeRoleMappingStore roleMapper = new NativeRoleMappingStore(settings, mockClient, mockSecurityIndex, scriptService) {
            @Override
            protected void loadMappings(ActionListener<List<ExpressionRoleMapping>> listener) {
                listener.onResponse(
                        Arrays.asList(
                                this.buildMapping("m1", new BytesArray("{" +
                                        "\"role_templates\":[{\"template\":{\"source\":\"_role_{{metadata.departmentNumber}}\"}}]," +
                                        "\"enabled\":true," +
                                        "\"rules\":{ " +
                                        " \"field\":{\"realm.name\":\"testrealmwithtemplatedrolemapping\"}" +
                                        "}}"))));
            }
        };
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        PlainActionFuture<AuthenticationResult> future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=Thor", new SecureString(PASSWORD)), future);
        AuthenticationResult result = future.actionGet();
        assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
        User user = result.getUser();
        assertThat(user, notNullValue());
        assertThat(user.roles(), arrayContaining("_role_13"));

        future = new PlainActionFuture<>();
        realm.authenticate(new UsernamePasswordToken("CN=ironman", new SecureString(PASSWORD)), future);
        result = future.actionGet();
        assertThat(result.getStatus(), is(AuthenticationResult.Status.SUCCESS));
        user = result.getUser();
        assertThat(user, notNullValue());
        assertThat(user.roles(), arrayContaining("_role_12"));
    }

    public void testRealmUsageStats() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testRealmUsageStats");
        String loadBalanceType = randomFrom("failover", "round_robin");
        Settings settings = settings(realmId, Settings.builder()
                .put(getFullSettingKey(realmId, DnRoleMapperSettings.ROLE_MAPPING_FILE_SETTING), getDataPath("role_mapping.yml"))
                .put(getFullSettingKey(realmId, LdapLoadBalancingSettings.LOAD_BALANCE_TYPE_SETTING), loadBalanceType)
                .build());
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        DnRoleMapper roleMapper = new DnRoleMapper(config, resourceWatcherService);
        LdapRealm realm = new LdapRealm(config, sessionFactory, roleMapper, threadPool);
        realm.initialize(Collections.singleton(realm), licenseState);

        PlainActionFuture<Map<String, Object>> future = new PlainActionFuture<>();
        realm.usageStats(future);
        Map<String, Object> stats = future.get();
        assertThat(stats, is(notNullValue()));
        assertThat(stats, hasEntry("name", realm.name()));
        assertThat(stats, hasEntry("order", realm.order()));
        assertThat(stats, hasEntry("size", 0));
        assertThat(stats, hasEntry("ssl", false));
        assertThat(stats, hasEntry("load_balance_type", loadBalanceType));
    }

    public void testDefaultSearchFilters() throws Exception {
        final RealmConfig.RealmIdentifier realmIdentifier = realmId("testDefaultSearchFilters");
        Settings settings = settings(realmIdentifier);
        RealmConfig config = setupRealm(realmIdentifier, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        assertEquals("(&(objectClass=user)(|(sAMAccountName={0})(userPrincipalName={0}@ad.test.elasticsearch.com)))",
                sessionFactory.defaultADAuthenticator.getUserSearchFilter());
        assertEquals(UpnADAuthenticator.UPN_USER_FILTER, sessionFactory.upnADAuthenticator.getUserSearchFilter());
        assertEquals(DownLevelADAuthenticator.DOWN_LEVEL_FILTER, sessionFactory.downLevelADAuthenticator.getUserSearchFilter());
    }

    public void testCustomSearchFilters() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testDefaultSearchFilters");
        Settings settings = settings(realmId, Settings.builder()
                .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_USER_SEARCH_FILTER_SETTING),
                    "(objectClass=default)")
                .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_UPN_USER_SEARCH_FILTER_SETTING),
                    "(objectClass=upn)")
                .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_DOWN_LEVEL_USER_SEARCH_FILTER_SETTING),
                        "(objectClass=down level)")
                .build());
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        assertEquals("(objectClass=default)", sessionFactory.defaultADAuthenticator.getUserSearchFilter());
        assertEquals("(objectClass=upn)", sessionFactory.upnADAuthenticator.getUserSearchFilter());
        assertEquals("(objectClass=down level)", sessionFactory.downLevelADAuthenticator.getUserSearchFilter());
    }

    public RealmConfig.RealmIdentifier realmId(String realmName) {
        return new RealmConfig.RealmIdentifier(LdapRealmSettings.AD_TYPE, realmName.toLowerCase(Locale.ROOT));
    }

    private Settings settings(RealmConfig.RealmIdentifier realmIdentifier) throws Exception {
        return settings(realmIdentifier, Settings.EMPTY);
    }

    public void testBuildUrlFromDomainNameAndDefaultPort() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testBuildUrlFromDomainNameAndDefaultPort");
        Settings settings = Settings.builder()
            .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING),
                "ad.test.elasticsearch.com")
            .build();
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        assertSingleLdapServer(sessionFactory, "ad.test.elasticsearch.com", 389);
    }

    public void testBuildUrlFromDomainNameAndCustomPort() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testBuildUrlFromDomainNameAndCustomPort");
        Settings settings = Settings.builder()
            .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING),
                "ad.test.elasticsearch.com")
            .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_LDAP_PORT_SETTING), 10389)
            .build();
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        assertSingleLdapServer(sessionFactory, "ad.test.elasticsearch.com", 10389);
    }

    public void testUrlConfiguredInSettings() throws Exception {
        final RealmConfig.RealmIdentifier realmId = realmId("testBuildUrlFromDomainNameAndCustomPort");
        Settings settings = Settings.builder()
            .put(getFullSettingKey(realmId.getName(), ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING),
                "ad.test.elasticsearch.com")
            .put(getFullSettingKey(realmId, SessionFactorySettings.URLS_SETTING), "ldap://ad01.testing.elastic.co:20389/")
            .build();
        RealmConfig config = setupRealm(realmId, settings);
        ActiveDirectorySessionFactory sessionFactory = new ActiveDirectorySessionFactory(config, sslService, threadPool);
        assertSingleLdapServer(sessionFactory, "ad01.testing.elastic.co", 20389);
    }

    private void assertSingleLdapServer(ActiveDirectorySessionFactory sessionFactory, String hostname, int port) {
        assertThat(sessionFactory.getServerSet(), instanceOf(FailoverServerSet.class));
        FailoverServerSet fss = (FailoverServerSet) sessionFactory.getServerSet();
        assertThat(fss.getServerSets(), arrayWithSize(1));
        assertThat(fss.getServerSets()[0], instanceOf(SingleServerSet.class));
        SingleServerSet sss = (SingleServerSet) fss.getServerSets()[0];
        assertThat(sss.getAddress(), equalTo(hostname));
        assertThat(sss.getPort(), equalTo(port));
    }

    private Settings settings(RealmConfig.RealmIdentifier realmIdentifier, Settings extraSettings) throws Exception {
        Settings.Builder builder = Settings.builder()
                .putList(getFullSettingKey(realmIdentifier, URLS_SETTING), ldapUrls())
                .put(getFullSettingKey(realmIdentifier.getName(), ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING),
                        "ad.test.elasticsearch.com")
                .put(getFullSettingKey(realmIdentifier, DnRoleMapperSettings.USE_UNMAPPED_GROUPS_AS_ROLES_SETTING), true);
        if (inFipsJvm()) {
            builder.put(getFullSettingKey(realmIdentifier, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM),
                    VerificationMode.CERTIFICATE);
        } else {
            builder.put(getFullSettingKey(realmIdentifier, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM),
                    randomBoolean() ? VerificationMode.CERTIFICATE : VerificationMode.NONE);
        }
        return builder.put(extraSettings).build();
    }
}


text:
from __future__ import absolute_import

from sentry import options
from sentry.identity.oauth2 import OAuth2Provider, OAuth2LoginView, OAuth2CallbackView

class SlackIdentityProvider(OAuth2Provider):
    key = "slack"
    name = "Slack"

    # This identity provider is used for authorizing the Slack application
    # through their Bot token (or legacy Workspace Token if enabled) flow.

    oauth_scopes = ("identity.basic", "identity.email")

    # Only used during installation for Bot apps in order to request "links:read"
    # user_scope, needed for unfurling.
    user_scopes = ()

    def get_oauth_authorize_url(self):
        return "https://slack.com/oauth/v2/authorize"

    # XXX(epurkhiser): While workspace tokens _do_ support the oauth.access
    # endpoint, it will no include the authorizing_user, so we continue to use
    # the deprecated oauth.token endpoint until we are able to migrate to a bot
    # app which uses oauth.access.
    def get_oauth_access_token_url(self):
        return "https://slack.com/api/oauth.v2.access"

    def get_oauth_client_id(self):
        return options.get("slack-v2.client-id") or options.get("slack.client-id")

    def get_oauth_client_secret(self):
        return options.get("slack-v2.client-secret") or options.get("slack.client-secret")

    def get_user_scopes(self):
        return self.config.get("user_scopes", self.user_scopes)

    def get_pipeline_views(self):
        return [
            SlackOAuth2LoginView(
                authorize_url=self.get_oauth_authorize_url(),
                client_id=self.get_oauth_client_id(),
                scope=" ".join(self.get_oauth_scopes()),
                user_scope=" ".join(self.get_user_scopes()),
            ),
            OAuth2CallbackView(
                access_token_url=self.get_oauth_access_token_url(),
                client_id=self.get_oauth_client_id(),
                client_secret=self.get_oauth_client_secret(),
            ),
        ]

    def get_oauth_data(self, payload):
        # TODO(epurkhiser): This flow isn't actually used right now in sentry.
        # In slack-bot world we would need to make an API call to the 'me'
        # endpoint to get their user ID here.
        return super(SlackIdentityProvider, self).get_oauth_data(self, payload)

    def build_identity(self, data):
        data = data["data"]

        return {
            "type": "slack",
            # TODO(epurkhiser): See note above
            "id": data["user"]["id"],
            "email": data["user"]["email"],
            "scopes": sorted(data["scope"].split(",")),
            "data": self.get_oauth_data(data),
        }

class SlackOAuth2LoginView(OAuth2LoginView):
    """
    We need to customize the OAuth2LoginView in order to support passing through
    the `user_scope` param in the request.

    The `user_scope` param would not be used when requesting identity scopes.
    """

    user_scope = ""

    def __init__(
        self, authorize_url=None, client_id=None, scope=None, user_scope=None, *args, **kwargs
    ):
        super(SlackOAuth2LoginView, self).__init__(
            authorize_url=authorize_url, client_id=client_id, scope=scope, *args, **kwargs
        )
        if user_scope is not None:
            self.user_scope = user_scope

    def get_authorize_params(self, state, redirect_uri):
        data = super(SlackOAuth2LoginView, self).get_authorize_params(state, redirect_uri)

        # XXX(meredith): Bot apps must be added manually to channels, and link unfurling
        # only works for channels the bot is a part of, so in order to expand the usage
        # of unfurling to work in channels the bot is not a part of we must request the
        # `links:read` scope for the user. This way channels that the authorizing user
        # are in will support link unfurling
        #
        # The way we can request scopes for users is by using the `user_scope` param. This
        # will give us the user token...which I don't think we use, but requesting the scope
        # seems to be enough to get the unfurling to work.
        #
        # Resources: https://api.slack.com/authentication/oauth-v2#asking
        if self.user_scope:
            data["user_scope"] = self.user_scope

        return data


text:
package com.navercorp.pinpoint.plugin.jdbc;

import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DB;
import com.navercorp.pinpoint.pluginit.jdbc.DriverManagerUtils;
import com.navercorp.pinpoint.pluginit.jdbc.DriverProperties;
import com.navercorp.pinpoint.pluginit.jdbc.JDBCDriverClass;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * @author HyunGil Jeong
 */
public abstract class MariaDB_IT_Base {

    private static final int PORT = 13306;
    protected static final String URL = "127.0.0.1:" + PORT;
    protected static final String DATABASE_NAME = "test";

    protected static final String JDBC_URL = "jdbc:mariadb://" + URL + "/" + DATABASE_NAME;

    // for Statement
    protected static final String STATEMENT_QUERY = "SELECT count(1) FROM playground";
    protected static final String STATEMENT_NORMALIZED_QUERY = "SELECT count(0#) FROM playground";

    // for Prepared Statement
    protected static final String PREPARED_STATEMENT_QUERY = "SELECT * FROM playground where id = ?";

    // for Callable Statement
    protected static final String PROCEDURE_NAME = "getPlaygroundByName";
    protected static final String CALLABLE_STATEMENT_QUERY = "{ CALL " + PROCEDURE_NAME + "(?, ?) }";
    protected static final String CALLABLE_STATEMENT_INPUT_PARAM = "TWO";
    protected static final int CALLABLE_STATMENT_OUTPUT_PARAM_TYPE = Types.INTEGER;

    private static DB TEST_DATABASE;
    protected static DriverProperties driverProperties;

    private static final String EMBEDDED_DB_PORT_KEY = "maria.embedded-db.port";

    protected static final String DB_TYPE = "MARIADB";
    protected static final String DB_EXECUTE_QUERY = "MARIADB_EXECUTE_QUERY";

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        driverProperties = DriverProperties.load("database/maria.properties", "maria");
        int embeddedDBPort = Integer.parseInt(driverProperties.getProperty(EMBEDDED_DB_PORT_KEY));
        TEST_DATABASE = DB.newEmbeddedDB(embeddedDBPort);
        TEST_DATABASE.start();
        TEST_DATABASE.createDB("test");
        TEST_DATABASE.source("jdbc/mariadb/init.sql");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        TEST_DATABASE = testDBStop();

    }

    abstract JDBCDriverClass getJDBCDriverClass();

    @Before
    public void registerDriver() throws Exception {
        JDBCDriverClass driverClass = getJDBCDriverClass();
        Driver driver = driverClass.getDriver().newInstance();
        DriverManager.registerDriver(driver);
    }

    @After
    public void deregisterDriver() {
        DriverManagerUtils.deregisterDriver();
    }

    private static DB testDBStop() throws ManagedProcessException {
        if (TEST_DATABASE != null) {
            TEST_DATABASE.stop();
        }
        return null;
    }

    protected final void executeStatement() throws Exception {
        final int expectedResultSize = 1;
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            connection = DriverManager.getConnection(JDBC_URL, "root", null);
            statement = connection.createStatement();
            rs = statement.executeQuery(STATEMENT_QUERY);
            int resultCount = 0;
            while (rs.next()) {
                ++resultCount;
                if (resultCount > expectedResultSize) {
                    fail();
                }
                assertEquals(3, rs.getInt(1));
            }
            assertEquals(expectedResultSize, resultCount);
        } finally {
            closeResultSet(rs);
            closeStatement(statement);
            closeConnection(connection);
        }
    }

    protected final void executePreparedStatement() throws Exception {
        final int expectedResultSize = 1;

        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = DriverManager.getConnection(JDBC_URL, "root", null);
            ps = connection.prepareStatement(PREPARED_STATEMENT_QUERY);
            ps.setInt(1, 3);
            rs = ps.executeQuery();
            int resultCount = 0;
            while (rs.next()) {
                ++resultCount;
                if (resultCount > expectedResultSize) {
                    fail();
                }
                assertEquals("THREE", rs.getString(2));
            }
            assertEquals(expectedResultSize, resultCount);
        } finally {
            closeResultSet(rs);
            closeStatement(ps);
            closeConnection(connection);
        }
    }

    protected final void executeCallableStatement() throws Exception {

        final int expectedResultSize = 1;
        final int expectedTotalCount = 3;
        final int expectedMatchingId = 2;
        final String outputParamCountName = "outputParamCount";

        Connection conn = null;
        CallableStatement cs = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(JDBC_URL, "root", null);

            cs = conn.prepareCall(CALLABLE_STATEMENT_QUERY);
            cs.setString(1, CALLABLE_STATEMENT_INPUT_PARAM);
            cs.registerOutParameter(2, CALLABLE_STATMENT_OUTPUT_PARAM_TYPE);

            rs = cs.executeQuery();
            int resultCount = 0;
            while (rs.next()) {
                ++resultCount;
                if (resultCount > expectedResultSize) {
                    fail();
                }
                assertEquals(expectedMatchingId, rs.getInt(1));
                assertEquals(CALLABLE_STATEMENT_INPUT_PARAM, rs.getString(2));
            }
            assertEquals(expectedResultSize, resultCount);

            final int totalCount = cs.getInt(outputParamCountName);
            assertEquals(expectedTotalCount, totalCount);

        } finally {
            closeResultSet(rs);
            closeStatement(cs);
            closeConnection(conn);
        }
    }

    private void closeConnection(Connection conn) throws SQLException {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // empty
            }
        }
    }

    private void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // empty
            }
        }
    }

    private void closeStatement(Statement statement) throws SQLException {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                // empty
            }
        }
    }

}


text:
package com.nosolojava.fsm.impl.runtime.executable.basic;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.nosolojava.fsm.runtime.Context;
import com.nosolojava.fsm.runtime.executable.Assign;

public class BasicAssign implements Assign {
	private static final long serialVersionUID = 1300495592980349446L;
	transient Logger logger = Logger.getLogger(this.getClass().getName());
	protected final String location;
	private final String expression;
	private final String value;
	private final String toText;

	protected BasicAssign(String location, String expression, String value, String toText) {
		super();
		this.location = location;
		this.expression = expression;
		this.value = value;
		this.toText = toText;

	}

	public static BasicAssign assignByExpression(String location, String expression) {
		String toText = "BasicAssign [" + location + "= " + expression + "]";
		return new BasicAssign(location, expression, null, toText);
	}

	public static BasicAssign assignByValue(String location, String value) {
		String toText = "BasicAssign [" + location + "= " + value + "]";
		return new BasicAssign(location, null, value, toText);
	}

	@Override
	public void run(Context context) {
		logger.log(Level.FINE, "Running assign {0}", new Object[] { this });
		Object valueAux = null;
		if (this.expression != null) {
			valueAux = context.getDataByExpression(this.expression);
		} else {
			valueAux = this.value;
		}

		String realLocation = getRealLocation(context);
		logger.log(Level.FINE, "Value= {0}, location= {1} and realLocatin= {2}", new Object[] { valueAux, location,
				realLocation });

		if (context.existsVarName(realLocation)) {
			context.updateData(realLocation, valueAux);
			logger.log(Level.FINE, "Context updated {0}={1}",
					new Object[] { realLocation, context.getDataByName(realLocation) });
		} else {
			logger.log(Level.SEVERE, "Context COULD NOT BE updated, var name {0} not found.",
					new Object[] { realLocation });

		}

	}

	protected String getRealLocation(Context context) {
		String realLocation = this.location;
		//allow expressions for locations (when location is not found only)
		if (!context.existsVarName(this.location)) {
			realLocation = context.getDataByExpression(this.location);
		}
		return realLocation;
	}

	@Override
	public String toString() {
		return toText;
	}

}


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

<TITLE>
Logger
</TITLE>

<META NAME="date" CONTENT="2014-04-14">

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

      ¸ÅÊö
      Èí¼þ°ü
    Àà
      ʹÓÃ
      Ê÷
      Ë÷Òý
      °ïÖú

 ÉÏÒ»¸öÀà
 ÏÂÒ»¸öÀà

  ¿ò¼Ü
 ÎÞ¿ò¼Ü

  ËùÓÐÀà

  ÕªÒª£º ǶÌ× | ×Ö¶Î | ¹¹Ôì·½·¨ | ·½·¨

ÏêϸÐÅÏ¢£º ×Ö¶Î | ¹¹Ôì·½·¨ | ·½·¨

darks.log

Àà Logger

java.lang.Object
  darks.log.Logger

Ö±½ÓÒÑÖª×ÓÀࣺ
DefaultLogger, InvalidLogger

public abstract class Logger
extends java.lang.Object

Main logger class for developer

 Create a logger object by class object or tag string. Example:

 static final Logger log = Logger.getLogger("demo");

 static final Logger log = Logger.getLogger("darks.tag.demo");

 static final Logger log = Logger.getLogger(Demo.class);

 For using Logger before, you must configure logd.properties, which must be
 put in Java/src, Android/assets and other classpath which can be found.

 Example:

  logd.root=info,console
  logd.appender.console=ConsoleAppender
  logd.appender.console.layout=PatternLayout
  logd.appender.console.layout.convertor=DefaultPattern
  logd.appender.console.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} - %m%n

 If you want to use logger in android environment, you must configure android
 application for finding configuration file. In order to ensure the setting
 before logger used, Recommend you to configure it in android
 Application onCreate method.

 Example:

        Logger.Android.setApplication(...);

 If you want to load logd.properties from SDCARD, you can do like this:

 Logger.Android.setConfigPath("/mnt/sdcard/xxx/logd.properties");

 Or

 Logger.Android.setConfigPath("xxx/logd.properties");

 If you want to catch android crash log automatically, you can register crash
 handler. Parameter callback can be called after ANR happened.

 Example:

 Logger.Android.setApplication(this, true);

 Or

 Logger.Android.setApplication(this);
 Logger.Android.registerCrashHandler();

 Or

 Logger.Android.setApplication(this);
 Logger.Android.registerCrashHandler(new CustomCrashCallBack());

 If you want to buffer, append or format log message, you can use
 LoggerBuffer. Example:

 static Logger log = Logger.getLogger("demo");
 log.append("darks").append('-').append("logs").info();
 log.append(2014).append(1).append(1).debug(e);
 log.buffer(2014, " is", " a good year").debug();
 log.format("darks-logs was created in %d by %s", 2014, "Liu Lihua").error(e);

 Logger.java

°æ±¾£º

1.0.2

×÷Õߣº

Liu lihua

×Ö¶ÎÕªÒª

static AndroidConfig
Android

          Android configuration

static LoggerConfig
Config

          Logger configuration

¹¹Ôì·½·¨ÕªÒª

Logger()

·½·¨ÕªÒª

abstract  void
addAppender(Appender appender)

          Add appender object

 LoggerBuffer
append()

          Append log message by string buffer.

 LoggerBuffer
append(java.lang.Object msg)

          Append log message by string buffer.

 LoggerBuffer
buffer(java.lang.Object... msgs)

          Buffer log message string.

 void
debug(java.lang.Object msg)

          Output log message by level DEBUG.

 void
debug(java.lang.Object msg,
      java.lang.Throwable t)

          Output log message and exception stack information by level DEBUG.

 void
error(java.lang.Object msg)

          Output log message by level ERROR.

 void
error(java.lang.Object msg,
      java.lang.Throwable t)

          Output log message and exception stack information by level ERROR.

 LoggerBuffer
format(java.lang.String format,
       java.lang.Object... objs)

          Format log message by pattern.

 Appender
getAppender(java.lang.String name)

          Get appender from appenders manager.

static Logger
getLogger(java.lang.Class<?> clazz)

          Get the logger by tag class.

static Logger
getLogger(java.lang.String tag)

          Get the logger by tag string.

static Logger
getRootLogger()

          Get root logger

 void
info(java.lang.Object msg)

          Output log message by level INFO.

 void
info(java.lang.Object msg,
     java.lang.Throwable t)

          Output log message and exception stack information by level INFO.

 boolean
isDebugEnabled()

          Check if debug mode enabled.

 boolean
isInfoEnabled()

          Check if info mode enabled.

 boolean
isLevelEnabled(Level level)

          Check if level's mode enabled.

 void
log(Level level,
    java.lang.Object msg)

          Output log message by target level.

abstract  void
log(Level level,
    java.lang.Object msg,
    java.lang.Throwable t)

          Output log message and exception stack information by target level.

abstract  Appender
removeAppender(java.lang.String name)

          Remove appender from current logger.

 void
setInherit(boolean inheritRoot)

          If parameter inheritRoot is true, children logger won't inherit root
 logger.

 void
trace(java.lang.Object msg)

          Output log message by level TRACE.

 void
trace(java.lang.Object msg,
      java.lang.Throwable t)

          Output log message and exception stack information by level TRACE.

 void
verbose(java.lang.Object msg)

          Output log message by level VERBOSE.

 void
verbose(java.lang.Object msg,
        java.lang.Throwable t)

          Output log message and exception stack information by level VERBOSE.

 void
warn(java.lang.Object msg)

          Output log message by level WARN.

 void
warn(java.lang.Object msg,
     java.lang.Throwable t)

          Output log message and exception stack information by level WARN.

´ÓÀà java.lang.Object ¼Ì³ÐµÄ·½·¨

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

×Ö¶ÎÏêϸÐÅÏ¢

Android

public static AndroidConfig Android

Android configuration

Config

public static LoggerConfig Config

Logger configuration

¹¹Ôì·½·¨ÏêϸÐÅÏ¢

Logger

public Logger()

·½·¨ÏêϸÐÅÏ¢

addAppender

public abstract void addAppender(Appender appender)

Add appender object

²ÎÊý£º
appender - Appender object

append

public LoggerBuffer append()

Append log message by string buffer.

·µ»Ø£º
Logger string buffer

append

public LoggerBuffer append(java.lang.Object msg)

Append log message by string buffer.

²ÎÊý£º
msg - Log message

·µ»Ø£º
Logger string buffer

buffer

public LoggerBuffer buffer(java.lang.Object... msgs)

Buffer log message string.

²ÎÊý£º
msgs - Message arrays

·µ»Ø£º
Logger buffer

debug

public void debug(java.lang.Object msg)

Output log message by level DEBUG.

²ÎÊý£º
msg - Log message

debug

public void debug(java.lang.Object msg,
                  java.lang.Throwable t)

Output log message and exception stack information by level DEBUG.

²ÎÊý£º
msg - Log message
t - Throwable object

error

public void error(java.lang.Object msg)

Output log message by level ERROR.

²ÎÊý£º
msg - Log message

error

public void error(java.lang.Object msg,
                  java.lang.Throwable t)

Output log message and exception stack information by level ERROR.

²ÎÊý£º
msg - Log message
t - Throwable object

format

public LoggerBuffer format(java.lang.String format,
                           java.lang.Object... objs)

Format log message by pattern. It call String.format method to format log
 message.

²ÎÊý£º
format - Format string.
objs -

·µ»Ø£º
Logger string buffer
ÁíÇë²Î¼û£º
Formatter

getAppender

public Appender getAppender(java.lang.String name)

Get appender from appenders manager.

²ÎÊý£º
name - Appender name

·µ»Ø£º
Appender object

getLogger

public static Logger getLogger(java.lang.Class<?> clazz)

Get the logger by tag class. Example:

 static Logger log = Logger.getLogger(Demo.class);

²ÎÊý£º
clazz - Tag class

·µ»Ø£º
Logger object

getLogger

public static Logger getLogger(java.lang.String tag)

Get the logger by tag string. Example:

 static Logger log = Logger.getLogger("demo");

²ÎÊý£º
tag - Tag string

·µ»Ø£º
Logger object

getRootLogger

public static Logger getRootLogger()

Get root logger

·µ»Ø£º
Logger object

info

public void info(java.lang.Object msg)

Output log message by level INFO.

²ÎÊý£º
msg - log message

info

public void info(java.lang.Object msg,
                 java.lang.Throwable t)

Output log message and exception stack information by level INFO.

²ÎÊý£º
msg - Log message
t - Throwable object

isDebugEnabled

public boolean isDebugEnabled()

Check if debug mode enabled.

·µ»Ø£º
If debug mode enabled, return true.

isInfoEnabled

public boolean isInfoEnabled()

Check if info mode enabled.

·µ»Ø£º
If info mode enabled, return true.

isLevelEnabled

public boolean isLevelEnabled(Level level)

Check if level's mode enabled.

²ÎÊý£º
level - Target level

·µ»Ø£º
If level's mode enabled, return true.

log

public void log(Level level,
                java.lang.Object msg)

Output log message by target level.

²ÎÊý£º
level - Level object
msg - Log message

log

public abstract void log(Level level,
                         java.lang.Object msg,
                         java.lang.Throwable t)

Output log message and exception stack information by target level.

²ÎÊý£º
level - Level object
msg - Log message
t - Throwable object

removeAppender

public abstract Appender removeAppender(java.lang.String name)

Remove appender from current logger.

²ÎÊý£º
name - Appender name

·µ»Ø£º
Appender object

setInherit

public void setInherit(boolean inheritRoot)

If parameter inheritRoot is true, children logger won't inherit root
 logger.

²ÎÊý£º
inheritRoot - Whether inherit root logger.

trace

public void trace(java.lang.Object msg)

Output log message by level TRACE.

²ÎÊý£º
msg - Log message

trace

public void trace(java.lang.Object msg,
                  java.lang.Throwable t)

Output log message and exception stack information by level TRACE.

²ÎÊý£º
msg - Log message
t - Throwable object

verbose

public void verbose(java.lang.Object msg)

Output log message by level VERBOSE.

²ÎÊý£º
msg - Log message

verbose

public void verbose(java.lang.Object msg,
                    java.lang.Throwable t)

Output log message and exception stack information by level VERBOSE.

²ÎÊý£º
msg - Log message
t - Throwable object

warn

public void warn(java.lang.Object msg)

Output log message by level WARN.

²ÎÊý£º
msg - Log message

warn

public void warn(java.lang.Object msg,
                 java.lang.Throwable t)

Output log message and exception stack information by level WARN.

²ÎÊý£º
msg - Log message
t - Throwable object

      ¸ÅÊö
      Èí¼þ°ü
    Àà
      ʹÓÃ
      Ê÷
      Ë÷Òý
      °ïÖú

 ÉÏÒ»¸öÀà
 ÏÂÒ»¸öÀà

  ¿ò¼Ü
 ÎÞ¿ò¼Ü

  ËùÓÐÀà

  ÕªÒª£º ǶÌ× | ×Ö¶Î | ¹¹Ôì·½·¨ | ·½·¨

ÏêϸÐÅÏ¢£º ×Ö¶Î | ¹¹Ôì·½·¨ | ·½·¨


text:
package impl

import java.nio.file.Files
import java.nio.file.StandardOpenOption
import java.util.Date

import com.lightbend.lagom.scaladsl.api.ServiceLocator.NoServiceLocator
import com.lightbend.lagom.scaladsl.server._
import com.lightbend.lagom.scaladsl.devmode.LagomDevModeComponents
import play.api.libs.ws.ahc.AhcWSComponents
import api.FooService
import com.softwaremill.macwire._

class FooLoader extends LagomApplicationLoader {

  override def load(context: LagomApplicationContext): LagomApplication =
    new FooApplication(context) {
      override def serviceLocator = NoServiceLocator
    }

  override def loadDevMode(context: LagomApplicationContext): LagomApplication =
    new FooApplication(context) with LagomDevModeComponents
}

abstract class FooApplication(context: LagomApplicationContext) extends LagomApplication(context) with AhcWSComponents {

  override lazy val lagomServer = serverFor[FooService](wire[FooServiceImpl])

  Files.write(
    environment.getFile("target/reload.log").toPath,
    s"${new Date()} - reloaded\n".getBytes("utf-8"),
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND
  )
}


text:
<?xml version="1.0"?>

<!DOCTYPE bindings [
<!ENTITY % notificationDTD SYSTEM "chrome://global/locale/notification.dtd">
%notificationDTD;
]>

<bindings id="notificationBindings"
          xmlns="http://www.mozilla.org/xbl"
          xmlns:xbl="http://www.mozilla.org/xbl"
          xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

  <binding id="notificationbox" extends="chrome://global/content/bindings/notification.xml#notificationbox">
    <content>
      <xul:vbox xbl:inherits="hidden=notificationshidden">
        <xul:spacer/>
        <children includes="notification"/>
      </xul:vbox>
      <children/>
    </content>

    <implementation>
      <constructor><![CDATA[
        let temp = {};
        Cu.import("resource://services-common/observers.js", temp);
        temp.Observers.add("weave:notification:added", this.onNotificationAdded, this);
        temp.Observers.add("weave:notification:removed", this.onNotificationRemoved, this);

        for each (var notification in Weave.Notifications.notifications)
          this._appendNotification(notification);
      ]]></constructor>

      <destructor><![CDATA[
        let temp = {};
        Cu.import("resource://services-common/observers.js", temp);
        temp.Observers.remove("weave:notification:added", this.onNotificationAdded, this);
        temp.Observers.remove("weave:notification:removed", this.onNotificationRemoved, this);
      ]]></destructor>

      <method name="onNotificationAdded">
        <parameter name="subject"/>
        <parameter name="data"/>
        <![CDATA[
          this._appendNotification(subject);
        ]]>
      </method>

      <method name="onNotificationRemoved">
        <parameter name="subject"/>
        <parameter name="data"/>
        <![CDATA[
          // If the view of the notification hasn't been removed yet, remove it.
          var notifications = this.allNotifications;
          for each (var notification in notifications) {
            if (notification.notification == subject) {
              notification.close();
              break;
            }
          }
        ]]>
      </method>

      <method name="_appendNotification">
        <parameter name="notification"/>
        <![CDATA[
          var node = this.appendNotification(notification.description,
                                             notification.title,
                                             notification.iconURL,
                                             notification.priority,
                                             notification.buttons);
          node.notification = notification;
        ]]>
      </method>

    </implementation>
  </binding>

  <binding id="notification" extends="chrome://global/content/bindings/notification.xml#notification">
    <content>
      <xul:hbox class="notification-inner outset" flex="1" xbl:inherits="type">
        <xul:toolbarbutton ondblclick="event.stopPropagation();"
                           class="messageCloseButton tabbable"
                           xbl:inherits="hidden=hideclose"
                           tooltiptext="&closeNotification.tooltip;"
                           oncommand="document.getBindingParent(this).close()"/>
        <xul:hbox anonid="details" align="center" flex="1">
          <xul:image anonid="messageImage" class="messageImage" xbl:inherits="src=image"/>
          <xul:description anonid="messageText" class="messageText" xbl:inherits="xbl:text=label"/>

          <xul:hbox oncommand="document.getBindingParent(this)._doButtonCommand(event);">
            <children/>
          </xul:hbox>
        </xul:hbox>
      </xul:hbox>
    </content>
    <implementation>

      <property name="notification"
                onget="return this._notification"
                onset="this._notification = val; return val;"/>
      <method name="close">
        <![CDATA[
          Weave.Notifications.remove(this.notification);

          // We should be able to call the base class's close method here
          // to remove the notification element from the notification box,
          // but we can't because of bug 373652, so instead we copied its code
          // and execute it below.
          var control = this.control;
          if (control)
            control.removeNotification(this);
          else
            this.hidden = true;
        ]]>
      </method>
    </implementation>
  </binding>

</bindings>


text:
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
 * Contains EWSType_FindItemParentType.
 */

/**
 * Represents the results of a search of a single root folder during a FindItem
 * operation.
 *
 * @package php-ews\Types
 */
class EWSType_FindItemParentType extends EWSType
{
    /**
     * Represents the next denominator to use for the next request when you are
     * using fraction page views.
     *
     * @since Exchange 2007
     *
     * @var integer
     */
    public $AbsoluteDenominator;

    /**
     * Contains a collection of groups found that have the search and
     * aggregation criteria identified in the FindItem operation request.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ArrayOfGroupedItemsType
     */
    public $Groups;

    /**
     * Indicates whether the current results contain the last item in the query
     * so that additional paging is not needed.
     *
     * @since Exchange 2007
     *
     * @var boolean
     */
    public $IncludesLastItemInRange;

    /**
     * Represents the next index that should be used for the next request when
     * you are using an indexed page view.
     *
     * @since Exchange 2007
     *
     * @var string
     */
    public $IndexedPagingOffset;

    /**
     * Contains an array of items found that have the search criteria identified
     * in the FindItem operation request.
     *
     * @since Exchange 2007
     *
     * @var EWSType_ArrayOfRealItemsType
     */
    public $Items;

    /**
     * Represents the new numerator value to use for the next request when you
     * are using fraction page views.
     *
     * @since Exchange 2007
     *
     * @var integer
     */
    public $NumeratorOffset;

    /**
     * Represents the total number of items in the view.
     *
     * @since Exchange 2007
     *
     * @var integer
     */
    public $TotalItemsInView;
}


text:
require "cgi"
require "uri"
require "logger"

require "openid/extras"

# See OpenID::Consumer or OpenID::Server modules, as well as the store classes
module OpenID
  class AssertionError < Exception
  end

  # Exceptions that are raised by the library are subclasses of this
  # exception type, so if you want to catch all exceptions raised by
  # the library, you can catch OpenIDError
  class OpenIDError < StandardError
  end

  module Util

    BASE64_CHARS = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
                    'abcdefghijklmnopqrstuvwxyz0123456789+/')
    BASE64_RE = Regexp.compile("
    \\A
    ([#{BASE64_CHARS}]{4})*
    ([#{BASE64_CHARS}]{2}==|
     [#{BASE64_CHARS}]{3}=)?
    \\Z", Regexp::EXTENDED)

    def Util.assert(value, message=nil)
      if not value
        raise AssertionError, message or value
      end
    end

    def Util.to_base64(s)
      [s].pack('m').gsub("\n", "")
    end

    def Util.from_base64(s)
      without_newlines = s.gsub(/[\r\n]+/, '')
      if !BASE64_RE.match(without_newlines)
        raise ArgumentError, "Malformed input: #{s.inspect}"
      end
      without_newlines.unpack('m').first
    end

    def Util.urlencode(args)
      a = []
      args.each do |key, val|
        val = '' unless val
        a << (CGI::escape(key) + "=" + CGI::escape(val))
      end
      a.join("&")
    end

    def Util.parse_query(qs)
      query = {}
      CGI::parse(qs).each {|k,v| query[k] = v[0]}
      return query
    end

    def Util.append_args(url, args)
      url = url.dup
      return url if args.length == 0

      if args.respond_to?('each_pair')
        args = args.sort
      end

      url << (url.include?("?") ? "&" : "?")
      url << Util.urlencode(args)
    end

    @@logger = Logger.new(STDERR)
    @@logger.progname = "OpenID"

    def Util.logger=(logger)
      @@logger = logger
    end

    def Util.logger
      @@logger
    end

    # change the message below to do whatever you like for logging
    def Util.log(message)
      logger.info(message)
    end

    def Util.auto_submit_html(form, title='OpenID transaction in progress')
      return "
<html>
<head>
  <title>#{title}</title>
</head>
<body onload='document.forms[0].submit();'>
#{form}
<script>
var elements = document.forms[0].elements;
for (var i = 0; i < elements.length; i++) {
  elements[i].style.display = \"none\";
}
</script>
</body>
</html>
"
    end

    ESCAPE_TABLE = { '&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''' }
    # Modified from ERb's html_encode
    def Util.html_encode(s)
      s.to_s.gsub(/[&<>"']/) {|s| ESCAPE_TABLE[s] }
    end
  end

end


text:
namespace IECore
{

/// SpherePrimitive represents a renderable parametric sphere
/// \ingroup geometryGroup
class IECORE_API SpherePrimitive : public Primitive
{

	public:

		IE_CORE_DECLAREOBJECT( SpherePrimitive, Primitive );

		/// Construct a full sphere of radius 1.
		SpherePrimitive();

		/// Construct a sphere with specified parameterisation. zMin and zMax differ from the Renderman specification
		/// slightly in that they're given as a proportion of that radius, so they should fall within the range [-1, 1 ]
		SpherePrimitive( float radius, float zMin = -1.0f, float zMax = 1.0f, float thetaMax = 360.0f );

		//! @name Sphere geometry access
		/// These functions allow access to get and set the sphere's geometry after construction.
		/////////////////////////////////////////////////////////////////////////////
		//@{

		float radius() const;
		float zMin() const;
		float zMax() const;

		/// The returned value is specified in degrees
		float thetaMax() const;

		void setRadius( float r );
		void setZMin( float zm );
		void setZMax( float zm );

		/// The value of thetaMax shoud be specified in degrees
		void setThetaMax( float tm );

		//@}

		virtual size_t variableSize( PrimitiveVariable::Interpolation interpolation ) const;

		virtual Imath::Box3f bound() const;
		/// Render the sphere
		virtual void render( Renderer *renderer ) const;

		virtual void topologyHash( MurmurHash &h ) const;

	private:

		static const unsigned int m_ioVersion;

		float m_radius;
		float m_zMin;
		float m_zMax;
		float m_thetaMax;

};

IE_CORE_DECLAREPTR( SpherePrimitive );

}

#endif // IECORE_SPHEREPRIMITIVE