text:
package org.springframework.security.web;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.ExceptionTranslationFilter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Used by {@link ExceptionTranslationFilter} to commence an authentication scheme.
 *
 * @author Ben Alex
 */
public interface AuthenticationEntryPoint {
	// ~ Methods
	// ========================================================================================================

	/**
	 * Commences an authentication scheme.
	 *

	 * ExceptionTranslationFilter will populate the HttpSession
	 * attribute named
	 * AbstractAuthenticationProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY
	 * with the requested target URL before calling this method.
	 *

	 * Implementations should modify the headers on the ServletResponse as
	 * necessary to commence the authentication process.
	 *
	 * @param request that resulted in an AuthenticationException
	 * @param response so that the user agent can begin authentication
	 * @param authException that caused the invocation
	 *
	 */
	void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException;
}


text:
<?php
class connectionTest extends PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        $this->object = new \Etcd\Connection();
    }

    public function testGetServer()
    {
        $this->assertEquals('http://localhost:4001',$this->object->getServer());
    }

    public function testGetVersion()
    {
        $this->assertEquals(2,substr_count($this->object->getVersion(), '.'));
    }

    public function testGetAPIVersion()
    {
        $this->assertEquals(2,$this->object->getAPIVersion());
    }

    public function testGetAPI()
    {
        $api = $this->object->getAPI();
        $this->assertInstanceOf('\Etcd\API\V2',$api);
    }

    /**
     * @expectedException \Etcd\Exception\APIException
     */
    public function testSetAPIVersionInvalid()
    {
        $this->object->setAPIVersion(1);
    }
}
?>

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.openapi.wm.impl.welcomeScreen;

import com.intellij.ide.ReopenProjectAction;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.IOException;
import java.util.List;

/**
 * @author Konstantin Bulenkov
 */
public class ChangeProjectIconAction extends RecentProjectsWelcomeScreenActionBase {
  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    List<AnAction> elements = getSelectedElements(e);
    String path = ((ReopenProjectAction)elements.get(0)).getProjectPath();
    final ChangeProjectIconForm form = new ChangeProjectIconForm(path);
    DialogWrapper dialog = new DialogWrapper(null) {
      {
        init();
      }

      @Nullable
      @Override
      protected JComponent createCenterPanel() {
        return form.myRootPanel;
      }
    };
    dialog.show();
    if (dialog.isOK()) {
      try {
        form.apply();
      }
      catch (IOException e1) {
        System.out.println(e1);
      }
    }
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    boolean enabled = getSelectedElements(e).size() == 1 && !hasGroupSelected(e);
    e.getPresentation().setEnabled(enabled);
  }

  public static class Form {

  }
}


text:
package in.twizmwaz.cardinal.command;

import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import in.twizmwaz.cardinal.Cardinal;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.settings.Settings;
import in.twizmwaz.cardinal.util.ChatUtil;
import in.twizmwaz.cardinal.util.Players;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;

public class PrivateMessageCommands {

    @Command(aliases = {"msg", "message", "pm", "privatemessage", "whisper", "tell"}, desc = "Send a private message to a player.", usage = "<player> <message>", min = 2)
    public static void pm(final CommandContext cmd, CommandSender sender) throws CommandException {
        if (!(sender instanceof Player)) {
            throw new CommandException(ChatConstant.ERROR_PLAYER_COMMAND.getMessage(ChatUtil.getLocale(sender)));
        }
        Player target = Bukkit.getPlayer(cmd.getString(0), sender);
        if (target == null) {
            throw new CommandException(ChatConstant.ERROR_PLAYER_NOT_FOUND.getMessage(ChatUtil.getLocale(sender)));
        }
        if (Settings.getSettingByName("PrivateMessages") == null || Settings.getSettingByName("PrivateMessages").getValueByPlayer(target).getValue().equalsIgnoreCase("all")) {
            target.sendMessage(ChatColor.GRAY + "(From " + Players.getName(sender) + ChatColor.GRAY + "): " + ChatColor.RESET + cmd.getJoinedStrings(1));
            sender.sendMessage(ChatColor.GRAY + "(To " + Players.getName(target) + ChatColor.GRAY + "): " + ChatColor.RESET + cmd.getJoinedStrings(1));
            target.setMetadata("reply", new FixedMetadataValue(Cardinal.getInstance(), sender));
        } else {
            sender.sendMessage(new LocalizedChatMessage(ChatConstant.ERROR_PLAYER_DISABLED_PMS, Players.getName(target) + ChatColor.RED).getMessage(ChatUtil.getLocale(sender)));
        }
    }

    @Command(aliases = {"reply", "r"}, desc = "Reply to a private message", min = 1)
    public static void reply(final CommandContext cmd, CommandSender sender) throws CommandException {
        if (!(sender instanceof Player)) {
            throw new CommandException(ChatConstant.ERROR_PLAYER_COMMAND.getMessage(ChatUtil.getLocale(sender)));
        }
        Player player = (Player) sender;
        if (!player.hasMetadata("reply")) {
            throw new CommandException(ChatConstant.ERROR_NO_MESSAGES.getMessage(ChatUtil.getLocale(sender)));
        }
        Player target = (Player) player.getMetadata("reply").get(0).value();
        if (target == null) {
            throw new CommandException(ChatConstant.ERROR_PLAYER_NOT_FOUND.getMessage(ChatUtil.getLocale(sender)));
        }
        if (Settings.getSettingByName("PrivateMessages") == null || Settings.getSettingByName("PrivateMessages").getValueByPlayer(target).getValue().equalsIgnoreCase("all")) {
            target.sendMessage(ChatColor.GRAY + "(From " + Players.getName(sender) + ChatColor.GRAY + "): " + ChatColor.RESET + cmd.getJoinedStrings(0));
            sender.sendMessage(ChatColor.GRAY + "(To " + Players.getName(target) + ChatColor.GRAY + "): " + ChatColor.RESET + cmd.getJoinedStrings(0));
            target.setMetadata("reply", new FixedMetadataValue(Cardinal.getInstance(), sender));
        } else {
            sender.sendMessage(new LocalizedChatMessage(ChatConstant.ERROR_PLAYER_DISABLED_PMS, Players.getName(target) + ChatColor.RED).getMessage(ChatUtil.getLocale(sender)));
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.driveactivity.v2.model;

/**
 * How the individual activities are consolidated. A set of activities may be consolidated into one
 * combined activity if they are related in some way, such as one actor performing the same action
 * on multiple targets, or multiple actors performing the same action on a single target. The
 * strategy defines the rules for which activities are related.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Drive Activity API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ConsolidationStrategy extends com.google.api.client.json.GenericJson {

  /**
   * The individual activities are consolidated using the legacy strategy.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Legacy legacy;

  /**
   * The individual activities are not consolidated.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private NoConsolidation none;

  /**
   * The individual activities are consolidated using the legacy strategy.
   * @return value or {@code null} for none
   */
  public Legacy getLegacy() {
    return legacy;
  }

  /**
   * The individual activities are consolidated using the legacy strategy.
   * @param legacy legacy or {@code null} for none
   */
  public ConsolidationStrategy setLegacy(Legacy legacy) {
    this.legacy = legacy;
    return this;
  }

  /**
   * The individual activities are not consolidated.
   * @return value or {@code null} for none
   */
  public NoConsolidation getNone() {
    return none;
  }

  /**
   * The individual activities are not consolidated.
   * @param none none or {@code null} for none
   */
  public ConsolidationStrategy setNone(NoConsolidation none) {
    this.none = none;
    return this;
  }

  @Override
  public ConsolidationStrategy set(String fieldName, Object value) {
    return (ConsolidationStrategy) super.set(fieldName, value);
  }

  @Override
  public ConsolidationStrategy clone() {
    return (ConsolidationStrategy) super.clone();
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.opencb.opencga</groupId>
        <artifactId>opencga</artifactId>
        <version>2.6.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>opencga-clinical</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-storage-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-catalog</artifactId>
        </dependency>
        <dependency>
            <groupId>org.opencb.commons</groupId>
            <artifactId>commons-datastore-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-catalog</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-storage-core</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-storage-mongodb</artifactId>
            <version>${project.parent.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.opencb.opencga</groupId>
            <artifactId>opencga-storage-mongodb</artifactId>
            <version>${project.parent.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-test-framework</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>rga/managed-schema</include>
                    <include>rga/aux-managed-schema</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <id>test-jar</id>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
sample-grape-api
================

Simple Grape API to demonstrate Grape

- start redis
`bundle exec redis-server`

- start web server
`bundle exec puma`


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="au.com.codeka.rps.FindingOpponentFragment">

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        style="?android:attr/progressBarStyleLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/progress"
        android:layout_centerHorizontal="true"
        android:text="Waiting for opponent..." />

</RelativeLayout>


text:
package <%= appPackage %>.domain.services.jobs;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import <%= appPackage %>.domain.services.SyncCommentRxBus;
import <%= appPackage %>.domain.services.SyncResponseEventType;
import <%= appPackage %>.model.Comment;
import <%= appPackage %>.model.CommentUtils;
import <%= appPackage %>.domain.services.networking.RemoteCommentService;
import <%= appPackage %>.domain.services.networking.RemoteException;

import timber.log.Timber;

public class SyncCommentJob extends Job {

    private static final String TAG = SyncCommentJob.class.getCanonicalName();
    private final Comment comment;

    public SyncCommentJob(Comment comment) {
        super(new Params(JobPriority.MID)
                .requireNetwork()
                .groupBy(TAG)
                .persist());
        this.comment = comment;
    }

    @Override
    public void onAdded() {
        Timber.d("Executing onAdded() for comment " + comment);
    }

    @Override
    public void onRun() throws Throwable {
        Timber.d("Executing onRun() for comment " + comment);

        // if any exception is thrown, it will be handled by shouldReRunOnThrowable()
        RemoteCommentService.getInstance().addComment(comment);

        // remote call was successful--the Comment will be updated locally to reflect that sync is no longer pending
        Comment updatedComment = CommentUtils.clone(comment, false);
        SyncCommentRxBus.getInstance().post(SyncResponseEventType.SUCCESS, updatedComment);
    }

    @Override
    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
        Timber.d("canceling job. reason: %d, throwable: %s", cancelReason, throwable);
        // sync to remote failed
        SyncCommentRxBus.getInstance().post(SyncResponseEventType.FAILED, comment);
    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
        if(throwable instanceof RemoteException) {
            RemoteException exception = (RemoteException) throwable;

            int statusCode = exception.getResponse().code();
            if (statusCode >= 400 && statusCode < 500) {
                return RetryConstraint.CANCEL;
            }
        }
        // if we are here, most likely the connection was lost during job execution
        return RetryConstraint.RETRY;
    }
}


text:
package org.apache.karaf.web.management.internal;

import org.apache.karaf.web.WebBundle;
import org.apache.karaf.web.WebContainerService;
import org.apache.karaf.web.management.WebMBean;

import javax.management.MBeanException;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
import javax.management.openmbean.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Implementation of the Web MBean.
 */
public class WebMBeanImpl extends StandardMBean implements WebMBean {

    private WebContainerService webContainerService;

    public WebMBeanImpl() throws NotCompliantMBeanException {
        super(WebMBean.class);
    }

    public void setWebContainerService(WebContainerService webContainerService) {
        this.webContainerService = webContainerService;
    }

    public TabularData getWebBundles() throws MBeanException {
        try {
            CompositeType webType = new CompositeType("Web Bundle", "An OSGi Web bundle",
                    new String[]{"ID", "State", "Web-State", "Level", "Web-ContextPath", "Name"},
                    new String[]{"ID of the bundle",
                            "OSGi state of the bundle",
                            "Web state of the bundle",
                            "Start level of the bundle",
                            "Web context path",
                            "Name of the bundle"},
                    new OpenType[]{SimpleType.LONG, SimpleType.STRING, SimpleType.STRING, SimpleType.INTEGER, SimpleType.STRING, SimpleType.STRING});
            TabularType tableType = new TabularType("Web Bundles", "Table of web bundles", webType,
                    new String[]{"ID"});
            TabularData table = new TabularDataSupport(tableType);
            for (WebBundle webBundle : webContainerService.list()) {
                try {
                    CompositeData data = new CompositeDataSupport(webType,
                            new String[]{"ID", "State", "Web-State", "Level", "Web-ContextPath", "Name"},
                            new Object[]{webBundle.getBundleId(),
                                    webBundle.getState(),
                                    webBundle.getWebState(),
                                    webBundle.getLevel(),
                                    webBundle.getContextPath(),
                                    webBundle.getName()});
                    table.put(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return table;
        } catch (Exception e) {
            throw new MBeanException(null, e.toString());
        }
    }

    public void start(Long bundleId) throws MBeanException {
        try {
            List<Long> list = new ArrayList<>();
            list.add(bundleId);
            webContainerService.start(list);
        } catch (Exception e) {
            throw new MBeanException(null, e.toString());
        }
    }

    public void start(List<Long> bundleIds) throws MBeanException {
        try {
            webContainerService.start(bundleIds);
        } catch (Exception e) {
            throw new MBeanException(null, e.toString());
        }
    }

    public void stop(Long bundleId) throws MBeanException {
        try {
            List<Long> list = new ArrayList<>();
            list.add(bundleId);
            webContainerService.stop(list);
        } catch (Exception e) {
            throw new MBeanException(null, e.toString());
        }
    }

    public void stop(List<Long> bundleIds) throws MBeanException {
        try {
            webContainerService.stop(bundleIds);
        } catch (Exception e) {
            throw new MBeanException(null, e.toString());
        }
    }

}


text:
package compose

import (
	"net/http"
	"time"

	"github.com/ory/fosite"
	foauth2 "github.com/ory/fosite/handler/oauth2"
	"github.com/ory/hydra/firewall"
	. "github.com/ory/hydra/oauth2"
	"github.com/ory/hydra/pkg"
	"github.com/ory/hydra/warden"
	"github.com/ory/hydra/warden/group"
	"github.com/ory/ladon"
	"github.com/sirupsen/logrus"
	"golang.org/x/oauth2"
)

func NewMockFirewall(issuer string, subject string, scopes fosite.Arguments, p ...ladon.Policy) (firewall.Firewall, *http.Client) {
	tokens := pkg.Tokens(1)

	fositeStore := pkg.FositeStore()
	ps := map[string]ladon.Policy{}

	for _, x := range p {
		ps[x.GetID()] = x
	}
	ladonWarden := pkg.LadonWarden(ps)

	ar := fosite.NewAccessRequest(NewSession(subject))
	ar.GrantedScopes = scopes
	fositeStore.CreateAccessTokenSession(nil, tokens[0][0], ar)

	conf := &oauth2.Config{Scopes: scopes, Endpoint: oauth2.Endpoint{}}

	return &warden.LocalWarden{
			Warden: ladonWarden,
			OAuth2: &fosite.Fosite{
				Store: fositeStore,
				TokenIntrospectionHandlers: fosite.TokenIntrospectionHandlers{
					&foauth2.CoreValidator{
						CoreStrategy:  pkg.HMACStrategy,
						CoreStorage:   fositeStore,
						ScopeStrategy: fosite.HierarchicScopeStrategy,
					},
				},
				ScopeStrategy: fosite.HierarchicScopeStrategy,
			},
			Issuer:              issuer,
			AccessTokenLifespan: time.Hour,
			Groups:              group.NewMemoryManager(),
			L:                   logrus.New(),
		}, conf.Client(oauth2.NoContext, &oauth2.Token{
			AccessToken: tokens[0][1],
			Expiry:      time.Now().Add(time.Hour),
			TokenType:   "bearer",
		})
}


text:
autoload :Closure, 'closure-compiler'

module Fewer
  module Engines
    class Js < Abstract
      self.content_type = 'application/x-javascript'
      self.extension = '.js'

      def read
        if options[:min]
          ::Closure::Compiler.new.compress(super)
        else
          super
        end
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Bkstg\CoreBundle\Tests\Event;

use Bkstg\CoreBundle\Event\EntityPublishedEvent;
use PHPUnit\Framework\TestCase;

class EntityPublishedEventTest extends TestCase
{
    /**
     * Tests the entity published event.
     *
     * @return void
     */
    public function testEvent(): void
    {
        $object = new \stdClass();
        $event = new EntityPublishedEvent($object);
        $this->assertSame($event->getObject(), $object);
    }
}


text:
import argparse
from collections import OrderedDict
import sys

from common_includes import *

ALREADY_MERGING_SENTINEL_FILE = "ALREADY_MERGING_SENTINEL_FILE"
COMMIT_HASHES_FILE = "COMMIT_HASHES_FILE"
TEMPORARY_PATCH_FILE = "TEMPORARY_PATCH_FILE"

CONFIG = {
  BRANCHNAME: "prepare-merge",
  PERSISTFILE_BASENAME: "/tmp/v8-merge-to-branch-tempfile",
  ALREADY_MERGING_SENTINEL_FILE:
      "/tmp/v8-merge-to-branch-tempfile-already-merging",
  DOT_GIT_LOCATION: ".git",
  VERSION_FILE: "src/version.cc",
  TEMPORARY_PATCH_FILE: "/tmp/v8-prepare-merge-tempfile-temporary-patch",
  COMMITMSG_FILE: "/tmp/v8-prepare-merge-tempfile-commitmsg",
  COMMIT_HASHES_FILE: "/tmp/v8-merge-to-branch-tempfile-PATCH_COMMIT_HASHES",
}

class Preparation(Step):
  MESSAGE = "Preparation."

  def RunStep(self):
    if os.path.exists(self.Config(ALREADY_MERGING_SENTINEL_FILE)):
      if self._options.force:
        os.remove(self.Config(ALREADY_MERGING_SENTINEL_FILE))
      elif self._options.step == 0:  # pragma: no cover
        self.Die("A merge is already in progress")
    open(self.Config(ALREADY_MERGING_SENTINEL_FILE), "a").close()

    self.InitialEnvironmentChecks()
    if self._options.revert_bleeding_edge:
      self["merge_to_branch"] = "bleeding_edge"
    elif self._options.branch:
      self["merge_to_branch"] = self._options.branch
    else:  # pragma: no cover
      self.Die("Please specify a branch to merge to")

    self.CommonPrepare()
    self.PrepareBranch()

class CreateBranch(Step):
  MESSAGE = "Create a fresh branch for the patch."

  def RunStep(self):
    self.GitCreateBranch(self.Config(BRANCHNAME),
                         "svn/%s" % self["merge_to_branch"])

class SearchArchitecturePorts(Step):
  MESSAGE = "Search for corresponding architecture ports."

  def RunStep(self):
    self["full_revision_list"] = list(OrderedDict.fromkeys(
        self._options.revisions))
    port_revision_list = []
    for revision in self["full_revision_list"]:
      # Search for commits which matches the "Port rXXX" pattern.
      git_hashes = self.GitLog(reverse=True, format="%H",
                               grep="Port r%d" % int(revision),
                               branch="svn/bleeding_edge")
      for git_hash in git_hashes.splitlines():
        svn_revision = self.GitSVNFindSVNRev(git_hash, "svn/bleeding_edge")
        if not svn_revision:  # pragma: no cover
          self.Die("Cannot determine svn revision for %s" % git_hash)
        revision_title = self.GitLog(n=1, format="%s", git_hash=git_hash)

        # Is this revision included in the original revision list?
        if svn_revision in self["full_revision_list"]:
          print("Found port of r%s -> r%s (already included): %s"
                % (revision, svn_revision, revision_title))
        else:
          print("Found port of r%s -> r%s: %s"
                % (revision, svn_revision, revision_title))
          port_revision_list.append(svn_revision)

    # Do we find any port?
    if len(port_revision_list) > 0:
      if self.Confirm("Automatically add corresponding ports (%s)?"
                      % ", ".join(port_revision_list)):
        #: 'y': Add ports to revision list.
        self["full_revision_list"].extend(port_revision_list)

class FindGitRevisions(Step):
  MESSAGE = "Find the git revisions associated with the patches."

  def RunStep(self):
    self["patch_commit_hashes"] = []
    for revision in self["full_revision_list"]:
      next_hash = self.GitSVNFindGitHash(revision, "svn/bleeding_edge")
      if not next_hash:  # pragma: no cover
        self.Die("Cannot determine git hash for r%s" % revision)
      self["patch_commit_hashes"].append(next_hash)

    # Stringify: [123, 234] -> "r123, r234"
    self["revision_list"] = ", ".join(map(lambda s: "r%s" % s,
                                      self["full_revision_list"]))

    if not self["revision_list"]:  # pragma: no cover
      self.Die("Revision list is empty.")

    # The commit message title is added below after the version is specified.
    self["new_commit_msg"] = ""

    for commit_hash in self["patch_commit_hashes"]:
      patch_merge_desc = self.GitLog(n=1, format="%s", git_hash=commit_hash)
      self["new_commit_msg"] += "%s\n\n" % patch_merge_desc

    bugs = []
    for commit_hash in self["patch_commit_hashes"]:
      msg = self.GitLog(n=1, git_hash=commit_hash)
      for bug in re.findall(r"^[ \t]*BUG[ \t]*=[ \t]*(.*?)[ \t]*$", msg,
                            re.M):
        bugs.extend(map(lambda s: s.strip(), bug.split(",")))
    bug_aggregate = ",".join(sorted(filter(lambda s: s and s != "none", bugs)))
    if bug_aggregate:
      self["new_commit_msg"] += "BUG=%s\nLOG=N\n" % bug_aggregate

class ApplyPatches(Step):
  MESSAGE = "Apply patches for selected revisions."

  def RunStep(self):
    for commit_hash in self["patch_commit_hashes"]:
      print("Applying patch for %s to %s..."
            % (commit_hash, self["merge_to_branch"]))
      patch = self.GitGetPatch(commit_hash)
      TextToFile(patch, self.Config(TEMPORARY_PATCH_FILE))
      self.ApplyPatch(self.Config(TEMPORARY_PATCH_FILE), self._options.revert)
    if self._options.patch:
      self.ApplyPatch(self._options.patch, self._options.revert)

class PrepareVersion(Step):
  MESSAGE = "Prepare version file."

  def RunStep(self):
    if self._options.revert_bleeding_edge:
      return
    # This is used to calculate the patch level increment.
    self.ReadAndPersistVersion()

class IncrementVersion(Step):
  MESSAGE = "Increment version number."

  def RunStep(self):
    if self._options.revert_bleeding_edge:
      return
    new_patch = str(int(self["patch"]) + 1)
    if self.Confirm("Automatically increment PATCH_LEVEL? (Saying 'n' will "
                    "fire up your EDITOR on %s so you can make arbitrary "
                    "changes. When you're done, save the file and exit your "
                    "EDITOR.)" % self.Config(VERSION_FILE)):
      text = FileToText(self.Config(VERSION_FILE))
      text = MSub(r"(?<=#define PATCH_LEVEL)(?P<space>\s+)\d*$",
                  r"\g<space>%s" % new_patch,
                  text)
      TextToFile(text, self.Config(VERSION_FILE))
    else:
      self.Editor(self.Config(VERSION_FILE))
    self.ReadAndPersistVersion("new_")
    self["version"] = "%s.%s.%s.%s" % (self["new_major"],
                                       self["new_minor"],
                                       self["new_build"],
                                       self["new_patch"])

class CommitLocal(Step):
  MESSAGE = "Commit to local branch."

  def RunStep(self):
    # Add a commit message title.
    if self._options.revert:
      if not self._options.revert_bleeding_edge:
        title = ("Version %s (rollback of %s)"
                 % (self["version"], self["revision_list"]))
      else:
        title = "Revert %s." % self["revision_list"]
    else:
      title = ("Version %s (merged %s)"
               % (self["version"], self["revision_list"]))
    self["new_commit_msg"] = "%s\n\n%s" % (title, self["new_commit_msg"])
    TextToFile(self["new_commit_msg"], self.Config(COMMITMSG_FILE))
    self.GitCommit(file_name=self.Config(COMMITMSG_FILE))

class CommitRepository(Step):
  MESSAGE = "Commit to the repository."

  def RunStep(self):
    self.GitCheckout(self.Config(BRANCHNAME))
    self.WaitForLGTM()
    self.GitPresubmit()
    self.GitDCommit()

class PrepareSVN(Step):
  MESSAGE = "Determine svn commit revision."

  def RunStep(self):
    if self._options.revert_bleeding_edge:
      return
    self.GitSVNFetch()
    commit_hash = self.GitLog(n=1, format="%H", grep=self["new_commit_msg"],
                              branch="svn/%s" % self["merge_to_branch"])
    if not commit_hash:  # pragma: no cover
      self.Die("Unable to map git commit to svn revision.")
    self["svn_revision"] = self.GitSVNFindSVNRev(commit_hash)
    print "subversion revision number is r%s" % self["svn_revision"]

class TagRevision(Step):
  MESSAGE = "Create the tag."

  def RunStep(self):
    if self._options.revert_bleeding_edge:
      return
    print "Creating tag svn/tags/%s" % self["version"]
    if self["merge_to_branch"] == "trunk":
      self["to_url"] = "trunk"
    else:
      self["to_url"] = "branches/%s" % self["merge_to_branch"]
    self.SVN("copy -r %s https://v8.googlecode.com/svn/%s "
             "https://v8.googlecode.com/svn/tags/%s -m "
             "\"Tagging version %s\""
             % (self["svn_revision"], self["to_url"],
                self["version"], self["version"]))

class CleanUp(Step):
  MESSAGE = "Cleanup."

  def RunStep(self):
    self.CommonCleanup()
    if not self._options.revert_bleeding_edge:
      print "*** SUMMARY ***"
      print "version: %s" % self["version"]
      print "branch: %s" % self["to_url"]
      print "svn revision: %s" % self["svn_revision"]
      if self["revision_list"]:
        print "patches: %s" % self["revision_list"]

class MergeToBranch(ScriptsBase):
  def _Description(self):
    return ("Performs the necessary steps to merge revisions from "
            "bleeding_edge to other branches, including trunk.")

  def _PrepareOptions(self, parser):
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--branch", help="The branch to merge to.")
    group.add_argument("-R", "--revert-bleeding-edge",
                       help="Revert specified patches from bleeding edge.",
                       default=False, action="store_true")
    parser.add_argument("revisions", nargs="*",
                        help="The revisions to merge.")
    parser.add_argument("-f", "--force",
                        help="Delete sentinel file.",
                        default=False, action="store_true")
    parser.add_argument("-m", "--message",
                        help="A commit message for the patch.")
    parser.add_argument("--revert",
                        help="Revert specified patches.",
                        default=False, action="store_true")
    parser.add_argument("-p", "--patch",
                        help="A patch file to apply as part of the merge.")

  def _ProcessOptions(self, options):
    # TODO(machenbach): Add a test that covers revert from bleeding_edge
    if len(options.revisions) < 1:
      if not options.patch:
        print "Either a patch file or revision numbers must be specified"
        return False
      if not options.message:
        print "You must specify a merge comment if no patches are specified"
        return False
    return True

  def _Steps(self):
    return [
      Preparation,
      CreateBranch,
      SearchArchitecturePorts,
      FindGitRevisions,
      ApplyPatches,
      PrepareVersion,
      IncrementVersion,
      CommitLocal,
      UploadStep,
      CommitRepository,
      PrepareSVN,
      TagRevision,
      CleanUp,
    ]

if __name__ == "__main__":  # pragma: no cover
  sys.exit(MergeToBranch(CONFIG).Run())


text:
include_recipe "minecraft-server::bukkit"

# Plugin path, file permissions and remote URI (see below)
remote_file "#{node[:minecraft][:server_dir]}/plugins/worldguard.zip" do
  owner node[:minecraft][:user]
  group node[:minecraft][:user]
  mode 0644
  source "http://dev.bukkit.org/media/files/635/730/worldguard-5.5.4.zip"
  action :nothing
end

# Only run above if file does not exist or has changed
http_request "HEAD #{'http://dev.bukkit.org/media/files/635/730/worldguard-5.5.4.zip'}" do
  message ""
  url "http://dev.bukkit.org/media/files/635/730/worldguard-5.5.4.zip"
  action :head
  if File.exists?("#{node[:minecraft][:server_dir]}/plugins/worldguard.zip")
    headers "If-Modified-Since" => File.mtime("#{node[:minecraft][:server_dir]}/plugins/worldguard.zip").httpdate
  end
  notifies :create, resources(:remote_file => "#{node[:minecraft][:server_dir]}/plugins/worldguard.zip"), :immediately
end

# Unzip compressed plugin archive (skip help docs)
execute "unzip-plugin" do
  cwd "#{node[:minecraft][:server_dir]}/plugins/"
  user node[:minecraft][:user]
  group node[:minecraft][:user]
  command "unzip #{node[:minecraft][:server_dir]}/plugins/worldguard.zip -x *.txt *.html"
  creates "#{node[:minecraft][:server_dir]}/plugins/WorldGuard.jar"
  not_if do
    File.exists?("#{node[:minecraft][:server_dir]}/plugins/WorldGuard.jar")
  end
end


text:
package org.apache.catalina.core;

import java.lang.reflect.Method;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.SingleThreadModel;
import javax.servlet.UnavailableException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import org.apache.PeriodicEventListener;
import org.apache.catalina.Container;
import org.apache.catalina.ContainerServlet;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.catalina.InstanceEvent;
import org.apache.catalina.InstanceListener;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Loader;
import org.apache.catalina.Wrapper;
import org.apache.catalina.security.SecurityUtil;
import org.apache.catalina.util.Enumerator;
import org.apache.catalina.util.InstanceSupport;
import org.apache.tomcat.util.log.SystemLogHandler;
import org.apache.tomcat.util.modeler.Registry;

/**
 * Standard implementation of the Wrapper interface that represents
 * an individual servlet definition.  No child Containers are allowed, and
 * the parent Container must be a Context.
 *
 * @author Craig R. McClanahan
 * @author Remy Maucherat
 *
 */
public class StandardWrapper
    extends ContainerBase
    implements ServletConfig, Wrapper, NotificationEmitter {

    protected static org.apache.juli.logging.Log log=
        org.apache.juli.logging.LogFactory.getLog( StandardWrapper.class );

    protected static final String[] DEFAULT_SERVLET_METHODS = new String[] {
                                                    "GET", "HEAD", "POST" };

    // ----------------------------------------------------------- Constructors

    /**
     * Create a new StandardWrapper component with the default basic Valve.
     */
    public StandardWrapper() {

        super();
        swValve=new StandardWrapperValve();
        pipeline.setBasic(swValve);
        broadcaster = new NotificationBroadcasterSupport();

        if (restrictedServlets == null) {
            restrictedServlets = new Properties();
            try {
                InputStream is =
                    this.getClass().getClassLoader().getResourceAsStream
                        ("org/apache/catalina/core/RestrictedServlets.properties");
                if (is != null) {
                    restrictedServlets.load(is);
                } else {
                    log.error(sm.getString("standardWrapper.restrictedServletsResource"));
                }
            } catch (IOException e) {
                log.error(sm.getString("standardWrapper.restrictedServletsResource"), e);
            }
        }

    }

    // ----------------------------------------------------- Instance Variables

    /**
     * The date and time at which this servlet will become available (in
     * milliseconds since the epoch), or zero if the servlet is available.
     * If this value equals Long.MAX_VALUE, the unavailability of this
     * servlet is considered permanent.
     */
    protected long available = 0L;

    /**
     * The broadcaster that sends j2ee notifications.
     */
    protected NotificationBroadcasterSupport broadcaster = null;

    /**
     * The count of allocations that are currently active (even if they
     * are for the same instance, as will be true on a non-STM servlet).
     */
    protected AtomicInteger countAllocated = new AtomicInteger(0);

    /**
     * The facade associated with this wrapper.
     */
    protected StandardWrapperFacade facade =
        new StandardWrapperFacade(this);

    /**
     * The descriptive information string for this implementation.
     */
    protected static final String info =
        "org.apache.catalina.core.StandardWrapper/1.0";

    /**
     * The (single) initialized instance of this servlet.
     */
    protected Servlet instance = null;

    /**
     * The support object for our instance listeners.
     */
    protected InstanceSupport instanceSupport = new InstanceSupport(this);

    /**
     * The context-relative URI of the JSP file for this servlet.
     */
    protected String jspFile = null;

    /**
     * The load-on-startup order value (negative value means load on
     * first call) for this servlet.
     */
    protected int loadOnStartup = -1;

    /**
     * Mappings associated with the wrapper.
     */
    protected ArrayList mappings = new ArrayList();

    /**
     * The initialization parameters for this servlet, keyed by
     * parameter name.
     */
    protected HashMap parameters = new HashMap();

    /**
     * The security role references for this servlet, keyed by role name
     * used in the servlet.  The corresponding value is the role name of
     * the web application itself.
     */
    protected HashMap references = new HashMap();

    /**
     * The run-as identity for this servlet.
     */
    protected String runAs = null;

    /**
     * The notification sequence number.
     */
    protected long sequenceNumber = 0;

    /**
     * The fully qualified servlet class name for this servlet.
     */
    protected String servletClass = null;

    /**
     * Does this servlet implement the SingleThreadModel interface?
     */
    protected boolean singleThreadModel = false;

    /**
     * Are we unloading our servlet instance at the moment?
     */
    protected boolean unloading = false;

    /**
     * Maximum number of STM instances.
     */
    protected int maxInstances = 20;

    /**
     * Number of instances currently loaded for a STM servlet.
     */
    protected int nInstances = 0;

    /**
     * Stack containing the STM instances.
     */
    protected Stack instancePool = null;

    /**
     * Wait time for servlet unload in ms.
     */
    protected long unloadDelay = 2000;

    /**
     * True if this StandardWrapper is for the JspServlet
     */
    protected boolean isJspServlet;

    /**
     * The ObjectName of the JSP monitoring mbean
     */
    protected ObjectName jspMonitorON;

    /**
     * Should we swallow System.out
     */
    protected boolean swallowOutput = false;

    // To support jmx attributes
    protected StandardWrapperValve swValve;
    protected long loadTime=0;
    protected int classLoadTime=0;

    /**
     * Static class array used when the SecurityManager is turned on and
     * Servlet.init is invoked.
     */
    protected static Class[] classType = new Class[]{ServletConfig.class};

    /**
     * Static class array used when the SecurityManager is turned on and
     * Servlet.service  is invoked.
     */
    protected static Class[] classTypeUsedInService = new Class[]{
                                                         ServletRequest.class,
                                                         ServletResponse.class};

    /**
     * Restricted servlets (which can only be loaded by a privileged webapp).
     */
    protected static Properties restrictedServlets = null;

    private final ReentrantReadWriteLock parametersLock =
            new ReentrantReadWriteLock();

    private final ReentrantReadWriteLock mappingsLock =
            new ReentrantReadWriteLock();

    private final ReentrantReadWriteLock referencesLock =
            new ReentrantReadWriteLock();

    // ------------------------------------------------------------- Properties

    /**
     * Return the available date/time for this servlet, in milliseconds since
     * the epoch.  If this date/time is Long.MAX_VALUE, it is considered to mean
     * that unavailability is permanent and any request for this servlet will return
     * an SC_NOT_FOUND error.  If this date/time is in the future, any request for
     * this servlet will return an SC_SERVICE_UNAVAILABLE error.  If it is zero,
     * the servlet is currently available.
     */
    public long getAvailable() {

        return (this.available);

    }

    /**
     * Set the available date/time for this servlet, in milliseconds since the
     * epoch.  If this date/time is Long.MAX_VALUE, it is considered to mean
     * that unavailability is permanent and any request for this servlet will return
     * an SC_NOT_FOUND error. If this date/time is in the future, any request for
     * this servlet will return an SC_SERVICE_UNAVAILABLE error.
     *
     * @param available The new available date/time
     */
    public void setAvailable(long available) {

        long oldAvailable = this.available;
        if (available > System.currentTimeMillis())
            this.available = available;
        else
            this.available = 0L;
        support.firePropertyChange("available", new Long(oldAvailable),
                                   new Long(this.available));

    }

    /**
     * Return the number of active allocations of this servlet, even if they
     * are all for the same instance (as will be true for servlets that do
     * not implement SingleThreadModel.
     */
    public int getCountAllocated() {

        return (this.countAllocated.get());

    }

    public String getEngineName() {
        return ((StandardContext)getParent()).getEngineName();
    }

    /**
     * Return descriptive information about this Container implementation and
     * the corresponding version number, in the format
     * <description>/<version>.
     */
    public String getInfo() {

        return (info);

    }

    /**
     * Return the InstanceSupport object for this Wrapper instance.
     */
    public InstanceSupport getInstanceSupport() {

        return (this.instanceSupport);

    }

    /**
     * Return the context-relative URI of the JSP file for this servlet.
     */
    public String getJspFile() {

        return (this.jspFile);

    }

    /**
     * Set the context-relative URI of the JSP file for this servlet.
     *
     * @param jspFile JSP file URI
     */
    public void setJspFile(String jspFile) {

        String oldJspFile = this.jspFile;
        this.jspFile = jspFile;
        support.firePropertyChange("jspFile", oldJspFile, this.jspFile);

        // Each jsp-file needs to be represented by its own JspServlet and
        // corresponding JspMonitoring mbean, because it may be initialized
        // with its own init params
        isJspServlet = true;

    }

    /**
     * Return the load-on-startup order value (negative value means
     * load on first call).
     */
    public int getLoadOnStartup() {

        if (isJspServlet && loadOnStartup < 0) {
            /*
             * JspServlet must always be preloaded, because its instance is
             * used during registerJMX (when registering the JSP
             * monitoring mbean)
             */
             return Integer.MAX_VALUE;
        } else {
            return (this.loadOnStartup);
        }
    }

    /**
     * Set the load-on-startup order value (negative value means
     * load on first call).
     *
     * @param value New load-on-startup value
     */
    public void setLoadOnStartup(int value) {

        int oldLoadOnStartup = this.loadOnStartup;
        this.loadOnStartup = value;
        support.firePropertyChange("loadOnStartup",
                                   new Integer(oldLoadOnStartup),
                                   new Integer(this.loadOnStartup));

    }

    /**
     * Set the load-on-startup order value from a (possibly null) string.
     * Per the specification, any missing or non-numeric value is converted
     * to a zero, so that this servlet will still be loaded at startup
     * time, but in an arbitrary order.
     *
     * @param value New load-on-startup value
     */
    public void setLoadOnStartupString(String value) {

        try {
            setLoadOnStartup(Integer.parseInt(value));
        } catch (NumberFormatException e) {
            setLoadOnStartup(0);
        }
    }

    public String getLoadOnStartupString() {
        return Integer.toString( getLoadOnStartup());
    }

    /**
     * Return maximum number of instances that will be allocated when a single
     * thread model servlet is used.
     */
    public int getMaxInstances() {

        return (this.maxInstances);

    }

    /**
     * Set the maximum number of instances that will be allocated when a single
     * thread model servlet is used.
     *
     * @param maxInstances New value of maxInstances
     */
    public void setMaxInstances(int maxInstances) {

        int oldMaxInstances = this.maxInstances;
        this.maxInstances = maxInstances;
        support.firePropertyChange("maxInstances", oldMaxInstances,
                                   this.maxInstances);

    }

    /**
     * Set the parent Container of this Wrapper, but only if it is a Context.
     *
     * @param container Proposed parent Container
     */
    public void setParent(Container container) {

        if ((container != null) &&
            !(container instanceof Context))
            throw new IllegalArgumentException
                (sm.getString("standardWrapper.notContext"));
        if (container instanceof StandardContext) {
            swallowOutput = ((StandardContext)container).getSwallowOutput();
            unloadDelay = ((StandardContext)container).getUnloadDelay();
        }
        super.setParent(container);

    }

    /**
     * Return the run-as identity for this servlet.
     */
    public String getRunAs() {

        return (this.runAs);

    }

    /**
     * Set the run-as identity for this servlet.
     *
     * @param runAs New run-as identity value
     */
    public void setRunAs(String runAs) {

        String oldRunAs = this.runAs;
        this.runAs = runAs;
        support.firePropertyChange("runAs", oldRunAs, this.runAs);

    }

    /**
     * Return the fully qualified servlet class name for this servlet.
     */
    public String getServletClass() {

        return (this.servletClass);

    }

    /**
     * Set the fully qualified servlet class name for this servlet.
     *
     * @param servletClass Servlet class name
     */
    public void setServletClass(String servletClass) {

        String oldServletClass = this.servletClass;
        this.servletClass = servletClass;
        support.firePropertyChange("servletClass", oldServletClass,
                                   this.servletClass);
        if (Constants.JSP_SERVLET_CLASS.equals(servletClass)) {
            isJspServlet = true;
        }
    }

    /**
     * Set the name of this servlet.  This is an alias for the normal
     * Container.setName() method, and complements the
     * getServletName() method required by the
     * ServletConfig interface.
     *
     * @param name The new name of this servlet
     */
    public void setServletName(String name) {

        setName(name);

    }

    /**
     * Return true if the servlet class represented by this
     * component implements the SingleThreadModel interface.
     */
    public boolean isSingleThreadModel() {

        try {
            loadServlet();
        } catch (Throwable t) {
            ;
        }
        return (singleThreadModel);

    }

    /**
     * Is this servlet currently unavailable?
     */
    public boolean isUnavailable() {

        if (available == 0L)
            return (false);
        else if (available <= System.currentTimeMillis()) {
            available = 0L;
            return (false);
        } else
            return (true);

    }

    /**
     * Gets the names of the methods supported by the underlying servlet.
     *
     * This is the same set of methods included in the Allow response header
     * in response to an OPTIONS request method processed by the underlying
     * servlet.
     *
     * @return Array of names of the methods supported by the underlying
     * servlet
     */
    public String[] getServletMethods() throws ServletException {

        Class servletClazz = loadServlet().getClass();
        if (!javax.servlet.http.HttpServlet.class.isAssignableFrom(
                                                        servletClazz)) {
            return DEFAULT_SERVLET_METHODS;
        }

        HashSet allow = new HashSet();
        allow.add("TRACE");
        allow.add("OPTIONS");

        Method[] methods = getAllDeclaredMethods(servletClazz);
        for (int i=0; methods != null && i<methods.length; i++) {
            Method m = methods[i];

            if (m.getName().equals("doGet")) {
                allow.add("GET");
                allow.add("HEAD");
            } else if (m.getName().equals("doPost")) {
                allow.add("POST");
            } else if (m.getName().equals("doPut")) {
                allow.add("PUT");
            } else if (m.getName().equals("doDelete")) {
                allow.add("DELETE");
            }
        }

        String[] methodNames = new String[allow.size()];
        return (String[]) allow.toArray(methodNames);

    }

    // --------------------------------------------------------- Public Methods

    /**
     * Execute a periodic task, such as reloading, etc. This method will be
     * invoked inside the classloading context of this container. Unexpected
     * throwables will be caught and logged.
     */
    public void backgroundProcess() {
        super.backgroundProcess();

        if (!started)
            return;

        if (getServlet() != null && (getServlet() instanceof PeriodicEventListener)) {
            ((PeriodicEventListener) getServlet()).periodicEvent();
        }
    }

    /**
     * Extract the root cause from a servlet exception.
     *
     * @param e The servlet exception
     */
    public static Throwable getRootCause(ServletException e) {
        Throwable rootCause = e;
        Throwable rootCauseCheck = null;
        // Extra aggressive rootCause finding
        int loops = 0;
        do {
            loops++;
            rootCauseCheck = rootCause.getCause();
            if (rootCauseCheck != null)
                rootCause = rootCauseCheck;
        } while (rootCauseCheck != null && (loops < 20));
        return rootCause;
    }

    /**
     * Refuse to add a child Container, because Wrappers are the lowest level
     * of the Container hierarchy.
     *
     * @param child Child container to be added
     */
    public void addChild(Container child) {

        throw new IllegalStateException
            (sm.getString("standardWrapper.notChild"));

    }

    /**
     * Add a new servlet initialization parameter for this servlet.
     *
     * @param name Name of this initialization parameter to add
     * @param value Value of this initialization parameter to add
     */
    public void addInitParameter(String name, String value) {

        try {
            parametersLock.writeLock().lock();
            parameters.put(name, value);
        } finally {
            parametersLock.writeLock().unlock();
        }
        fireContainerEvent("addInitParameter", name);

    }

    /**
     * Add a new listener interested in InstanceEvents.
     *
     * @param listener The new listener
     */
    public void addInstanceListener(InstanceListener listener) {

        instanceSupport.addInstanceListener(listener);

    }

    /**
     * Add a mapping associated with the Wrapper.
     *
     * @param mapping The new wrapper mapping
     */
    public void addMapping(String mapping) {

        try {
            mappingsLock.writeLock().lock();
            mappings.add(mapping);
        } finally {
            mappingsLock.writeLock().unlock();
        }
        fireContainerEvent("addMapping", mapping);

    }

    /**
     * Add a new security role reference record to the set of records for
     * this servlet.
     *
     * @param name Role name used within this servlet
     * @param link Role name used within the web application
     */
    public void addSecurityReference(String name, String link) {

        try {
            referencesLock.writeLock().lock();
            references.put(name, link);
        } finally {
            referencesLock.writeLock().unlock();
        }
        fireContainerEvent("addSecurityReference", name);

    }

    /**
     * Return the associated servlet instance.
     */
    public Servlet getServlet() {
        return instance;
    }

    /**
     * Allocate an initialized instance of this Servlet that is ready to have
     * its service() method called.  If the servlet class does
     * not implement SingleThreadModel, the (only) initialized
     * instance may be returned immediately.  If the servlet class implements
     * SingleThreadModel, the Wrapper implementation must ensure
     * that this instance is not allocated again until it is deallocated by a
     * call to deallocate().
     *
     * @exception ServletException if the servlet init() method threw
     *  an exception
     * @exception ServletException if a loading error occurs
     */
    public Servlet allocate() throws ServletException {

        // If we are currently unloading this servlet, throw an exception
        if (unloading)
            throw new ServletException
              (sm.getString("standardWrapper.unloading", getName()));

        boolean newInstance = false;

        // If not SingleThreadedModel, return the same instance every time
        if (!singleThreadModel) {

            // Load and initialize our instance if necessary
            if (instance == null) {
                synchronized (this) {
                    if (instance == null) {
                        try {
                            if (log.isDebugEnabled())
                                log.debug("Allocating non-STM instance");

                            instance = loadServlet();
                            // For non-STM, increment here to prevent a race
                            // condition with unload. Bug 43683, test case #3
                            if (!singleThreadModel) {
                                newInstance = true;
                                countAllocated.incrementAndGet();
                            }
                        } catch (ServletException e) {
                            throw e;
                        } catch (Throwable e) {
                            throw new ServletException
                                (sm.getString("standardWrapper.allocate"), e);
                        }
                    }
                }
            }

            if (!singleThreadModel) {
                if (log.isTraceEnabled())
                    log.trace("  Returning non-STM instance");
                // For new instances, count will have been incremented at the
                // time of creation
                if (!newInstance) {
                    countAllocated.incrementAndGet();
                }
                return (instance);
            }
        }

        synchronized (instancePool) {

            while (countAllocated.get() >= nInstances) {
                // Allocate a new instance if possible, or else wait
                if (nInstances < maxInstances) {
                    try {
                        instancePool.push(loadServlet());
                        nInstances++;
                    } catch (ServletException e) {
                        throw e;
                    } catch (Throwable e) {
                        throw new ServletException
                            (sm.getString("standardWrapper.allocate"), e);
                    }
                } else {
                    try {
                        instancePool.wait();
                    } catch (InterruptedException e) {
                        ;
                    }
                }
            }
            if (log.isTraceEnabled())
                log.trace("  Returning allocated STM instance");
            countAllocated.incrementAndGet();
            return (Servlet) instancePool.pop();

        }

    }

    /**
     * Return this previously allocated servlet to the pool of available
     * instances.  If this servlet class does not implement SingleThreadModel,
     * no action is actually required.
     *
     * @param servlet The servlet to be returned
     *
     * @exception ServletException if a deallocation error occurs
     */
    public void deallocate(Servlet servlet) throws ServletException {

        // If not SingleThreadModel, no action is required
        if (!singleThreadModel) {
            countAllocated.decrementAndGet();
            return;
        }

        // Unlock and free this instance
        synchronized (instancePool) {
            countAllocated.decrementAndGet();
            instancePool.push(servlet);
            instancePool.notify();
        }

    }

    /**
     * Return the value for the specified initialization parameter name,
     * if any; otherwise return null.
     *
     * @param name Name of the requested initialization parameter
     */
    public String findInitParameter(String name) {

        try {
            parametersLock.readLock().lock();
            return ((String) parameters.get(name));
        } finally {
            parametersLock.readLock().unlock();
        }

    }

    /**
     * Return the names of all defined initialization parameters for this
     * servlet.
     */
    public String[] findInitParameters() {

        try {
            parametersLock.readLock().lock();
            String results[] = new String[parameters.size()];
            return ((String[]) parameters.keySet().toArray(results));
        } finally {
            parametersLock.readLock().unlock();
        }

    }

    /**
     * Return the mappings associated with this wrapper.
     */
    public String[] findMappings() {

        try {
            mappingsLock.readLock().lock();
            return (String[]) mappings.toArray(new String[mappings.size()]);
        } finally {
            mappingsLock.readLock().unlock();
        }

    }

    /**
     * Return the security role link for the specified security role
     * reference name, if any; otherwise return null.
     *
     * @param name Security role reference used within this servlet
     */
    public String findSecurityReference(String name) {

        try {
            referencesLock.readLock().lock();
            return ((String) references.get(name));
        } finally {
            referencesLock.readLock().unlock();
        }

    }

    /**
     * Return the set of security role reference names associated with
     * this servlet, if any; otherwise return a zero-length array.
     */
    public String[] findSecurityReferences() {

        try {
            referencesLock.readLock().lock();
            String results[] = new String[references.size()];
            return ((String[]) references.keySet().toArray(results));
        } finally {
            referencesLock.readLock().unlock();
        }

    }

    /**
     * FIXME: Fooling introspection ...
     */
    public Wrapper findMappingObject() {
        return (Wrapper) getMappingObject();
    }

    /**
     * Load and initialize an instance of this servlet, if there is not already
     * at least one initialized instance.  This can be used, for example, to
     * load servlets that are marked in the deployment descriptor to be loaded
     * at server startup time.
     *

     * IMPLEMENTATION NOTE:  Servlets whose classnames begin with
     * org.apache.catalina. (so-called "container" servlets)
     * are loaded by the same classloader that loaded this class, rather than
     * the classloader for the current web application.
     * This gives such classes access to Catalina internals, which are
     * prevented for classes loaded for web applications.
     *
     * @exception ServletException if the servlet init() method threw
     *  an exception
     * @exception ServletException if some other loading problem occurs
     */
    public synchronized void load() throws ServletException {
        instance = loadServlet();
    }

    /**
     * Load and initialize an instance of this servlet, if there is not already
     * at least one initialized instance.  This can be used, for example, to
     * load servlets that are marked in the deployment descriptor to be loaded
     * at server startup time.
     */
    public synchronized Servlet loadServlet() throws ServletException {

        // Nothing to do if we already have an instance or an instance pool
        if (!singleThreadModel && (instance != null))
            return instance;

        PrintStream out = System.out;
        if (swallowOutput) {
            SystemLogHandler.startCapture();
        }

        Servlet servlet;
        try {
            long t1=System.currentTimeMillis();
            // If this "servlet" is really a JSP file, get the right class.
            // HOLD YOUR NOSE - this is a kludge that avoids having to do special
            // case Catalina-specific code in Jasper - it also requires that the
            // servlet path be replaced by the <jsp-file> element content in
            // order to be completely effective
            String actualClass = servletClass;
            if ((actualClass == null) && (jspFile != null)) {
                Wrapper jspWrapper = (Wrapper)
                    ((Context) getParent()).findChild(Constants.JSP_SERVLET_NAME);
                if (jspWrapper != null) {
                    actualClass = jspWrapper.getServletClass();
                    // Merge init parameters
                    String paramNames[] = jspWrapper.findInitParameters();
                    for (int i = 0; i < paramNames.length; i++) {
                        if (parameters.get(paramNames[i]) == null) {
                            parameters.put
                                (paramNames[i],
                                 jspWrapper.findInitParameter(paramNames[i]));
                        }
                    }
                }
            }

            // Complain if no servlet class has been specified
            if (actualClass == null) {
                unavailable(null);
                throw new ServletException
                    (sm.getString("standardWrapper.notClass", getName()));
            }

            // Acquire an instance of the class loader to be used
            Loader loader = getLoader();
            if (loader == null) {
                unavailable(null);
                throw new ServletException
                    (sm.getString("standardWrapper.missingLoader", getName()));
            }

            ClassLoader classLoader = loader.getClassLoader();

            // Special case class loader for a container provided servlet
            //
            if (isContainerProvidedServlet(actualClass) &&
                    ! ((Context)getParent()).getPrivileged() ) {
                // If it is a priviledged context - using its own
                // class loader will work, since it's a child of the container
                // loader
                classLoader = this.getClass().getClassLoader();
            }

            // Load the specified servlet class from the appropriate class loader
            Class classClass = null;
            try {
                if (SecurityUtil.isPackageProtectionEnabled()){
                    final ClassLoader fclassLoader = classLoader;
                    final String factualClass = actualClass;
                    try{
                        classClass = (Class)AccessController.doPrivileged(
                                new PrivilegedExceptionAction(){
                                    public Object run() throws Exception{
                                        if (fclassLoader != null) {
                                            return fclassLoader.loadClass(factualClass);
                                        } else {
                                            return Class.forName(factualClass);
                                        }
                                    }
                        });
                    } catch(PrivilegedActionException pax){
                        Exception ex = pax.getException();
                        if (ex instanceof ClassNotFoundException){
                            throw (ClassNotFoundException)ex;
                        } else {
                            getServletContext().log( "Error loading "
                                + fclassLoader + " " + factualClass, ex );
                        }
                    }
                } else {
                    if (classLoader != null) {
                        classClass = classLoader.loadClass(actualClass);
                    } else {
                        classClass = Class.forName(actualClass);
                    }
                }
            } catch (ClassNotFoundException e) {
                unavailable(null);
                getServletContext().log( "Error loading " + classLoader + " " + actualClass, e );
                throw new ServletException
                    (sm.getString("standardWrapper.missingClass", actualClass),
                     e);
            }

            if (classClass == null) {
                unavailable(null);
                throw new ServletException
                    (sm.getString("standardWrapper.missingClass", actualClass));
            }

            // Instantiate and initialize an instance of the servlet class itself
            try {
                servlet = (Servlet) classClass.newInstance();
                // Annotation processing
                if (!((Context) getParent()).getIgnoreAnnotations()) {
                    if (getParent() instanceof StandardContext) {
                       ((StandardContext)getParent()).getAnnotationProcessor().processAnnotations(servlet);
                       ((StandardContext)getParent()).getAnnotationProcessor().postConstruct(servlet);
                    }
                }
            } catch (ClassCastException e) {
                unavailable(null);
                // Restore the context ClassLoader
                throw new ServletException
                    (sm.getString("standardWrapper.notServlet", actualClass), e);
            } catch (Throwable e) {
                unavailable(null);

                // Added extra log statement for Bugzilla 36630:
                // http://bz.apache.org/bugzilla/show_bug.cgi?id=36630
                if(log.isDebugEnabled()) {
                    log.debug(sm.getString("standardWrapper.instantiate", actualClass), e);
                }

                // Restore the context ClassLoader
                throw new ServletException
                    (sm.getString("standardWrapper.instantiate", actualClass), e);
            }

            // Check if loading the servlet in this web application should be
            // allowed
            if (!isServletAllowed(servlet)) {
                throw new SecurityException
                    (sm.getString("standardWrapper.privilegedServlet",
                                  actualClass));
            }

            // Special handling for ContainerServlet instances
            if ((servlet instanceof ContainerServlet) &&
                  (isContainerProvidedServlet(actualClass) ||
                    ((Context)getParent()).getPrivileged() )) {
                ((ContainerServlet) servlet).setWrapper(this);
            }

            classLoadTime=(int) (System.currentTimeMillis() -t1);
            // Call the initialization method of this servlet
            try {
                instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT,
                                                  servlet);

                if( Globals.IS_SECURITY_ENABLED) {
                    boolean success = false;
                    try {
                        Object[] args = new Object[]{ facade };
                        SecurityUtil.doAsPrivilege("init",
                                                   servlet,
                                                   classType,
                                                   args);
                        success = true;
                    } finally {
                        if (!success) {
                            // destroy() will not be called, thus clear the reference now
                            SecurityUtil.remove(servlet);
                        }
                    }
                } else {
                    servlet.init(facade);
                }

                // Invoke jspInit on JSP pages
                if ((loadOnStartup >= 0) && (jspFile != null)) {
                    // Invoking jspInit
                    DummyRequest req = new DummyRequest();
                    req.setServletPath(jspFile);
                    req.setQueryString(Constants.PRECOMPILE + "=true");
                    DummyResponse res = new DummyResponse();

                    if( Globals.IS_SECURITY_ENABLED) {
                        Object[] args = new Object[]{req, res};
                        SecurityUtil.doAsPrivilege("service",
                                                   servlet,
                                                   classTypeUsedInService,
                                                   args);
                        args = null;
                    } else {
                        servlet.service(req, res);
                    }
                }
                instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                                  servlet);
            } catch (UnavailableException f) {
                instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                                  servlet, f);
                unavailable(f);
                throw f;
            } catch (ServletException f) {
                instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                                  servlet, f);
                // If the servlet wanted to be unavailable it would have
                // said so, so do not call unavailable(null).
                throw f;
            } catch (Throwable f) {
                getServletContext().log("StandardWrapper.Throwable", f );
                instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                                  servlet, f);
                // If the servlet wanted to be unavailable it would have
                // said so, so do not call unavailable(null).
                throw new ServletException
                    (sm.getString("standardWrapper.initException", getName()), f);
            }

            // Register our newly initialized instance
            singleThreadModel = servlet instanceof SingleThreadModel;
            if (singleThreadModel) {
                if (instancePool == null)
                    instancePool = new Stack();
            }
            fireContainerEvent("load", this);

            loadTime=System.currentTimeMillis() -t1;
        } finally {
            if (swallowOutput) {
                String log = SystemLogHandler.stopCapture();
                if (log != null && log.length() > 0) {
                    if (getServletContext() != null) {
                        getServletContext().log(log);
                    } else {
                        out.println(log);
                    }
                }
            }
        }
        return servlet;

    }

    /**
     * Remove the specified initialization parameter from this servlet.
     *
     * @param name Name of the initialization parameter to remove
     */
    public void removeInitParameter(String name) {

        try {
            parametersLock.writeLock().lock();
            parameters.remove(name);
        } finally {
            parametersLock.writeLock().unlock();
        }
        fireContainerEvent("removeInitParameter", name);

    }

    /**
     * Remove a listener no longer interested in InstanceEvents.
     *
     * @param listener The listener to remove
     */
    public void removeInstanceListener(InstanceListener listener) {

        instanceSupport.removeInstanceListener(listener);

    }

    /**
     * Remove a mapping associated with the wrapper.
     *
     * @param mapping The pattern to remove
     */
    public void removeMapping(String mapping) {

        try {
            mappingsLock.writeLock().lock();
            mappings.remove(mapping);
        } finally {
            mappingsLock.writeLock().unlock();
        }
        fireContainerEvent("removeMapping", mapping);

    }

    /**
     * Remove any security role reference for the specified role name.
     *
     * @param name Security role used within this servlet to be removed
     */
    public void removeSecurityReference(String name) {

        try {
            referencesLock.writeLock().lock();
            references.remove(name);
        } finally {
            referencesLock.writeLock().unlock();
        }
        fireContainerEvent("removeSecurityReference", name);

    }

    /**
     * Return a String representation of this component.
     */
    public String toString() {

        StringBuffer sb = new StringBuffer();
        if (getParent() != null) {
            sb.append(getParent().toString());
            sb.append(".");
        }
        sb.append("StandardWrapper[");
        sb.append(getName());
        sb.append("]");
        return (sb.toString());

    }

    /**
     * Process an UnavailableException, marking this servlet as unavailable
     * for the specified amount of time.
     *
     * @param unavailable The exception that occurred, or null
     *  to mark this servlet as permanently unavailable
     */
    public void unavailable(UnavailableException unavailable) {
        getServletContext().log(sm.getString("standardWrapper.unavailable", getName()));
        if (unavailable == null)
            setAvailable(Long.MAX_VALUE);
        else if (unavailable.isPermanent())
            setAvailable(Long.MAX_VALUE);
        else {
            int unavailableSeconds = unavailable.getUnavailableSeconds();
            if (unavailableSeconds <= 0)
                unavailableSeconds = 60;        // Arbitrary default
            setAvailable(System.currentTimeMillis() +
                         (unavailableSeconds * 1000L));
        }

    }

    /**
     * Unload all initialized instances of this servlet, after calling the
     * destroy() method for each instance.  This can be used,
     * for example, prior to shutting down the entire servlet engine, or
     * prior to reloading all of the classes from the Loader associated with
     * our Loader's repository.
     *
     * @exception ServletException if an exception is thrown by the
     *  destroy() method
     */
    public synchronized void unload() throws ServletException {

        // Nothing to do if we have never loaded the instance
        if (!singleThreadModel && (instance == null))
            return;
        unloading = true;

        // Loaf a while if the current instance is allocated
        // (possibly more than once if non-STM)
        if (countAllocated.get() > 0) {
            int nRetries = 0;
            long delay = unloadDelay / 20;
            while ((nRetries < 21) && (countAllocated.get() > 0)) {
                if ((nRetries % 10) == 0) {
                    log.info(sm.getString("standardWrapper.waiting",
                                          countAllocated.toString()));
                }
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    ;
                }
                nRetries++;
            }
        }

        PrintStream out = System.out;
        if (swallowOutput) {
            SystemLogHandler.startCapture();
        }

        // Call the servlet destroy() method
        try {
            instanceSupport.fireInstanceEvent
              (InstanceEvent.BEFORE_DESTROY_EVENT, instance);

            if( Globals.IS_SECURITY_ENABLED) {
                try {
                    SecurityUtil.doAsPrivilege("destroy",
                                               instance);
                } finally {
                    SecurityUtil.remove(instance);
                }
            } else {
                instance.destroy();
            }

            instanceSupport.fireInstanceEvent
              (InstanceEvent.AFTER_DESTROY_EVENT, instance);

            // Annotation processing
            if (!((Context) getParent()).getIgnoreAnnotations()) {
               ((StandardContext)getParent()).getAnnotationProcessor().preDestroy(instance);
            }

        } catch (Throwable t) {
            instanceSupport.fireInstanceEvent
              (InstanceEvent.AFTER_DESTROY_EVENT, instance, t);
            instance = null;
            instancePool = null;
            nInstances = 0;
            fireContainerEvent("unload", this);
            unloading = false;
            throw new ServletException
                (sm.getString("standardWrapper.destroyException", getName()),
                 t);
        } finally {
            // Write captured output
            if (swallowOutput) {
                String log = SystemLogHandler.stopCapture();
                if (log != null && log.length() > 0) {
                    if (getServletContext() != null) {
                        getServletContext().log(log);
                    } else {
                        out.println(log);
                    }
                }
            }
        }

        // Deregister the destroyed instance
        instance = null;

        if (singleThreadModel && (instancePool != null)) {
            try {
                while (!instancePool.isEmpty()) {
                    Servlet s = (Servlet) instancePool.pop();
                    if (Globals.IS_SECURITY_ENABLED) {
                        try {
                            SecurityUtil.doAsPrivilege("destroy", s);
                        } finally {
                            SecurityUtil.remove(s);
                        }
                    } else {
                        s.destroy();
                    }
                    // Annotation processing
                    if (!((Context) getParent()).getIgnoreAnnotations()) {
                       ((StandardContext)getParent()).getAnnotationProcessor().preDestroy(s);
                    }
                }
            } catch (Throwable t) {
                instancePool = null;
                nInstances = 0;
                unloading = false;
                fireContainerEvent("unload", this);
                throw new ServletException
                    (sm.getString("standardWrapper.destroyException",
                                  getName()), t);
            }
            instancePool = null;
            nInstances = 0;
        }

        singleThreadModel = false;

        unloading = false;
        fireContainerEvent("unload", this);

    }

    // -------------------------------------------------- ServletConfig Methods

    /**
     * Return the initialization parameter value for the specified name,
     * if any; otherwise return null.
     *
     * @param name Name of the initialization parameter to retrieve
     */
    public String getInitParameter(String name) {

        return (findInitParameter(name));

    }

    /**
     * Return the set of initialization parameter names defined for this
     * servlet.  If none are defined, an empty Enumeration is returned.
     */
    public Enumeration getInitParameterNames() {

        try {
            parametersLock.readLock().lock();
            return (new Enumerator(parameters.keySet()));
        } finally {
            parametersLock.readLock().unlock();
        }

    }

    /**
     * Return the servlet context with which this servlet is associated.
     */
    public ServletContext getServletContext() {

        if (parent == null)
            return (null);
        else if (!(parent instanceof Context))
            return (null);
        else
            return (((Context) parent).getServletContext());

    }

    /**
     * Return the name of this servlet.
     */
    public String getServletName() {

        return (getName());

    }

    public long getProcessingTime() {
        return swValve.getProcessingTime();
    }

    public void setProcessingTime(long processingTime) {
        swValve.setProcessingTime(processingTime);
    }

    public long getMaxTime() {
        return swValve.getMaxTime();
    }

    public void setMaxTime(long maxTime) {
        swValve.setMaxTime(maxTime);
    }

    public long getMinTime() {
        return swValve.getMinTime();
    }

    public void setMinTime(long minTime) {
        swValve.setMinTime(minTime);
    }

    public int getRequestCount() {
        return swValve.getRequestCount();
    }

    public void setRequestCount(int requestCount) {
        swValve.setRequestCount(requestCount);
    }

    public int getErrorCount() {
        return swValve.getErrorCount();
    }

    public void setErrorCount(int errorCount) {
           swValve.setErrorCount(errorCount);
    }

    /**
     * Increment the error count used for monitoring.
     */
    public void incrementErrorCount(){
        swValve.setErrorCount(swValve.getErrorCount() + 1);
    }

    public long getLoadTime() {
        return loadTime;
    }

    public void setLoadTime(long loadTime) {
        this.loadTime = loadTime;
    }

    public int getClassLoadTime() {
        return classLoadTime;
    }

    // -------------------------------------------------------- Package Methods

    // -------------------------------------------------------- protected Methods

    /**
     * Add a default Mapper implementation if none have been configured
     * explicitly.
     *
     * @param mapperClass Java class name of the default Mapper
     */
    protected void addDefaultMapper(String mapperClass) {

        ;       // No need for a default Mapper on a Wrapper

    }

    /**
     * Return true if the specified class name represents a
     * container provided servlet class that should be loaded by the
     * server class loader.
     *
     * @param classname Name of the class to be checked
     */
    protected boolean isContainerProvidedServlet(String classname) {

        if (classname.startsWith("org.apache.catalina.")) {
            return (true);
        }
        try {
            Class clazz =
                this.getClass().getClassLoader().loadClass(classname);
            return (ContainerServlet.class.isAssignableFrom(clazz));
        } catch (Throwable t) {
            return (false);
        }

    }

    /**
     * Return true if loading this servlet is allowed.
     */
    protected boolean isServletAllowed(Object servlet) {

        // Privileged webapps may load all servlets without restriction
        if (((Context) getParent()).getPrivileged()) {
            return true;
        }

        if (servlet instanceof ContainerServlet) {
            return (false);
        }

        Class clazz = servlet.getClass();
        while (clazz != null && !clazz.getName().equals("javax.servlet.http.HttpServlet")) {
            if ("restricted".equals(restrictedServlets.getProperty(clazz.getName()))) {
                return (false);
            }
            clazz = clazz.getSuperclass();
        }

        return (true);

    }

    protected Method[] getAllDeclaredMethods(Class c) {

        if (c.equals(javax.servlet.http.HttpServlet.class)) {
            return null;
        }

        Method[] parentMethods = getAllDeclaredMethods(c.getSuperclass());

        Method[] thisMethods = c.getDeclaredMethods();
        if (thisMethods == null) {
            return parentMethods;
        }

        if ((parentMethods != null) && (parentMethods.length > 0)) {
            Method[] allMethods =
                new Method[parentMethods.length + thisMethods.length];
	    System.arraycopy(parentMethods, 0, allMethods, 0,
                             parentMethods.length);
	    System.arraycopy(thisMethods, 0, allMethods, parentMethods.length,
                             thisMethods.length);

	    thisMethods = allMethods;
	}

	return thisMethods;
    }

    // ------------------------------------------------------ Lifecycle Methods

    /**
     * Start this component, pre-loading the servlet if the load-on-startup
     * value is set appropriately.
     *
     * @exception LifecycleException if a fatal error occurs during startup
     */
    public void start() throws LifecycleException {

        // Send j2ee.state.starting notification
        if (this.getObjectName() != null) {
            Notification notification = new Notification("j2ee.state.starting",
                                                        this.getObjectName(),
                                                        sequenceNumber++);
            broadcaster.sendNotification(notification);
        }

        // Start up this component
        super.start();

        if( oname != null )
            registerJMX((StandardContext)getParent());

        // Load and initialize an instance of this servlet if requested
        // MOVED TO StandardContext START() METHOD

        setAvailable(0L);

        // Send j2ee.state.running notification
        if (this.getObjectName() != null) {
            Notification notification =
                new Notification("j2ee.state.running", this.getObjectName(),
                                sequenceNumber++);
            broadcaster.sendNotification(notification);
        }

    }

    /**
     * Stop this component, gracefully shutting down the servlet if it has
     * been initialized.
     *
     * @exception LifecycleException if a fatal error occurs during shutdown
     */
    public void stop() throws LifecycleException {

        setAvailable(Long.MAX_VALUE);

        // Send j2ee.state.stopping notification
        if (this.getObjectName() != null) {
            Notification notification =
                new Notification("j2ee.state.stopping", this.getObjectName(),
                                sequenceNumber++);
            broadcaster.sendNotification(notification);
        }

        // Shut down our servlet instance (if it has been initialized)
        try {
            unload();
        } catch (ServletException e) {
            getServletContext().log(sm.getString
                      ("standardWrapper.unloadException", getName()), e);
        }

        // Shut down this component
        super.stop();

        // Send j2ee.state.stoppped notification
        if (this.getObjectName() != null) {
            Notification notification =
                new Notification("j2ee.state.stopped", this.getObjectName(),
                                sequenceNumber++);
            broadcaster.sendNotification(notification);
        }

        if( oname != null ) {
            Registry.getRegistry(null, null).unregisterComponent(oname);

            // Send j2ee.object.deleted notification
            Notification notification =
                new Notification("j2ee.object.deleted", this.getObjectName(),
                                sequenceNumber++);
            broadcaster.sendNotification(notification);
        }

        if (isJspServlet && jspMonitorON != null ) {
            Registry.getRegistry(null, null).unregisterComponent(jspMonitorON);
        }

    }

    protected void registerJMX(StandardContext ctx) {

        String parentName = ctx.getName();
        parentName = ("".equals(parentName)) ? "/" : parentName;

        String hostName = ctx.getParent().getName();
        hostName = (hostName==null) ? "DEFAULT" : hostName;

        String domain = ctx.getDomain();

        String webMod= "//" + hostName + parentName;
        String onameStr = domain + ":j2eeType=Servlet,name=" + getName() +
                          ",WebModule=" + webMod + ",J2EEApplication=" +
                          ctx.getJ2EEApplication() + ",J2EEServer=" +
                          ctx.getJ2EEServer();
        try {
            oname=new ObjectName(onameStr);
            controller=oname;
            Registry.getRegistry(null, null)
                .registerComponent(this, oname, null );

            // Send j2ee.object.created notification
            if (this.getObjectName() != null) {
                Notification notification = new Notification(
                                                "j2ee.object.created",
                                                this.getObjectName(),
                                                sequenceNumber++);
                broadcaster.sendNotification(notification);
            }
        } catch( Exception ex ) {
            log.info("Error registering servlet with jmx " + this, ex);
        }

        if (isJspServlet) {
            // Register JSP monitoring mbean
            onameStr = domain + ":type=JspMonitor,name=" + getName()
                       + ",WebModule=" + webMod
                       + ",J2EEApplication=" + ctx.getJ2EEApplication()
                       + ",J2EEServer=" + ctx.getJ2EEServer();
            try {
                jspMonitorON = new ObjectName(onameStr);
                Registry.getRegistry(null, null)
                    .registerComponent(instance, jspMonitorON, null);
            } catch( Exception ex ) {
                log.info("Error registering JSP monitoring with jmx " +
                         instance, ex);
            }
        }
    }

    /* Remove a JMX notficationListener
     * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
     */
    public void removeNotificationListener(NotificationListener listener,
    		NotificationFilter filter, Object object) throws ListenerNotFoundException {
    	broadcaster.removeNotificationListener(listener,filter,object);

    }

    protected MBeanNotificationInfo[] notificationInfo;

    /* Get JMX Broadcaster Info
     * @TODO use StringManager for international support!
     * @TODO This two events we not send j2ee.state.failed and j2ee.attribute.changed!
     * @see javax.management.NotificationBroadcaster#getNotificationInfo()
     */
    public MBeanNotificationInfo[] getNotificationInfo() {

    	if(notificationInfo == null) {
    		notificationInfo = new MBeanNotificationInfo[]{
    				new MBeanNotificationInfo(new String[] {
    				"j2ee.object.created"},
					Notification.class.getName(),
					"servlet is created"
    				),
					new MBeanNotificationInfo(new String[] {
					"j2ee.state.starting"},
					Notification.class.getName(),
					"servlet is starting"
					),
					new MBeanNotificationInfo(new String[] {
					"j2ee.state.running"},
					Notification.class.getName(),
					"servlet is running"
					),
					new MBeanNotificationInfo(new String[] {
					"j2ee.state.stopped"},
					Notification.class.getName(),
					"servlet start to stopped"
					),
					new MBeanNotificationInfo(new String[] {
					"j2ee.object.stopped"},
					Notification.class.getName(),
					"servlet is stopped"
					),
					new MBeanNotificationInfo(new String[] {
					"j2ee.object.deleted"},
					Notification.class.getName(),
					"servlet is deleted"
					)
    		};

    	}

    	return notificationInfo;
    }

    /* Add a JMX-NotificationListener
     * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)
     */
    public void addNotificationListener(NotificationListener listener,
            NotificationFilter filter, Object object) throws IllegalArgumentException {
    	broadcaster.addNotificationListener(listener,filter,object);
    }

    /**
     * Remove a JMX-NotificationListener
     * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
     */
    public void removeNotificationListener(NotificationListener listener)
        throws ListenerNotFoundException {
    	broadcaster.removeNotificationListener(listener);
    }

     // ------------------------------------------------------------- Attributes

    public boolean isEventProvider() {
        return false;
    }

    public boolean isStateManageable() {
        return false;
    }

    public boolean isStatisticsProvider() {
        return false;
    }

}


text:
module Transit

  class LocationIdNotFoundError < Exception
  end

  class LocationIdNotParsableError < Exception
  end

end


text:
/**
 *
 * @author levisjani
 */

public class Demo {
   public static void main(String[] args) {
      Originator originator = new Originator();
      CareTaker careTaker = new CareTaker();
      originator.setState("State #1");
      originator.setState("State #2");
      careTaker.add(originator.saveStateToMemento());
      originator.setState("State #3");
      careTaker.add(originator.saveStateToMemento());
      originator.setState("State #4");

      System.out.println("Current State from originator: " + originator.getState());
      originator.getStateFromMemento(careTaker.get());
      System.out.println("First saved State: " + originator.getState());
      originator.getStateFromMemento(careTaker.get());
      System.out.println("Second saved State: " + originator.getState());
      /* originator.getStateFromMemento(careTaker.get(2));
      System.out.println("Third saved State: " + originator.getState());
      */
   }
}


text:
#ifndef __USB_ENDPOINT_H__
#define __USB_ENDPOINT_H__

#include <usb_type.h>
#include <usb_queue.h>

extern usb_endpoint_t usb_endpoint_control_out;
extern USB_DECLARE_QUEUE(usb_endpoint_control_out);

extern usb_endpoint_t usb_endpoint_control_in;
extern USB_DECLARE_QUEUE(usb_endpoint_control_in);

extern usb_endpoint_t usb_endpoint_bulk_in;
extern USB_DECLARE_QUEUE(usb_endpoint_bulk_in);

extern usb_endpoint_t usb_endpoint_bulk_out;
extern USB_DECLARE_QUEUE(usb_endpoint_bulk_out);

#endif /* end of include guard: __USB_ENDPOINT_H__ */


text:
'use strict';

// ==============================
// CONNECTIONS
// ==============================

// VGA has its own interface which handles images only through an analog signal
var vga = {
    name: "VGA",
    data: "images",
    signal: "analog",
    handleAnalogSignal: function () {
        return "Interface: " + this.name + "\nData: " + this.data + "\nSignal: " + this.signal;
    }
};

// But your computer uses HDMI as output and your projector uses VGA as input...
// Here you need an adapter if you want to display images.
module.exports = {
    vga: vga,
    handleDigitalSignal: function () {
        return this.vga.handleAnalogSignal();
    }
};