Java Code Examples for javax.servlet.http.HttpServlet

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project guice-jit-providers, under directory /extensions/servlet/src/com/google/inject/servlet/.

Source file: ServletDefinition.java

  18 
vote

public void destroy(Set<HttpServlet> destroyedSoFar){
  HttpServlet reference=httpServlet.get();
  if (null == reference || destroyedSoFar.contains(reference)) {
    return;
  }
  try {
    reference.destroy();
  }
  finally {
    destroyedSoFar.add(reference);
  }
}
 

Example 2

From project sisu-guice, under directory /extensions/servlet/src/com/google/inject/servlet/.

Source file: ServletDefinition.java

  18 
vote

public void destroy(Set<HttpServlet> destroyedSoFar){
  HttpServlet reference=httpServlet.get();
  if (null == reference || destroyedSoFar.contains(reference)) {
    return;
  }
  try {
    reference.destroy();
  }
  finally {
    destroyedSoFar.add(reference);
  }
}
 

Example 3

From project jbosgi, under directory /testsuite/example/src/test/java/org/jboss/test/osgi/example/interceptor/bundle/.

Source file: PublisherInterceptor.java

  17 
vote

public void invoke(int state,InvocationContext context){
  HttpMetadata metadata=context.getAttachment(HttpMetadata.class);
  if (state == Bundle.STARTING) {
    String servletName=metadata.getServletName();
    try {
      log.info("Publish HttpMetadata: " + metadata);
      Bundle bundle=context.getBundle();
      Class<?> servletClass=bundle.loadClass(servletName);
      HttpServlet servlet=(HttpServlet)servletClass.newInstance();
      ClassLoader ctxLoader=Thread.currentThread().getContextClassLoader();
      try {
        HttpService httpService=getHttpService(context,true);
        httpService.registerServlet("/example-interceptor/servlet",servlet,null,null);
      }
  finally {
        Thread.currentThread().setContextClassLoader(ctxLoader);
      }
    }
 catch (    RuntimeException rte) {
      throw rte;
    }
catch (    Exception ex) {
      throw new LifecycleInterceptorException("Cannot publish: " + servletName,ex);
    }
  }
 else   if (state == Bundle.STOPPING) {
    log.info("Unpublish HttpMetadata: " + metadata);
    ClassLoader ctxLoader=Thread.currentThread().getContextClassLoader();
    try {
      HttpService httpService=getHttpService(context,false);
      if (httpService != null)       httpService.unregister("/example-interceptor/servlet");
    }
  finally {
      Thread.currentThread().setContextClassLoader(ctxLoader);
    }
  }
}
 

Example 4

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/server/.

Source file: SPARQLServer.java

  17 
vote

private void configureOneDataset(ServletContextHandler context,DatasetRef sDesc,boolean enableCompression){
  String datasetPath=sDesc.name;
  if (datasetPath.equals("/"))   datasetPath="";
 else   if (!datasetPath.startsWith("/"))   datasetPath="/" + datasetPath;
  if (datasetPath.endsWith("/"))   datasetPath=datasetPath.substring(0,datasetPath.length() - 1);
  DatasetRegistry.get().put(datasetPath,sDesc);
  serverLog.info(format("Dataset path = %s",datasetPath));
  HttpServlet sparqlQuery=new SPARQL_QueryDataset(verbose);
  HttpServlet sparqlUpdate=new SPARQL_Update(verbose);
  HttpServlet sparqlUpload=new SPARQL_Upload(verbose);
  HttpServlet sparqlHttpR=new SPARQL_REST_R(verbose);
  HttpServlet sparqlHttpRW=new SPARQL_REST_RW(verbose);
  addServlet(context,datasetPath,sparqlQuery,sDesc.queryEP,enableCompression);
  addServlet(context,datasetPath,sparqlUpdate,sDesc.updateEP,false);
  addServlet(context,datasetPath,sparqlUpload,sDesc.uploadEP,false);
  addServlet(context,datasetPath,sparqlHttpR,sDesc.readGraphStoreEP,enableCompression);
  addServlet(context,datasetPath,sparqlHttpRW,sDesc.readWriteGraphStoreEP,enableCompression);
}
 

Example 5

From project moho, under directory /moho-impl/src/main/java/com/voxeo/moho/imified/.

Source file: IMifiedDriver.java

  17 
vote

@Override public void init(SpiFramework framework){
  _appEventSource=framework;
  HttpServlet servlet=framework.getHTTPController();
  if (servlet.getServletConfig().getInitParameter("imifiedApiURL") != null) {
    _imifiedApiURL=servlet.getServletConfig().getInitParameter("imifiedApiURL");
  }
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,20);
  ConnPerRouteBean connPerRoute=new ConnPerRouteBean(20);
  ConnManagerParams.setMaxConnectionsPerRoute(params,connPerRoute);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager cm=new ThreadSafeClientConnManager(params,schemeRegistry);
  _httpClient=new DefaultHttpClient(cm,params);
  _httpClient.setReuseStrategy(new DefaultConnectionReuseStrategy());
  _httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy(){
    public long getKeepAliveDuration(    HttpResponse response,    HttpContext context){
      HeaderElementIterator it=new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
      while (it.hasNext()) {
        HeaderElement he=it.nextElement();
        String param=he.getName();
        String value=he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
          try {
            return Long.parseLong(value) * 1000;
          }
 catch (          NumberFormatException ex) {
          }
        }
      }
      return -1;
    }
  }
);
}
 

Example 6

From project org.ops4j.pax.vaadin, under directory /pax-vaadin-service/src/main/java/org/ops4j/pax/vaadin/internal/.

Source file: Activator.java

  17 
vote

private void createAndRegisterVaadinResourceServlet(){
  Bundle vaadin=null;
  for (  Bundle bundle : bundleContext.getBundles()) {
    if ("com.vaadin".equals(bundle.getSymbolicName())) {
      vaadin=bundle;
      break;
    }
  }
  Dictionary<String,String> props;
  props=new Hashtable<String,String>();
  props.put("alias",VaadinResourceServlet._VAADIN);
  HttpServlet vaadinResourceServlet=new VaadinResourceServlet(vaadin);
  resourceService=bundleContext.registerService(Servlet.class.getName(),vaadinResourceServlet,props);
  bundleContext.registerService(VaadinResourceService.class.getName(),vaadinResourceServlet,null);
}
 

Example 7

From project Pitbull, under directory /pitbull-servlet/src/main/java/org/jboss/pitbull/servlet/internal/.

Source file: ServletRequestHandler.java

  17 
vote

@Override public void execute(Connection connection,RequestHeader requestHeader,InputStream input,StreamedResponse writer) throws IOException {
  HttpServletRequestImpl request=new HttpServletRequestImpl();
  request.setConnection(connection);
  request.setHeaderBlob(requestHeader);
  request.setIs(input);
  request.setContext(context);
  HttpServletResponseImpl response=new HttpServletResponseImpl(writer);
  try {
    HttpServlet instance=(HttpServlet)servlet.startRequest();
    try {
      instance.service(request,response);
    }
  finally {
      servlet.endRequest();
    }
  }
 catch (  IOException e) {
    throw e;
  }
catch (  RuntimeException e) {
    throw e;
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 8

From project annotare2, under directory /app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/.

Source file: AppServletModule.java

  15 
vote

private void serveAndBindRpcService(String serviceName,Class<? extends HttpServlet> implClass,String... moduleNames){
  for (  String moduleName : moduleNames) {
    String servicePath="/" + moduleName + "/"+ serviceName;
    serve(servicePath).with(implClass);
    allRpc.awareOf(servicePath);
  }
  bind(implClass).in(Scopes.SINGLETON);
}
 

Example 9

From project aws-tvm-anonymous, under directory /src/com/amazonaws/tvm/.

Source file: RootServlet.java

  15 
vote

protected String getServletParameter(HttpServlet servlet,String parameterName){
  String parameterValue=servlet.getInitParameter(parameterName);
  if (parameterValue == null) {
    parameterValue=servlet.getServletContext().getInitParameter(parameterName);
  }
  return parameterValue;
}
 

Example 10

From project aws-tvm-identity, under directory /src/com/amazonaws/tvm/.

Source file: RootServlet.java

  15 
vote

protected String getServletParameter(HttpServlet servlet,String parameterName){
  String parameterValue=servlet.getInitParameter(parameterName);
  if (parameterValue == null) {
    parameterValue=servlet.getServletContext().getInitParameter(parameterName);
  }
  return parameterValue;
}
 

Example 11

From project echo2, under directory /src/testapp/interactive/eclipse/.

Source file: TestAppRun.java

  15 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      try {
        testContext.getSessionHandler().stop();
        System.out.println("Shutdown request received: terminating.");
        System.exit(0);
      }
 catch (      Exception ex) {
        ex.printStackTrace();
      }
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 12

From project echo3, under directory /src/server-java/testapp-interactive/eclipse/.

Source file: TestAppRun.java

  15 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  final Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      try {
        testContext.getSessionHandler().stop();
        System.out.println("Shutdown request received: terminating.");
        System.exit(0);
      }
 catch (      Exception ex) {
        ex.printStackTrace();
      }
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 13

From project echo3extras, under directory /src/server-java/testapp-interactive/eclipse/.

Source file: TestAppRun.java

  15 
vote

public static void main(String[] arguments) throws Exception {
  try {
    URL url=new URL("http://localhost:" + PORT + "/__SHUTDOWN__/");
    URLConnection conn=url.openConnection();
    InputStream in=conn.getInputStream();
    in.close();
  }
 catch (  ConnectException ex) {
  }
  Server server=new Server(PORT);
  Context testContext=new Context(server,CONTEXT_PATH,Context.SESSIONS);
  testContext.addServlet(new ServletHolder(SERVLET_CLASS),PATH_SPEC);
  Context shutdownContext=new Context(server,"/__SHUTDOWN__");
  shutdownContext.addServlet(new ServletHolder(new HttpServlet(){
    private static final long serialVersionUID=1L;
    protected void service(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      System.out.println("Shutdown request received: terminating.");
      System.exit(0);
    }
  }
),"/");
  System.out.println("Deploying " + SERVLET_CLASS.getName() + " on http://localhost:"+ PORT+ CONTEXT_PATH+ PATH_SPEC);
  server.start();
  server.join();
}
 

Example 14

From project Flume-Hive, under directory /src/java/com/cloudera/util/.

Source file: StatusHttpServer.java

  15 
vote

/** 
 * Add a servlet in the server.
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param servletClass The servlet class
 */
public <T extends HttpServlet>void addServlet(String name,String pathSpec,Class<T> servletClass){
  WebAppContext context=webAppContext;
  if (name == null) {
    context.addServlet(pathSpec,servletClass.getName());
  }
 else {
    context.addServlet(servletClass,pathSpec);
  }
}
 

Example 15

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/util/.

Source file: StatusHttpServer.java

  15 
vote

/** 
 * Add a servlet in the server.
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param servletClass The servlet class
 */
public <T extends HttpServlet>void addServlet(String name,String pathSpec,Class<T> servletClass){
  WebAppContext context=webAppContext;
  if (name == null) {
    context.addServlet(pathSpec,servletClass.getName());
  }
 else {
    context.addServlet(servletClass,pathSpec);
  }
}
 

Example 16

From project guice-automatic-injection, under directory /integrations/enterprise/src/main/java/de/devsurf/injection/guice/enterprise/features/.

Source file: WebServletBindingFeature.java

  15 
vote

@Override public void process(final Class<Object> annotatedClass,final Map<String,Annotation> annotations){
  final WebServlet annotation=(WebServlet)annotations.get(WebServlet.class.getName());
  String[] patterns=annotation.value();
  final String value;
  final String[] values;
  if (patterns.length > 0) {
    final PropertiesResolver resolver=new PropertiesResolver(patterns[0]);
    resolver.setInjector(injector);
    value=resolver.get();
    if (patterns.length > 1) {
      values=new String[patterns.length - 1];
      for (int i=1; i < patterns.length; i++) {
        final PropertiesResolver patternResolver=new PropertiesResolver(patterns[i]);
        patternResolver.setInjector(injector);
        values[i - 1]=patternResolver.get();
      }
    }
 else {
      values=null;
    }
  }
 else {
    LOGGER.info("Ignoring Servlet \"" + annotatedClass + "\", because no Values for URLs were specified.");
    return;
  }
  _binder.install(new ServletModule(){
    @Override protected void configureServlets(){
      serve(value).with(annotatedClass.asSubclass(HttpServlet.class));
    }
  }
);
}
 

Example 17

From project hama, under directory /core/src/main/java/org/apache/hama/http/.

Source file: HttpServer.java

  15 
vote

/** 
 * Add an internal servlet in the server.
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 * @deprecated this is a temporary method
 */
@Deprecated public void addInternalServlet(String name,String pathSpec,Class<? extends HttpServlet> clazz){
  ServletHolder holder=new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  webAppContext.addServlet(holder,pathSpec);
}
 

Example 18

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  15 
vote

SimpleRequestDispatcher(String path){
  PathTreeDictionary registry=(PathTreeDictionary)currentRegistry.get();
  if (registry == null)   registry=defaultRegistry;
  Object[] os=registry.get(path);
  servlet=(HttpServlet)os[0];
  if (servlet == null)   throw new NullPointerException();
  dispatchLen=((Integer)os[1]).intValue();
  int qmp=path.indexOf('?');
  if (qmp < 0 || qmp >= path.length() - 1)   dispatchPath=path;
 else {
    dispatchPath=path.substring(0,qmp);
    dispatchQuery=path.substring(qmp + 1);
  }
}
 

Example 19

From project java-maven-tests, under directory /src/spring31-mvc-demo/src/main/java/com/alexshabanov/spr31/controller/.

Source file: HelloController.java

  15 
vote

@RequestMapping("/index.html") public String index(Model model,HttpSession session,HttpServlet servlet){
  final Hello hello=helloService.getGreeting("index.html");
  model.addAttribute(hello);
  LOG.info("Hello object = {}, sessionId = {}",hello,session.getId());
  return "hello";
}
 

Example 20

From project jetty-project, under directory /jetty-remote-testsuite/jetty-remote-testsuite-servlet/src/main/java/org/mortbay/jetty/test/remote/.

Source file: ServletRequestContext.java

  15 
vote

public ServletRequestContext(HttpServlet servlet,HttpServletRequest request,HttpServletResponse response){
  super();
  this.servlet=servlet;
  this.request=request;
  this.response=response;
}
 

Example 21

From project lime-mvc, under directory /extensions/freemarker/src/org/zdevra/guice/mvc/freemarker/.

Source file: FreemarkerViewPoint.java

  15 
vote

@SuppressWarnings("unchecked") @Override public void render(ModelMap model,HttpServlet servlet,HttpServletRequest request,HttpServletResponse response){
  try {
    List<String> attrNames=Collections.list(request.getAttributeNames());
    Map<String,Object> data=new HashMap<String,Object>();
    for (    String attrName : attrNames) {
      Object attr=request.getAttribute(attrName);
      data.put(attrName,attr);
    }
    Template template=freemarkerConf.getTemplate(templateFile);
    ByteArrayOutputStream bout=new ByteArrayOutputStream(2048);
    Writer out=new OutputStreamWriter(new BufferedOutputStream(bout));
    template.process(data,out);
    out.flush();
    response.getWriter().write(bout.toString());
  }
 catch (  TemplateException e) {
    throw new FreemarkerViewException(templateFile,request,e);
  }
catch (  IOException e) {
    throw new FreemarkerViewException(templateFile,request,e);
  }
}
 

Example 22

From project maven-deployit-plugin, under directory /spring-petclinic/src/main/java/com/xebialabs/servlets/.

Source file: StaticContentServlet.java

  15 
vote

private synchronized HttpServlet getServletImplementation(){
  if (fileServlet != null)   return fileServlet;
  try {
    System.out.println("Load \"weblogic.servlet.FileServlet\"");
    fileServlet=(HttpServlet)this.getClass().getClassLoader().loadClass("weblogic.servlet.FileServlet").newInstance();
    fileServlet.init(this.getServletConfig());
    return fileServlet;
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
catch (  ServletException e) {
    e.printStackTrace();
  }
  try {
    System.out.println("Load \"org.apache.catalina.servlets.DefaultServlet\"");
    fileServlet=(HttpServlet)this.getClass().getClassLoader().loadClass("org.apache.catalina.servlets.DefaultServlet").newInstance();
    fileServlet.init(this.getServletConfig());
    return fileServlet;
  }
 catch (  InstantiationException e) {
    e.printStackTrace();
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
catch (  ServletException e) {
    e.printStackTrace();
  }
  throw new RuntimeException("Cannot find out a servlet implementation....");
}
 

Example 23

From project ning-service-skeleton, under directory /base/src/main/java/com/ning/jetty/base/modules/.

Source file: BaseServerModule.java

  15 
vote

public BaseServerModule(final Map<Class,Object> bindings,final ConfigSource configSource,final List<Class> configs,final List<Class<? extends HealthCheck>> healthchecks,final List<Class> beans,final String areciboProfile,final boolean trackRequests,final boolean log4jEnabled,final String jaxRSUriPattern,final List<String> jaxRSResources,final List<Module> modules,final Map<String,ArrayList<Map.Entry<Class<? extends Filter>,Map<String,String>>>> filters,final Map<String,ArrayList<Map.Entry<Class<? extends Filter>,Map<String,String>>>> filtersRegex,final Map<String,Class<? extends HttpServlet>> jaxRSServlets,final Map<String,Class<? extends HttpServlet>> jaxRSServletsRegex,final Map<String,Class<? extends HttpServlet>> servlets,final Map<String,Class<? extends HttpServlet>> servletsRegex){
  this.bindings.putAll(bindings);
  this.configSource=configSource;
  this.configs.addAll(configs);
  this.healthchecks.addAll(healthchecks);
  this.beans.addAll(beans);
  this.areciboProfile=areciboProfile;
  this.log4jEnabled=log4jEnabled;
  this.trackRequests=trackRequests;
  this.jaxRSUriPattern=jaxRSUriPattern;
  this.jaxRSResources.addAll(jaxRSResources);
  this.modules.addAll(modules);
  this.filters=filters;
  this.filtersRegex=filtersRegex;
  this.jaxRSServlets=jaxRSServlets;
  this.jaxRSServletsRegex=jaxRSServletsRegex;
  this.servlets=servlets;
  this.servletsRegex=servletsRegex;
  this.configs.add(DaoConfig.class);
  this.configs.add(TrackerConfig.class);
}
 

Example 24

From project nuxeo-webengine, under directory /nuxeo-webengine-jaxrs/src/main/java/org/nuxeo/ecm/webengine/jaxrs/servlet/.

Source file: RequestChain.java

  15 
vote

/** 
 * Create a new request chain given the target servlet and an optional list of filter sets.
 * @param servlet the target
 * @param filters the filter sets
 */
public RequestChain(HttpServlet servlet,FilterSet[] filters){
  if (servlet == null) {
    throw new IllegalArgumentException("No target servlet defined");
  }
  this.filters=filters == null ? new FilterSet[0] : filters;
  this.servlet=servlet;
}
 

Example 25

From project sauce-ondemand-plugin, under directory /src/test/java/hudson/plugins/sauce_ondemand/.

Source file: BaseTezt.java

  15 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  server=new Server(8080);
  File sauceSettings=new File(new File(System.getProperty("user.home")),".sauce-ondemand");
  if (!sauceSettings.exists()) {
    String userName=System.getProperty("sauce.user");
    String accessKey=System.getProperty("access.key");
    Credential credential=new Credential(userName,accessKey);
    credential.saveTo(sauceSettings);
  }
  ServletHandler handler=new ServletHandler();
  handler.addServletWithMapping(new ServletHolder(new HttpServlet(){
    @Override protected void doGet(    HttpServletRequest req,    HttpServletResponse resp) throws ServletException, IOException {
      resp.setContentType("text/html");
      resp.getWriter().println("<html><head><title>test" + secret + "</title></head><body>it works</body></html>");
    }
  }
),"/");
  server.setHandler(handler);
  SocketConnector connector=new SocketConnector();
  server.addConnector(connector);
  server.start();
  jettyLocalPort=connector.getLocalPort();
  System.out.println("Started Jetty at " + jettyLocalPort);
}