Java Code Examples for javax.servlet.ServletException

The following are top voted examples for showing how to use javax.servlet.ServletException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: lutece-core   File: DosGuardFilter.java View source code Vote up 7 votes
/**
 * [email protected]}
 */
@Override
public void init( FilterConfig config ) throws ServletException
{
    _filterConfig = config;
    _mapLastRequestTimes = new HashMap<String, Long>( INITIAL_CAPACITY );
    _listOrderedRequests = new LinkedList<Entry>(  );

    try
    {
        String paramValue = _filterConfig.getInitParameter( "minContentLength" );

        if ( paramValue != null )
        {
            _nMinContentLength = Integer.parseInt( paramValue );
        }

        paramValue = _filterConfig.getInitParameter( "minInterval" );

        if ( paramValue != null )
        {
            _nMinInterval = Integer.parseInt( paramValue );
        }
    }
    catch ( NumberFormatException ex )
    {
        ServletException servletEx = new ServletException( ex.getMessage(  ) );
        servletEx.initCause( ex );
        throw servletEx;
    }
}
 
Example 2
Project: spacewalk   File: RhnRequestProcessor.java View source code Vote up 7 votes
private void fixCause(ServletException e) {
    // ServletException has a rootCause that is separate from
    // Throwable.cause. Try and set Throwable.cause to ServletException.rootCause
    // for the chain of exceptions starting with e.rootCause
    do {
        Throwable cause = e.getRootCause();
        if (cause != null && e.getCause() == null) {
            e.initCause(cause);
        }
        if (cause instanceof ServletException) {
            e = (ServletException) cause;
        }
        else {
            e = null;
        }
    } while (e != null);
}
 
Example 3
Project: syncope   File: DefaultRolesPrefixPostProcessor.java View source code Vote up 7 votes
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) {
    if (bean instanceof DefaultMethodSecurityExpressionHandler) {
        ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
    }
    if (bean instanceof DefaultWebSecurityExpressionHandler) {
        ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null);
    }
    if (bean instanceof SecurityContextHolderAwareRequestFilter) {
        SecurityContextHolderAwareRequestFilter filter = (SecurityContextHolderAwareRequestFilter) bean;
        filter.setRolePrefix(StringUtils.EMPTY);
        try {
            filter.afterPropertiesSet();
        } catch (ServletException e) {
            throw new FatalBeanException(e.getMessage(), e);
        }
    }

    return bean;
}
 
Example 4
Project: android-servlet-container   File: WebAppConfiguration.java View source code Vote up 7 votes
/**
 * Build a dispatcher to the error handler if it's available. If it fails,
 * return null.
 */
private RequestDispatcher buildErrorDispatcher(String errorURI, int statusCode, String summaryMessage, Throwable exception) {
    // Parse the url for query string, etc
    String queryString = "";
    int questionPos = errorURI.indexOf('?');
    if (questionPos != -1) {
        if (questionPos != errorURI.length() - 1) {
            queryString = errorURI.substring(questionPos + 1);
        }
        errorURI = errorURI.substring(0, questionPos);
    }

    // Get the message by recursing if none supplied
    ServletException errIterator = new ServletException(exception);
    while ((summaryMessage == null) && (errIterator != null)) {
        summaryMessage = errIterator.getMessage();
        if (errIterator.getRootCause() instanceof ServletException) {
            errIterator = (ServletException) errIterator.getRootCause();
        } else {
            if (summaryMessage == null) {
                summaryMessage = errIterator.getRootCause().getMessage();
            }
            errIterator = null;
        }
    }

    // Return the dispatcher
    StringBuffer servletPath = new StringBuffer();
    StringBuffer pathInfo = new StringBuffer();
    ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo);
    if (servlet != null) {
        RequestDispatcher rd = new RequestDispatcher(this, servlet);
        if (rd != null) {
            rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, statusCode,
                    summaryMessage, exception, errorURI, this.filterPatternsError);
            return rd;
        }
    }
    return null;
}
 
Example 5
Project: moho   File: MockSipServlet.java View source code Vote up 6 votes
public MockSipServlet(Mockery mockery) {
  _mockery = mockery;
  _ctx = new MockServletContext();
  _ctx.setAttribute(SIP_FACTORY, _mockery.mock(SipFactory.class));
  _ctx.setAttribute("javax.servlet.sdp.SdpFactory", _mockery.mock(SdpFactory.class));
  try {
    init(new MockServletConfig(_ctx));
  }
  catch (ServletException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}
 
Example 6
Project: java-webapp-security-examples   File: JavaEELoginService.java View source code Vote up 6 votes
@Override
public LoginStatus login(String username, String password) {
    try {
        if (request.getRemoteUser() == null) {
            request.login(username, password);
            log.debug("Login succeeded!");
        }
        return new LoginStatus(true, request.getRemoteUser());
    } catch (ServletException e) {
        e.printStackTrace();
        return new LoginStatus(false, null);
    }
}
 
Example 7
Project: TrianaCloud   File: BrokerServletContextListener.java View source code Vote up 6 votes
public void contextInitialized(ServletContextEvent event) {
    ServletContext sc = event.getServletContext();

    String host = sc.getInitParameter("rabbitmq.host");
    int port = Integer.parseInt(sc.getInitParameter("rabbitmq.port"));
    String user = sc.getInitParameter("rabbitmq.user");
    String pass = sc.getInitParameter("rabbitmq.pass");
    String rpc_queue_name = sc.getInitParameter("rabbitmq.rpc_queue_name");
    String vHost = sc.getInitParameter("rabbitmq.vhost");

    ConcurrentHashMap<String, Task> taskMap = new ConcurrentHashMap<String, Task>();
    ConcurrentHashMap<String, Task> resultMap = new ConcurrentHashMap<String, Task>();

    receiver = new Receiver(host, port, user, pass, vHost);
    rpcServer = new RPCServer(host, port, user, pass, vHost, rpc_queue_name);

    String replyQueue = receiver.init();
    try {
        rpcServer.init();
    } catch (ServletException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    receiverThread = new Thread(receiver);
    receiverThread.start();

    rpcServerThread = new Thread(rpcServer);
    rpcServerThread.start();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);
    factory.setUsername(user);
    factory.setPassword(pass);

    sc.setAttribute("RabbitMQConnectionFactory", factory);
    sc.setAttribute("taskmap", taskMap);
    sc.setAttribute("replyQueue", replyQueue);
    sc.setAttribute("resultMap", resultMap);
    sc.setAttribute("rpc_queue_name", rpc_queue_name);
}
 
Example 8
Project: solmix   File: ServletManagerTracker.java View source code Vote up 6 votes
/**
 * @param reference
 */
private synchronized Servlet createServlet(ServiceReference<Servlet> reference) {
    Servlet servlet = context.getService(reference);
    String name = (String) reference.getProperty(SERVLET_NAME);
    String pattern = (String) reference.getProperty(SERVLET_PATTERN);
    if (servlet == null)
        return null;
    if (name == null && pattern == null) {
        return null;
    }
    if (name != null && pattern == null)
        throw new IllegalArgumentException("A registed-Servlet must register with a property named <" + SERVLET_PATTERN + ">");
    try {
        ServletHandler handler = new ServletHandler(this.servletContext, servlet, reference, pattern);
        checkInsert(handler);
        handler.init();
    } catch (ServletException e) {
        e.printStackTrace();
    }
    return servlet;
}
 
Example 9
Project: hbs4ode   File: Axis2TestBase.java View source code Vote up 6 votes
protected void start() throws AxisFault {
    super.start();
    _ode = new ODEServer();
    try {
        _ode.init(webappPath+"/WEB-INF", configContext.getAxisConfiguration());
    } catch (ServletException e) {
        e.printStackTrace();
    }
}
 
Example 10
Project: remote   File: SoapExportServlet.java View source code Vote up 6 votes
@Override
 public void loadBus(ServletConfig config) /*throws ServletException*/ {
   super.loadBus(config);

   ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
   try {
     Thread.currentThread().setContextClassLoader(service.getClass().getClassLoader());
     
     Bus bus = getBus();
     setExtensions(bus);
     
     BusFactory.setDefaultBus(bus);
     bus.getInInterceptors().add(new InInterceptor());
     
     bus.getOutInterceptors().add(new OutInterceptor()); 
      
     SoapBindingFactory soapFactory = new SoapBindingFactory();
     soapFactory.setBus(bus);
     
     BindingFactoryManager mgr = bus.getExtension(BindingFactoryManager.class);
     mgr.registerBindingFactory(SoapBindingFactory.SOAP_11_BINDING, soapFactory);
     
     createServer(bus);
     
   } catch (BusException ex) {
     Activator.log("CXF Bus Exception", ex);
     try {
	throw new ServletException(ex);
} catch (ServletException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
   } finally {
     Thread.currentThread().setContextClassLoader(oldClassLoader);
   }
 }
 
Example 11
Project: GWAP   File: DBConnection.java View source code Vote up 6 votes
public static Connection getConnection()
{
	try{
	    return DriverManager.getConnection(connString,username,password);
	}
	catch (Exception e) {
		e.printStackTrace();
		try {
			throw new ServletException("error when querying students ",e);
		} catch (ServletException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	} 

}
 
Example 12
Project: openwayback   File: FastArchivalUrlReplayParseEventHandler.java View source code Vote up 6 votes
/**
         *
         * @param pContext
         * @throws IOException
         */
        @Override
	public void handleParseComplete(ParseContext pContext) throws IOException {
		// if no HTML element was found (inHTML==false), don't insert EndJsp.
		if (endJsp != null && pContext.isInHTML()) {
			ReplayParseContext context = (ReplayParseContext) pContext;
			OutputStream out = context.getOutputStream();
			String tmp = null; 
			try {
				tmp = context.getJspExec().jspToString(endJsp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
			if (tmp != null) {
//				Charset charset = Charset.forName(context.getOutputCharset());
				String charset = context.getOutputCharset();
				out.write(tmp.getBytes(charset));
			}
		}
	}
 
Example 13
Project: org.ops4j.pax.web   File: Context.java View source code Vote up 6 votes
public synchronized void destroy() {
    try {
        destroyHandler();
    } catch (ServletException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: sandbox   File: JspProvider.java View source code Vote up 6 votes
@Override
public void writeTo(Viewable t, Class<?> type, Type genericType,
        Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders,
        OutputStream entityStream) throws IOException,
        WebApplicationException {
    try (PrintWriter out = new PrintWriter(entityStream)) {
        request.setAttribute("parameter", t.parameter);
        request.getRequestDispatcher(t.path).forward(request,
                new HttpServletResponseWrapper(response) {

                    @Override
                    public PrintWriter getWriter() throws IOException {
                        return out;
                    }
                });
    } catch (ServletException e) {
        e.printStackTrace();
    }
}
 
Example 15
Project: overtown   File: StartupHandlerImpl.java View source code Vote up 6 votes
public HttpHandler createRootHandler(Configuration configuration , ScannerResult scannerResult) {
  PathHandler pathHandler = Handlers.path();

  String appContext = "/" + configuration.getAppContext();
  pathHandler.addPrefixPath( appContext , createAppHandlers(scannerResult));
  if(!scannerResult.getServerEndpoints().isEmpty()){
    DeploymentInfo builder = new DeploymentInfo().setClassLoader(this.getClass().getClassLoader()).setContextPath("/");
    WebSocketDeploymentInfo wsDeployInfo = new WebSocketDeploymentInfo();
    wsDeployInfo.setBuffers(new ByteBufferSlicePool(100, 1000));
    for(Class<?> serverEndpoint : scannerResult.getServerEndpoints() ){
      wsDeployInfo.addEndpoint( serverEndpoint );
    }
    builder.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, wsDeployInfo);
    builder.setDeploymentName("websocketDeploy.war");

    final ServletContainer container = ServletContainer.Factory.newInstance();
    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    try {
      OvertownSessionManager sessionManager = OvertownSessionManager.getInstance();
      String wsContextPath = "ws";
      if( !appContext.endsWith("/") ){
        wsContextPath += appContext + "/" + wsContextPath;
      }
      pathHandler.addPrefixPath( wsContextPath ,
              new SessionAttachmentHandler(  manager.start() , sessionManager.getSessionManager(),
                sessionManager.getSessionConfig()) );
    } catch (ServletException e) {
      e.printStackTrace();
    }
  }
  String staticContextPath = configuration.getStaticRootPath();
  if( !appContext.endsWith("/") ){
    staticContextPath = appContext + "/" + staticContextPath;
  }
  pathHandler.addPrefixPath( staticContextPath , new ResourceHandlerMounter().mount());
  return pathHandler;
}
 
Example 16
Project: AngularBeans   File: AngularBeansServletContextListener.java View source code Vote up 6 votes
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
	context = servletContextEvent.getServletContext();

	try {
		if (sockJsServer == null) {
			initJSR356();

		}

	} catch (ServletException e) {

		e.printStackTrace();
	}

	generateModule();
	generateExtentions();

}
 
Example 17
Project: java_learn   File: SignGuestbookServlet.java View source code Vote up 6 votes
public void doPost(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
  	 UserService userService = UserServiceFactory.getUserService();
       User user = userService.getCurrentUser();

       // We have one entity group per Guestbook with all Greetings residing
       // in the same entity group as the Guestbook to which they belong.
       // This lets us run a transactional ancestor query to retrieve all
       // Greetings for a given Guestbook.  However, the write rate to each
       // Guestbook should be limited to ~1/second.
       String guestbookName = req.getParameter("guestbookName");
       Key guestbookKey = KeyFactory.createKey("Guestbook", guestbookName);
       String content = req.getParameter("content");
       Date date = new Date();
       Entity greeting = new Entity("Greeting", guestbookKey);
       greeting.setProperty("user", user);
       greeting.setProperty("date", date);
       greeting.setProperty("content", content);

       DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
       datastore.put(greeting);
       RequestDispatcher rd = req.getRequestDispatcher("WEB-INF/jsp/guest/main.jsp");
	 try {
	rd.forward(req, resp);
} catch (ServletException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
  }
 
Example 18
Project: MusesServer   File: TestEventProcessorRt2aeIntegration.java View source code Vote up 6 votes
public final void testRestart(){
	CorrelationStartupServlet servlet = new CorrelationStartupServlet();
	try {
		servlet.init();
	} catch (ServletException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 19
Project: Payara   File: JAXWSServlet.java View source code Vote up 6 votes
protected void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException {
    startedEvent(endpoint.getEndpointAddressPath());
    if (("Tester".equalsIgnoreCase(request.getQueryString())) &&
            (!(HTTPBinding.HTTP_BINDING.equals(endpoint.getProtocolBinding())))) {
        Endpoint endpt = wsEngine_.getEndpoint(request.getServletPath());
        if (endpt != null && Boolean.parseBoolean(endpt.getDescriptor().getDebugging())) {
            WebServiceTesterServlet.invoke(request, response,
                    endpt.getDescriptor());
            endedEvent(endpoint.getEndpointAddressPath());
            return;
        }
    }

    // lookup registered URLs and get the appropriate adapter;
    // pass control to the adapter
    try {
        ServletAdapter targetEndpoint = (ServletAdapter) getEndpointFor(request);
        if (targetEndpoint != null) {
            targetEndpoint.handle(getServletContext(), request, response);
        } else {
            throw new ServletException("Service not found");
        }
    } catch (Throwable t) {
        ServletException se = new ServletException();
        se.initCause(t);
        throw se;
    }
    endedEvent(endpoint.getEndpointAddressPath());
}
 
Example 20
Project: PASTA   File: DynamicContentServlet.java View source code Vote up 6 votes
private void refreshGrowthStats() throws ServletException {
       ServletContext servletContext = getServletContext();
	String numDataPackages = null;
	String numDataPackagesSites = null;
			
       logger.info("Refreshing PASTA data package growth stats.");

       try {
		PastaStatistics pastaStats = new PastaStatistics("public");
		numDataPackages = pastaStats.getNumDataPackages().toString();
		numDataPackagesSites = pastaStats.getNumDataPackagesSites().toString();
	}
	catch (PastaConfigurationException | PastaAuthenticationException e) {
		ServletException se = new ServletException("Pasta statistics exception");
		se.initCause(e);
		throw se;		
	}

       GrowthStats gs = new GrowthStats();
       String googleChartJson = gs.getGoogleChartJson(new GregorianCalendar(), Calendar.MONTH);

       /* Lock the servlet context object to guarantee that only one thread at a
        * time can be getting or setting the context attribute. 
        */
       synchronized(servletContext) {
       	if (numDataPackages != null) 
       		servletContext.setAttribute("numDataPackages", numDataPackages);
       	
       	if (numDataPackagesSites != null) 
       		servletContext.setAttribute("numDataPackagesSites", numDataPackagesSites);
       	
       	if (googleChartJson != null) 
       		servletContext.setAttribute("googleChartJson", googleChartJson);
       }
}
 
Example 21
Project: freemarker-old   File: FreemarkerServlet.java View source code Vote up 6 votes
private ServletException newServletExceptionWithFreeMarkerLogging(String message, Throwable cause) throws ServletException {
    if (cause instanceof TemplateException) {
        // For backward compatibility, we log into the same category as Environment did when
        // log_template_exceptions was true.
        LOG_RT.error(message, cause);
    } else {
        LOG.error(message, cause);
    }

    ServletException e = new ServletException(message, cause);
    try {
        // Prior to Servlet 2.5, the cause exception wasn't set by the above constructor.
        // If we are on 2.5+ then this will throw an exception as the cause was already set.
        e.initCause(cause);
    } catch (Exception ex) {
        // Ignored; see above
    }
    throw e;
}
 
Example 22
Project: Fudan-Sakai   File: FileUploadFilter.java View source code Vote up 6 votes
public void init(FilterConfig config) throws ServletException {
    repositoryPath = config.getInitParameter("org.sakaiproject.tool.messageforums.FileUploadFilter.repositoryPath");

    try {
        String paramValue = config.getInitParameter("org.sakaiproject.tool.messageforums.FileUploadFilter.sizeThreshold");

        if (paramValue != null) {
            sizeThreshold = Integer.parseInt(paramValue);
        }
        paramValue = config.getInitParameter("org.sakaiproject.tool.messageforums.FileUploadFilter.sizeMax");
        if (paramValue != null) {
            sizeMax = Long.parseLong(paramValue);
        }
    } catch (NumberFormatException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
}
 
Example 23
Project: sakai-cle   File: UploadFilter.java View source code Vote up 6 votes
public void init(FilterConfig config) throws ServletException {
     repositoryPath = ServerConfigurationService.getString(
"samigo.answerUploadRepositoryPath", "${sakai.home}/samigo/answerUploadRepositoryPath/");

    try {
       String paramValue = ServerConfigurationService.getString(
          "samigo.sizeThreshold", "1024");
       if (paramValue != null)
          sizeThreshold = Integer.parseInt(paramValue);

       paramValue = ServerConfigurationService.getString(
          "samigo.sizeMax", "40960");
       if (paramValue != null)
          sizeMax = Long.parseLong(paramValue);

       paramValue = ServerConfigurationService.getString(
          "samigo.saveMediaToDb", "true");
       if (paramValue != null)
          saveMediaToDb = paramValue;

//System.out.println("**** repositoryPath="+repositoryPath);
//System.out.println("**** sabeMediaToDb="+saveMediaToDb);
//System.out.println("**** sizeThreshold="+sizeThreshold);
//System.out.println("**** sizeMax="+sizeMax);
    }
    catch (NumberFormatException ex) {
       ServletException servletEx = new ServletException();
       servletEx.initCause(ex);
       throw servletEx;
    }
    ServletContext context = config.getServletContext();
    context.setAttribute("FILEUPLOAD_REPOSITORY_PATH",repositoryPath);
    context.setAttribute("FILEUPLOAD_SIZE_THRESHOLD", Integer.valueOf(sizeThreshold));
    context.setAttribute("FILEUPLOAD_SIZE_MAX", Long.valueOf(sizeMax));
    context.setAttribute("FILEUPLOAD_SAVE_MEDIA_TO_DB", saveMediaToDb);
 }
 
Example 24
Project: incubator-freemarker   File: FreemarkerServlet.java View source code Vote up 6 votes
private ServletException newServletExceptionWithFreeMarkerLogging(String message, Throwable cause) throws ServletException {
    if (cause instanceof TemplateException) {
        // For backward compatibility, we log into the same category as Environment did when
        // log_template_exceptions was true.
        LOG_RT.error(message, cause);
    } else {
        LOG.error(message, cause);
    }

    ServletException e = new ServletException(message, cause);
    try {
        // Prior to Servlet 2.5, the cause exception wasn't set by the above constructor.
        // If we are on 2.5+ then this will throw an exception as the cause was already set.
        e.initCause(cause);
    } catch (Exception ex) {
        // Ignored; see above
    }
    throw e;
}
 
Example 25
Project: mymam   File: UploadMultipartRequestWrapper.java View source code Vote up 6 votes
public UploadMultipartRequestWrapper(HttpServletRequest request, ServletFileUpload upload) throws ServletException {
    super(request);
    try {
        List fileItems = upload.parseRequest(request);
        for (int i = 0; i < fileItems.size(); i++) {
            FileItem item = (FileItem) fileItems.get(i);
            if (item.isFormField()) {
                addParameter(item.getFieldName(), item.getString(), formParameters);
            } else {
                addParameter(item.getFieldName(), item, fileParameters);
            }
        }
    } catch (FileUploadException e) {
        // Request timed out
        ServletException servletException = new ServletException();
        servletException.initCause(e);
        throw servletException;
    }
}
 
Example 26
Project: glassfish-main   File: JAXWSServlet.java View source code Vote up 6 votes
protected void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException {
    startedEvent(endpoint.getEndpointAddressPath());
    if (("Tester".equalsIgnoreCase(request.getQueryString())) &&
            (!(HTTPBinding.HTTP_BINDING.equals(endpoint.getProtocolBinding())))) {
        Endpoint endpt = wsEngine_.getEndpoint(request.getServletPath());
        if (endpt != null && Boolean.parseBoolean(endpt.getDescriptor().getDebugging())) {
            WebServiceTesterServlet.invoke(request, response,
                    endpt.getDescriptor());
            endedEvent(endpoint.getEndpointAddressPath());
            return;
        }
    }

    // lookup registered URLs and get the appropriate adapter;
    // pass control to the adapter
    try {
        ServletAdapter targetEndpoint = (ServletAdapter) getEndpointFor(request);
        if (targetEndpoint != null) {
            targetEndpoint.handle(getServletContext(), request, response);
        } else {
            throw new ServletException("Service not found");
        }
    } catch (Throwable t) {
        ServletException se = new ServletException();
        se.initCause(t);
        throw se;
    }
    endedEvent(endpoint.getEndpointAddressPath());
}
 
Example 27
Project: Katari   File: HtmlValidationFilterTest.java View source code Vote up 6 votes
@Test
public final void testDoFilter_invalidHtml() throws Exception {

  // Mocks the filter chain.
  FilterChain chain = new FilterChain() {
    public void doFilter(final ServletRequest request, final
        ServletResponse response) throws IOException {
      log.trace("Entering doFilter");

      PrintWriter writer = new PrintWriter(response.getOutputStream());
      writer.write(
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
          + " \"http://www.w3.org/TR/html4/strict.dtd\">"
          + " <html><table id='someid'><td id='someid'>"
          + " <non_existing_attribute></td></html>");
      writer.flush();
      log.trace("Leaving doFilter");
    }
  };

  // Executes the test.
  HtmlValidationFilter filter = new HtmlValidationFilter();
  filter.init(filterConfig);
  try {
    filter.doFilter(request, response, chain);
    assertTrue("Expected ServletException not thrown", true);
  } catch (ServletException e) {
    String message = e.getMessage();
    assertTrue(message.matches("(?s).*<non_existing_attribute>(?s).*"));
  }
}
 
Example 28
Project: resin   File: WebApp.java View source code Vote up 6 votes
/**
 * Adds a new or augments existing registration
 *
 * @since 3.0
 */
private ServletRegistration.Dynamic addServlet(String servletName,
                                               String servletClassName,
                                               Class<? extends Servlet> servletClass,
                                               Servlet servlet)
{
  if (! isInitializing())
    throw new IllegalStateException(L.l("addServlet may only be called during initialization"));

  try {
    ServletConfigImpl config
      = (ServletConfigImpl) getServletRegistration(servletName);

    if (config == null) {
      config = createServlet();

      config.setServletName(servletName);
      config.setServletClass(servletClassName);
      config.setServletClass(servletClass);
      config.setServlet(servlet);

      addServlet(config);
    } else {
      if (config.getClassName() == null)
        config.setServletClass(servletClassName);

      if (config.getServletClass() == null)
        config.setServletClass(servletClass);

      if (config.getServlet() == null)
        config.setServlet(servlet);
    }

    return config;
  }
  catch (ServletException e) {
    //spec declares no throws so far
    throw new RuntimeException(e.getMessage(), e);
  }
}
 
Example 29
Project: openwayback   File: BeforeBodyEndTagJSPExecRule.java View source code Vote up 6 votes
public void emit(ReplayParseContext context, Node node) throws IOException {
	String found = context.getData(FERRET_DONE_KEY);
	if(found == null) {
		context.putData(FERRET_DONE_KEY,"1");
		try {
			super.emit(context, node);
		} catch (ServletException e) {
			e.printStackTrace();
			throw new IOException(e.getMessage());
		}
	}
}
 
Example 30
Project: Payara   File: SSIServletExternalResolver.java View source code Vote up 6 votes
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos =
            new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper =
            new ResponseIncludeWrapper(context, req, res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String(bytes, Charset.defaultCharset());
        } else {
            retVal = new String (bytes, Charsets.lookupCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
                "HEAD")) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 31
Project: jsp-template-inheritance   File: ExtendsTag.java View source code Vote up 6 votes
@Override
public void doTag() throws JspException, IOException {
    StringWriter ignoredWriter = new StringWriter();
    getJspBody().invoke(ignoredWriter); // ignore body text

    PageContext pageContext = (PageContext) getJspContext();

    try {
        pageContext.forward(getRefinedName());
    } catch (ServletException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 32
Project: stormpath-sdk-java   File: DefaultServletContextClientFactory.java View source code Vote up 6 votes
protected void applyCacheManager(ClientBuilder builder) {

        CacheManager cacheManager;

        try {
            cacheManager = config.getInstance(STORMPATH_CACHE_MANAGER);
        } catch (ServletException e) {
            String msg = "Unable to get CacheManager instance from Config: " + e.getMessage();
            throw new IllegalStateException(msg, e);
        }

        Assert.notNull(cacheManager, "Configured CacheManager cannot be null.  If you want to disable caching " +
                                     "entirely, configure a " + DisabledCacheManager.class.getName() + " instead.");

        builder.setCacheManager(cacheManager);
    }
 
Example 33
Project: rhq   File: InventoryHierarchyTag.java View source code Vote up 6 votes
private String buildGroupHTML() throws JspException {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    Subject subject;
    try {
        subject = RequestUtils.getSubject(request);
    } catch (ServletException e) {
        throw new JspException(e.getMessage());
    }

    ResourceGroup resourceGroup = this.resourceGroupManager.getResourceGroupById(subject, this.groupId, null);
    StringBuilder html = new StringBuilder();
    html.append("<a href=\"").append(buildGroupURL(resourceGroup)).append("\">");
    html.append(resourceGroup.getName()).append("</a>");
    return html.toString();
}
 
Example 34
Project: tapestry-spring-security   File: RequestFilterWrapper.java View source code Vote up 6 votes
public final boolean service(final Request request,
        final Response response, final RequestHandler handler)
        throws IOException {

    // TODO: Thread safety!
    // Assume request handled if filter chain is NOT executed
    final boolean[] res = new boolean[] {true};
    try {
        filter.doFilter(globals.getHTTPServletRequest(), globals
                .getHTTPServletResponse(), new FilterChain() {
            public void doFilter(final ServletRequest req,
                    final ServletResponse resp) throws IOException,
                    ServletException {
                res[0] = handler.service(request, response);
            }
        });
    } catch (ServletException e) {
        IOException ex = new IOException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }
    return res[0];
}
 
Example 35
Project: profile   File: AccessDeniedHandlerImpl.java View source code Vote up 6 votes
protected void forwardToErrorPage(RequestContext context) throws SecurityProviderException, IOException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    String errorPageUrl = getErrorPageUrl();

    response.setStatus(HttpServletResponse.SC_FORBIDDEN);

    logger.debug("Forwarding to error page at {}, with 403 FORBIDDEN status", errorPageUrl);

    RequestDispatcher dispatcher = request.getRequestDispatcher(errorPageUrl);
    try {
        dispatcher.forward(request, response);
    } catch (ServletException e) {
        throw new SecurityProviderException(e.getMessage(), e);
    }
}
 
Example 36
Project: oozie   File: BundleEngine.java View source code Vote up 6 votes
/**
 * Parse filter string to a map with key = filter name and values = filter values
 *
 * @param filter the filter string
 * @return filter key and value map
 * @throws CoordinatorEngineException thrown if failed to parse filter string
 */
@VisibleForTesting
Map<String, List<String>> parseFilter(String filter) throws BundleEngineException {
    try {
        return JobsFilterUtils.parseFilter(filter);
    }
    catch (ServletException ex) {
        throw new BundleEngineException(ErrorCode.E0420, filter, ex.getMessage());
    }
}
 
Example 37
Project: JNetty   File: WebApp.java View source code Vote up 6 votes
/**
 * Adds a new or augments existing registration
 * 
 * @since 3.0
 */
private ServletRegistration.Dynamic addServlet(String servletName, String servletClassName, Class<? extends Servlet> servletClass, Servlet servlet)
{

	try
	{
		ServletConfigImpl config = (ServletConfigImpl) getServletRegistration(servletName);

		if (config == null)
		{
			config = createNewServletConfig();

			config.setServletName(servletName);
			config.setServletClass(servletClassName);
			config.setServletClass(servletClass);
			config.setServlet(servlet);

			addServlet(config);
		}
		else
		{
			if (config.getClassName() == null)
				config.setServletClass(servletClassName);

			if (config.getServletClass() == null)
				config.setServletClass(servletClass);

			if (config.getServlet() == null)
				config.setServlet(servlet);
		}

		if (debug)
		{
			log.debug("dynamic servlet added [name: '" + servletName + "', class: '" + servletClassName + "'] (in " + this + ")");
		}

		return config;
	}
	catch (ServletException e)
	{
		// spec declares no throws so far
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 38
Project: cxf   File: ServletController.java View source code Vote up 6 votes
private void init() {
    if (servletConfig == null) {
        return;
    }
    
    String hideServiceList = servletConfig.getInitParameter("hide-service-list-page");
    if (!StringUtils.isEmpty(hideServiceList)) {
        this.isHideServiceList = Boolean.valueOf(hideServiceList);
    }
    
    String authServiceListPage = servletConfig.getInitParameter("service-list-page-authenticate");
    if (!StringUtils.isEmpty(authServiceListPage)) {
        this.isAuthServiceListPage = Boolean.valueOf(authServiceListPage);
    }
    
    String authServiceListRealm = servletConfig.getInitParameter("service-list-page-authenticate-realm");
    if (!StringUtils.isEmpty(authServiceListRealm)) {
        this.authServiceListPageRealm = authServiceListRealm;
    }
    
    String isDisableAddressUpdates = servletConfig.getInitParameter("disable-address-updates");
    if (!StringUtils.isEmpty(isDisableAddressUpdates)) {
        this.disableAddressUpdates = Boolean.valueOf(isDisableAddressUpdates);
    }
    String isForcedBaseAddress = servletConfig.getInitParameter("base-address");
    if (!StringUtils.isEmpty(isForcedBaseAddress)) {
        this.forcedBaseAddress = isForcedBaseAddress;
    }
    try {
        serviceListGenerator.init(servletConfig);
    } catch (ServletException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String serviceListPath = servletConfig.getInitParameter("service-list-path");
    if (!StringUtils.isEmpty(serviceListPath)) {
        this.serviceListRelativePath = serviceListPath;
    }
}
 
Example 39
Project: Tomcat   File: SSIServletExternalResolver.java View source code Vote up 6 votes
@Override
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos =
            new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper =
            new ResponseIncludeWrapper(context, req, res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String( bytes );
        } else {
            retVal = new String (bytes,
                    B2CConverter.getCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
                org.apache.coyote.http11.Constants.HEAD)) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 40
Project: tnoodle   File: WebAppConfiguration.java View source code Vote up 6 votes
/**
 * Build a dispatcher to the error handler if it's available. If it fails, return null.
 */
private RequestDispatcher buildErrorDispatcher(String errorURI, int statusCode,
        String summaryMessage, Throwable exception) {
    // Parse the url for query string, etc
    String queryString = "";
    int questionPos = errorURI.indexOf('?');
    if (questionPos != -1) {
        if (questionPos != errorURI.length() - 1) {
            queryString = errorURI.substring(questionPos + 1);
        }
        errorURI = errorURI.substring(0, questionPos);
    }

    // Get the message by recursing if none supplied
    ServletException errIterator = new ServletException(exception);
    while ((summaryMessage == null) && (errIterator != null)) {
        summaryMessage = errIterator.getMessage();
        if (errIterator.getRootCause() instanceof ServletException) {
            errIterator = (ServletException) errIterator.getRootCause();
        } else {
            if (summaryMessage == null) {
                summaryMessage = errIterator.getRootCause().getMessage();
            }
            errIterator = null;
        }
    }

    // Return the dispatcher
    StringBuffer servletPath = new StringBuffer();
    StringBuffer pathInfo = new StringBuffer();
    ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo);
    if (servlet != null) {
        RequestDispatcher rd = new RequestDispatcher(this, servlet);
        if (rd != null) {
            rd.setForErrorDispatcher(servletPath.toString(),
                    pathInfo.toString().equals("") ? null : pathInfo.toString(),
                            queryString, statusCode, summaryMessage,
                            exception, errorURI, this.filterPatternsError);
            return rd;
        }
    }
    return null;
}
 
Example 41
Project: coding-dojo   File: UnwrapSecurityExceptionFilter.java View source code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request,response);
    } catch (ServletException e) {
        Throwable t = e.getRootCause();
        if (t instanceof JellyTagException) {
            JellyTagException jte = (JellyTagException) t;
            Throwable cause = jte.getCause();
            if (cause instanceof AcegiSecurityException) {
                AcegiSecurityException se = (AcegiSecurityException) cause;
                throw new ServletException(se);
            }
        }
        throw e;
    }
}
 
Example 42
Project: hudson-main   File: UnwrapSecurityExceptionFilter.java View source code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request,response);
    } catch (ServletException e) {
        Throwable t = e.getRootCause();
        if (t instanceof JellyTagException) {
            JellyTagException jte = (JellyTagException) t;
            Throwable cause = jte.getCause();
            if (cause instanceof AcegiSecurityException) {
                AcegiSecurityException se = (AcegiSecurityException) cause;
                throw new ServletException(se);
            }
        }
        throw e;
    }
}
 
Example 43
Project: opennms_dashboard   File: SpringWebflowContextTest.java View source code Vote up 6 votes
public void testLoadContext() throws Throwable {

        DaoTestConfigBean bean = new DaoTestConfigBean();
        bean.afterPropertiesSet();

        MockDatabase db = new MockDatabase(true);
        DataSourceFactory.setInstance(db);

        servletContext = new MockServletContext("file:src/main/webapp");

        servletContext.addInitParameter("contextConfigLocation", 
                                        "classpath:/org/opennms/web/rest/applicationContext-test.xml " +
                                        "classpath:/META-INF/opennms/applicationContext-commonConfigs.xml " +
                                        "classpath*:/META-INF/opennms/component-service.xml " +
                                        "classpath*:/META-INF/opennms/component-dao.xml " +
                                        "classpath:/META-INF/opennms/applicationContext-reportingCore.xml " +
                                        "classpath:/org/opennms/web/svclayer/applicationContext-svclayer.xml " +
                                        "classpath:/META-INF/opennms/applicationContext-reporting.xml " +
                                        "/WEB-INF/applicationContext-spring-security.xml " +
                                        "/WEB-INF/applicationContext-spring-webflow.xml"
        );

        servletContext.addInitParameter("parentContextKey", "daoContext");

        ServletContextEvent e = new ServletContextEvent(servletContext);
        contextListener = new ContextLoaderListener();
        contextListener.contextInitialized(e);

        servletContext.setContextPath(contextPath);
        servletConfig = new MockServletConfig(servletContext, "dispatcher");    
        servletConfig.addInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig");
        servletConfig.addInitParameter("com.sun.jersey.config.property.packages", "org.opennms.web.rest");

        try {

            MockFilterConfig filterConfig = new MockFilterConfig(servletContext, "openSessionInViewFilter");
            filter = new OpenSessionInViewFilter();        
            filter.init(filterConfig);

            dispatcher = new SpringServlet();
            dispatcher.init(servletConfig);

        } catch (ServletException se) {
            throw se.getRootCause();
        }
    }
 
Example 44
Project: hudson.core   File: UnwrapSecurityExceptionFilter.java View source code Vote up 6 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        Throwable t = e.getRootCause();
        if (t instanceof JellyTagException) {
            JellyTagException jte = (JellyTagException) t;
            Throwable cause = jte.getCause();
        }
        throw e;
    }
}
 
Example 45
Project: jetty.project   File: FilterHolder.java View source code Vote up 6 votes
@Override
public void initialize() throws Exception
{
    super.initialize();
    
    if (_filter==null)
    {
        try
        {
            ServletContext context=_servletHandler.getServletContext();
            _filter=(context instanceof ServletContextHandler.Context)
                ?((ServletContextHandler.Context)context).createFilter(getHeldClass())
                :getHeldClass().newInstance();
        }
        catch (ServletException se)
        {
            Throwable cause = se.getRootCause();
            if (cause instanceof InstantiationException)
                throw (InstantiationException)cause;
            if (cause instanceof IllegalAccessException)
                throw (IllegalAccessException)cause;
            throw se;
        }
    }

    _config=new Config();
    if (LOG.isDebugEnabled())
        LOG.debug("Filter.init {}",_filter);
    _filter.init(_config);
}
 
Example 46
Project: cipango   File: MetaData.java View source code Vote up 6 votes
public EventListener newListenerInstance(SipAppContext context,Class<? extends EventListener> clazz) throws ServletException, InstantiationException, IllegalAccessException
{
    try
    {
        return ((ServletContextHandler.Context)context.getWebAppContext().getServletContext()).createListener(clazz);
    }
    catch (ServletException se)
    {
        Throwable cause = se.getRootCause();
        if (cause instanceof InstantiationException)
            throw (InstantiationException)cause;
        if (cause instanceof IllegalAccessException)
            throw (IllegalAccessException)cause;
        throw se;
    }
}
 
Example 47
Project: hudson   File: UnwrapSecurityExceptionFilter.java View source code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request,response);
    } catch (ServletException e) {
        Throwable t = e.getRootCause();
        if (t instanceof JellyTagException) {
            JellyTagException jte = (JellyTagException) t;
            Throwable cause = jte.getCause();
            if (cause instanceof AcegiSecurityException) {
                AcegiSecurityException se = (AcegiSecurityException) cause;
                throw new ServletException(se);
            }
        }
        throw e;
    }
}
 
Example 48
Project: jetty-spdy   File: FilterHolder.java View source code Vote up 6 votes
@Override
public void doStart()
    throws Exception
{
    super.doStart();
    
    if (!javax.servlet.Filter.class
        .isAssignableFrom(_class))
    {
        String msg = _class+" is not a javax.servlet.Filter";
        super.stop();
        throw new IllegalStateException(msg);
    }

    if (_filter==null)
    {
        try
        {
            _filter=((ServletContextHandler.Context)_servletHandler.getServletContext()).createFilter(getHeldClass());
        }
        catch (ServletException se)
        {
            Throwable cause = se.getRootCause();
            if (cause instanceof InstantiationException)
                throw (InstantiationException)cause;
            if (cause instanceof IllegalAccessException)
                throw (IllegalAccessException)cause;
            throw se;
        }
    }
    
    _config=new Config();
    _filter.init(_config);
}
 
Example 49
Project: hudson-2.x   File: UnwrapSecurityExceptionFilter.java View source code Vote up 6 votes
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request,response);
    } catch (ServletException e) {
        Throwable t = e.getRootCause();
        if (t instanceof JellyTagException) {
            JellyTagException jte = (JellyTagException) t;
            Throwable cause = jte.getCause();
            if (cause instanceof AcegiSecurityException) {
                AcegiSecurityException se = (AcegiSecurityException) cause;
                throw new ServletException(se);
            }
        }
        throw e;
    }
}
 
Example 50
Project: jetty-plugin-support   File: FilterHolder.java View source code Vote up 6 votes
@Override
public void doStart()
    throws Exception
{
    super.doStart();
    
    if (!javax.servlet.Filter.class
        .isAssignableFrom(_class))
    {
        String msg = _class+" is not a javax.servlet.Filter";
        super.stop();
        throw new IllegalStateException(msg);
    }

    if (_filter==null)
    {
        try
        {
            _filter=((ServletContextHandler.Context)_servletHandler.getServletContext()).createFilter(getHeldClass());
        }
        catch (ServletException se)
        {
            Throwable cause = se.getRootCause();
            if (cause instanceof InstantiationException)
                throw (InstantiationException)cause;
            if (cause instanceof IllegalAccessException)
                throw (IllegalAccessException)cause;
            throw se;
        }
    }
    
    _config=new Config();
    _filter.init(_config);
}
 
Example 51
Project: primefaces-starter   File: ConversationExceptionFilter.java View source code Vote up 6 votes
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;
	try {
		chain.doFilter(request, response);
	} catch (ServletException e) {
		if (e.getCause() instanceof NonexistentConversationException) {
			HttpServletRequestWrapper wrapper = new ConversationAwareRequestWrapper(request);
			String context = request.getContextPath();
			String viewId = request.getRequestURI();
			String path = viewId.replaceFirst(context, "");
			request.getRequestDispatcher(path).forward(wrapper, res);
		} else {
			throw e;
		}
	}
}
 
Example 52
Project: cas-client-3.2.1   File: ErrorRedirectFilter.java View source code Vote up 6 votes
public void doFilter(final ServletRequest request, final ServletResponse response,
		final FilterChain filterChain) throws IOException, ServletException {
	final HttpServletResponse httpResponse = (HttpServletResponse) response;
	try {
		filterChain.doFilter(request, response);
	} catch (final ServletException e) {
		final Throwable t = e.getCause();
		ErrorHolder currentMatch = null;
           for (final ErrorHolder errorHolder : this.errors) {
			if (errorHolder.exactMatch(t)) {
				currentMatch = errorHolder;
				break;
			} else if (errorHolder.inheritanceMatch(t)) {
				currentMatch = errorHolder;
			}
		}
		
		if (currentMatch != null) {
			httpResponse.sendRedirect(currentMatch.getUrl());
		} else {
			httpResponse.sendRedirect(defaultErrorRedirectPage);
		}
	}
}
 
Example 53
Project: zanata-server   File: GwtDispatchService.java View source code Vote up 6 votes
@Override
public Result execute(final Action<?> action) throws Exception {
    final Result[] result = { null };
    try {
        new ContextualHttpServletRequest(getThreadLocalRequest()) {
            @Override
            public void process() throws Exception {
                SeamDispatch dispatch = ServiceLocator.instance()
                        .getInstance(SeamDispatch.class);
                result[0] = dispatch.execute(action);
            }
        }.run();
    } catch (ServletException e) {
        Throwable cause = e.getCause();
        // ActionException is under shared package which is serializable by
        // GWT.
        if (cause != null && cause instanceof ActionException) {
            throw ActionException.class.cast(cause);
        }
        throw e;
    }
    return result[0];
}
 
Example 54
Project: bonita-web   File: AuthenticationFilter.java View source code Vote up 6 votes
/**
 * @return true if one of the rules pass false otherwise
 */
protected boolean isAuthorized(final HttpServletRequestAccessor requestAccessor,
        final HttpServletResponseAccessor responseAccessor,
        final TenantIdAccessor tenantIdAccessor,
        final FilterChain chain) throws ServletException, IOException {

    for (final AuthenticationRule rule : getRules()) {
        try {
            if (rule.doAuthorize(requestAccessor, tenantIdAccessor)) {
                chain.doFilter(requestAccessor.asHttpServletRequest(), responseAccessor.asServletResponse());
                return true;
            }
        } catch (final ServletException e) {
            if (e.getCause() instanceof TenantIsPausedRedirectionToMaintenancePageException) {
                return handleTenantPausedException(requestAccessor, responseAccessor, e);
            } else {
                throw e;
            }
        }
    }
    return false;
}
 
Example 55
Project: nuxeo   File: NXFileRenderer.java View source code Vote up 6 votes
@Override
public void decode(FacesContext context, UIComponent component) {

    rendererParamsNotNull(context, component);

    if (!shouldDecode(component)) {
        return;
    }

    String clientId = decodeBehaviors(context, component);

    if (clientId == null) {
        clientId = component.getClientId(context);
    }

    assert (clientId != null);
    ExternalContext externalContext = context.getExternalContext();
    Map<String, String> requestMap = externalContext.getRequestParameterMap();

    if (requestMap.containsKey(clientId)) {
        setSubmittedValue(component, requestMap.get(clientId));
    }

    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    try {
        Collection<Part> parts = request.getParts();
        for (Part cur : parts) {
            if (clientId.equals(cur.getName())) {
                // Nuxeo patch: transform into serializable blob right away, and do not set component transient
                // component.setTransient(true);
                // setSubmittedValue(component, cur);
                setSubmittedValue(component, FileUtils.createBlob(cur));
            }
        }
    } catch (IOException ioe) {
        throw new FacesException(ioe);
    } catch (ServletException se) {
        Throwable cause = se.getCause();
        // Nuxeo specific error management
        if ((cause instanceof InvalidContentTypeException)
                || (cause != null && cause.getClass().getName().contains("InvalidContentTypeException"))) {
            setSubmittedValue(component, Blobs.createBlob(""));
        } else {
            throw new FacesException(se);
        }
    }
}
 
Example 56
Project: BroadleafCommerce   File: AdminCsrfFilter.java View source code Vote up 6 votes
public void doFilter(ServletRequest baseRequest, ServletResponse baseResponse, FilterChain chain) throws IOException, ServletException {
    try {
        super.doFilter(baseRequest, baseResponse, chain);
    } catch (ServletException e) {
        if (e.getCause() instanceof ServiceException) {
            HttpServletRequest baseHttpRequest = (HttpServletRequest) baseRequest;
            //if authentication is null and CSRF token is invalid, must be session time out
            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                baseHttpRequest.setAttribute("sessionTimeout", true);
                failureHandler.onAuthenticationFailure((HttpServletRequest) baseRequest, (HttpServletResponse) baseResponse, new SessionAuthenticationException("Session Time Out"));
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }
}
 
Example 57
Project: winstone   File: WebAppConfiguration.java View source code Vote up 6 votes
/**
 * Build a dispatcher to the error handler if it's available. If it fails, return null.
 */
private SimpleRequestDispatcher buildErrorDispatcher(String errorURI, final int statusCode, String summaryMessage,
        final Throwable exception) {
    // Parse the url for query string, etc
    String queryString = "";
    final int questionPos = errorURI.indexOf('?');
    if (questionPos != -1) {
        if (questionPos != errorURI.length() - 1) {
            queryString = errorURI.substring(questionPos + 1);
        }
        errorURI = errorURI.substring(0, questionPos);
    }

    // Get the message by recursing if none supplied
    ServletException errIterator = new ServletException(exception);
    while (summaryMessage == null && errIterator != null) {
        summaryMessage = errIterator.getMessage();
        if (errIterator.getRootCause() instanceof ServletException) {
            errIterator = (ServletException) errIterator.getRootCause();
        } else {
            if (summaryMessage == null && errIterator.getCause() != null) {
                summaryMessage = errIterator.getRootCause().getMessage();
            }
            errIterator = null;
        }
    }

    // Return the dispatcher
    final StringBuilder servletPath = new StringBuilder();
    final StringBuilder pathInfo = new StringBuilder();
    final ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo);
    if (servlet != null) {
        final SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, servlet);
        if (rd != null) {
            rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(),
                    queryString, statusCode, summaryMessage, exception, errorURI, filterPatternsError);
            return rd;
        }
    }
    return null;
}
 
Example 58
Project: gatein-wci   File: CommandServlet.java View source code Vote up 5 votes
/**
 * <p>Execute a command after having performed a request dispatch in the target servlet context.</p>
 * <p/>
 * <p>The provided callback argument must expose a public non static and non abstract method with the signature
 * <code>execute(HttpServletRequest,HttpServletResponse)</code>. This method must return an object and can declare
 * any exception. This method will be invoked after the request dispatch operation is done.</p>
 * <p/>
 * <p>Any throwable thrown by the callback invocation will be wrapped in a <code>ServletException</code> and
 * rethrown, unless it is an instance of <code>ServletException</code> or <code>IOException</code>.</p>
 *
 * @param servletPath the servlet path on which the command servlet is mapped
 * @param request the servlet container request
 * @param response the servlet container response
 * @param callback      the callback to invoke after the inclusion is done
 * @param targetContext the target servlet context
 * @return the object returned by the callback
 * @throws IOException      likely thrown by the request dispatch operation
 * @throws ServletException wraps any exception thrown by the callback
 */
static Object include(
   String servletPath,
   HttpServletRequest request,
   HttpServletResponse response,
   Object callback,
   ServletContext targetContext) throws ServletException, IOException
{
   try
   {
      localCmd.set(callback);
      RequestDispatcher switcher = targetContext.getRequestDispatcher(servletPath);
      switcher.include(request, response);

      //
      Throwable throwable = localThrowable.get();

      //
      if (throwable != null)
      {
         if (throwable instanceof IOException)
         {
            throw (IOException)throwable;
         }
         else if (throwable instanceof ServletException)
         {
            throw (ServletException)throwable;
         }
         else
         {
            ServletException se = new ServletException();
            se.initCause(throwable);
            throw se;
         }
      }

      //
      return localResponse.get();
   }
   finally
   {
      localCmd.set(null);
      localResponse.set(null);
      localThrowable.set(null);
   }
}
 
Example 59
Project: jetty.project   File: DebugHandler.java View source code Vote up 5 votes
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
{
    final Response base_response = baseRequest.getResponse();
    final Thread thread=Thread.currentThread();
    final String old_name=thread.getName();

    boolean suspend=false;
    boolean retry=false;
    String name=(String)request.getAttribute("org.eclipse.jetty.thread.name");
    if (name == null)
        name = old_name + ":" + baseRequest.getHttpURI();
    else
        retry=true;

    String ex=null;
    try
    {
        if (retry)
            print(name,"RESUME");
        else
            print(name,"REQUEST "+baseRequest.getRemoteAddr()+" "+request.getMethod()+" "+baseRequest.getHeader("Cookie")+"; "+baseRequest.getHeader("User-Agent"));
        thread.setName(name);

        getHandler().handle(target,baseRequest,request,response);
    }
    catch(IOException ioe)
    {
        ex=ioe.toString();
        throw ioe;
    }
    catch(ServletException se)
    {
        ex=se.toString()+":"+se.getCause();
        throw se;
    }
    catch(RuntimeException rte)
    {
        ex=rte.toString();
        throw rte;
    }
    catch(Error e)
    {
        ex=e.toString();
        throw e;
    }
    finally
    {
        thread.setName(old_name);
        suspend=baseRequest.getHttpChannelState().isSuspended();
        if (suspend)
        {
            request.setAttribute("org.eclipse.jetty.thread.name",name);
            print(name,"SUSPEND");
        }
        else
            print(name,"RESPONSE "+base_response.getStatus()+(ex==null?"":("/"+ex))+" "+base_response.getContentType());
    }
}