javax.servlet.UnavailableException Java Examples

The following examples show how to use javax.servlet.UnavailableException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HostManagerServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void init() throws ServletException {

    // Ensure that our ContainerServlet properties have been set
    if ((wrapper == null) || (context == null))
        throw new UnavailableException
            (sm.getString("hostManagerServlet.noWrapper"));

    // Set our properties from the initialization parameters
    String value = null;
    try {
        value = getServletConfig().getInitParameter("debug");
        debug = Integer.parseInt(value);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
    }

}
 
Example #2
Source File: ProxyServlet.java    From logbook-kai with MIT License 6 votes vote down vote up
@Override
public void init() throws ServletException {
    super.init();

    ServletConfig config = this.getServletConfig();

    String prefix = config.getInitParameter("prefix");
    this._prefix = prefix == null ? this._prefix : prefix;

    // Adjust prefix value to account for context path
    String contextPath = this.getServletContext().getContextPath();
    this._prefix = this._prefix == null ? contextPath : (contextPath + this._prefix);

    String proxyTo = config.getInitParameter("proxyTo");
    this._proxyTo = proxyTo == null ? this._proxyTo : proxyTo;

    if (this._proxyTo == null)
        throw new UnavailableException("Init parameter 'proxyTo' is required.");

    if (!this._prefix.startsWith("/"))
        throw new UnavailableException("Init parameter 'prefix' parameter must start with a '/'.");

    if (this._isDebugEnabled) {
        this._log.debug(config.getServletName() + " @ " + this._prefix + " to " + this._proxyTo);
    }
}
 
Example #3
Source File: InterfaceA_EngineBasedServer.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void init() throws ServletException {     

        ServletContext context = getServletContext();

        // read persistence flag from web.xml & get engine instance
        try {
            String persistOn = context.getInitParameter("EnablePersistence") ;
            boolean enablePersist = "true".equalsIgnoreCase(persistOn);

            _engine = (EngineGateway) context.getAttribute("engine");
            if (_engine == null) {
                _engine = new EngineGatewayImpl(enablePersist);
                context.setAttribute("engine", _engine);
            }
        } catch (YPersistenceException e) {
            logger.fatal("Failure to initialise runtime (persistence failure)", e);
            throw new UnavailableException("Persistence failure");
        }
    }
 
Example #4
Source File: AbstractRestServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig servletConfig) throws ServletException {
  // First try the servlet context init-param.
  String source = "InitParameter";
  key = servletConfig.getInitParameter(APPKEY);
  if (key == null || key.startsWith("${")) {
    source = "System Property";
    key = System.getProperty(APPKEY);
  }
  if (key == null || key.startsWith("${")) {
    source = "Environment Variable";
    key = System.getenv(APPKEY_ENV);
  }
  if (key == null) {
    throw new UnavailableException("Places App Key not set");
  }
  if (key.startsWith("${")) {
    throw new UnavailableException("Places App Key not expanded from " + source);
  }
}
 
Example #5
Source File: HostManagerServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {

    // Ensure that our ContainerServlet properties have been set
    if ((wrapper == null) || (context == null))
        throw new UnavailableException
            (sm.getString("hostManagerServlet.noWrapper"));

    // Set our properties from the initialization parameters
    String value = null;
    try {
        value = getServletConfig().getInitParameter("debug");
        debug = Integer.parseInt(value);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
    }

}
 
Example #6
Source File: WebdavServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init()
    throws ServletException {

    super.init();

    if (getServletConfig().getInitParameter("secret") != null)
        secret = getServletConfig().getInitParameter("secret");

    if (getServletConfig().getInitParameter("maxDepth") != null)
        maxDepth = Integer.parseInt(
                getServletConfig().getInitParameter("maxDepth"));

    if (getServletConfig().getInitParameter("allowSpecialPaths") != null)
        allowSpecialPaths = Boolean.parseBoolean(
                getServletConfig().getInitParameter("allowSpecialPaths"));

    // Load the MD5 helper used to calculate signatures.
    try {
        md5Helper = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new UnavailableException("No MD5");
    }

}
 
Example #7
Source File: ManagedServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void forceInit() throws ServletException {
    if (!started) {
        if(servletContext.getDeployment().getDeploymentState() != DeploymentManager.State.STARTED) {
            throw UndertowServletMessages.MESSAGES.deploymentStopped(servletContext.getDeployment().getDeploymentInfo().getDeploymentName());
        }
        synchronized (this) {
            if (!started) {
                try {
                    instanceStrategy.start();
                } catch (UnavailableException e) {
                    handleUnavailableException(e);
                }
                started = true;
            }
        }
    }
}
 
Example #8
Source File: ManagedServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void createServlet() throws ServletException {
    if (permanentlyUnavailable) {
        return;
    }
    try {
        if (!started && servletInfo.getLoadOnStartup() != null && servletInfo.getLoadOnStartup() >= 0) {
            instanceStrategy.start();
            started = true;
        }
    } catch (UnavailableException e) {
        if (e.isPermanent()) {
            permanentlyUnavailable = true;
            stop();
        }
    }
}
 
Example #9
Source File: HostManagerServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {

    // Ensure that our ContainerServlet properties have been set
    if ((wrapper == null) || (context == null))
        throw new UnavailableException
            (sm.getString("hostManagerServlet.noWrapper"));

    // Set our properties from the initialization parameters
    String value = null;
    try {
        value = getServletConfig().getInitParameter("debug");
        debug = Integer.parseInt(value);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
    }

}
 
Example #10
Source File: WebdavServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init()
    throws ServletException {

    super.init();

    if (getServletConfig().getInitParameter("secret") != null)
        secret = getServletConfig().getInitParameter("secret");

    if (getServletConfig().getInitParameter("maxDepth") != null)
        maxDepth = Integer.parseInt(
                getServletConfig().getInitParameter("maxDepth"));

    if (getServletConfig().getInitParameter("allowSpecialPaths") != null)
        allowSpecialPaths = Boolean.parseBoolean(
                getServletConfig().getInitParameter("allowSpecialPaths"));

    // Load the MD5 helper used to calculate signatures.
    try {
        md5Helper = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new UnavailableException("No MD5");
    }

}
 
Example #11
Source File: ManagedServlet.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public void createServlet() throws ServletException {
    if (permanentlyUnavailable) {
        return;
    }
    try {
        if (!started && servletInfo.getLoadOnStartup() != null && servletInfo.getLoadOnStartup() >= 0) {
            instanceStrategy.start();
            started = true;
        }
    } catch (UnavailableException e) {
        if (e.isPermanent()) {
            permanentlyUnavailable = true;
            stop();
        }
    }
}
 
Example #12
Source File: ManagedServlet.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
public void forceInit() throws ServletException {
    if (!started) {
        if(servletContext.getDeployment().getDeploymentState() != DeploymentManager.State.STARTED) {
            throw UndertowServletMessages.MESSAGES.deploymentStopped(servletContext.getDeployment().getDeploymentInfo().getDeploymentName());
        }
        synchronized (this) {
            if (!started) {
                try {
                    instanceStrategy.start();
                } catch (UnavailableException e) {
                    handleUnavailableException(e);
                }
                started = true;
            }
        }
    }
}
 
Example #13
Source File: ManagedServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public void handleUnavailableException(UnavailableException e) {
    if (e.isPermanent()) {
        UndertowServletLogger.REQUEST_LOGGER.stoppingServletDueToPermanentUnavailability(getServletInfo().getName(), e);
        stop();
        setPermanentlyUnavailable(true);
    } else {
        long until = System.currentTimeMillis() + e.getUnavailableSeconds() * 1000;
        unavailableUntilUpdater.set(this, until);
        UndertowServletLogger.REQUEST_LOGGER.stoppingServletUntilDueToTemporaryUnavailability(getServletInfo().getName(), new Date(until), e);
    }
}
 
Example #14
Source File: VoiceXmlSnippet.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void init() throws ServletException {
    super.init();

    final DocumentBuilderFactory factory =
            DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    // Configure the factory to ignore comments
    factory.setIgnoringComments(true);
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new ServletException(e.getMessage(), e);
    }
    TransformerFactory transFact = TransformerFactory.newInstance( );
    try {
        final ServletContext context = getServletContext();
        final URL xsltURL = context.getResource("/VoiceXmlPromptTemplate.xsl");
        final String xsltSystemID = xsltURL.toExternalForm();
        promptTemplate = transFact.newTemplates(
                new StreamSource(xsltSystemID));
    } catch (TransformerConfigurationException tce) {
        throw new UnavailableException("Unable to compile stylesheet");
    } catch (MalformedURLException mue) {
        throw new UnavailableException("Unable to locate XSLT file");
    }
}
 
Example #15
Source File: InterfaceX_EngineSideServer.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void init() throws ServletException {
    ServletContext context = getServletContext();

    try {
        // get reference to engine
        _engine = (EngineGateway) context.getAttribute("engine");
        if (_engine == null) {

            // turn on persistence if required
            String persistOn = context.getInitParameter("EnablePersistence");
            boolean persist = "true".equalsIgnoreCase(persistOn);
            _engine = new EngineGatewayImpl(persist);
            context.setAttribute("engine", _engine);
        }
        // add interface X monitoring if required
        String listenerURI = context.getInitParameter("InterfaceXListener");
        if (listenerURI != null) {
            for (String uri : listenerURI.split(";")) {
                _engine.addInterfaceXListener(uri);
            }    
        }

    }
    catch (YPersistenceException e) {
        logger.fatal("Failure to initialise runtime (persistence failure)", e);
        throw new UnavailableException("Persistence failure");
    }
}
 
Example #16
Source File: ManagedServlet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void handleUnavailableException(UnavailableException e) {
    if (e.isPermanent()) {
        UndertowServletLogger.REQUEST_LOGGER.stoppingServletDueToPermanentUnavailability(getServletInfo().getName(), e);
        stop();
        setPermanentlyUnavailable(true);
    } else {
        long until = System.currentTimeMillis() + e.getUnavailableSeconds() * 1000;
        unavailableUntilUpdater.set(this, until);
        UndertowServletLogger.REQUEST_LOGGER.stoppingServletUntilDueToTemporaryUnavailability(getServletInfo().getName(), new Date(until), e);
    }
}
 
Example #17
Source File: SpaceUtils.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int compare(Space o1, Space o2) {

    Integer buildingCheck;
    try {
        buildingCheck = checkObjects(getSpaceBuilding(o1), getSpaceBuilding(o2));
        if (buildingCheck != null) {
            return buildingCheck.intValue();
        }

        Integer campusCheck = checkObjects(getSpaceCampus(o1), getSpaceCampus(o2));
        if (campusCheck != null) {
            return campusCheck.intValue();
        }

        Integer floorCheck = checkObjects(getSpaceFloorWithIntermediary(o1), getSpaceFloorWithIntermediary(o2));
        if (floorCheck != null) {
            return floorCheck.intValue();
        }

        int compareTo = o1.getName().compareTo(o2.getName());
        if (compareTo == 0) {
            return o1.getExternalId().compareTo(o2.getExternalId());
        }
        return compareTo;
    } catch (UnavailableException e1) {
        return -1;
    }
}
 
Example #18
Source File: HttpServletResponseWrapper.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public int statusCode() {
  int result = ServletRuntime.get().status(response);
  if (caught != null && result == 200) { // We may have a potentially bad status due to defaults
    // Servlet only seems to define one exception that has a built-in code. Logic in Jetty
    // defaults the status to 500 otherwise.
    if (caught instanceof UnavailableException) {
      return ((UnavailableException) caught).isPermanent() ? 404 : 503;
    }
    return 500;
  }
  return result;
}
 
Example #19
Source File: UnavailableServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    if(config.getInitParameter(PERMANENT) != null) {
        throw new UnavailableException("msg");
    } else if(first){
        first = false;
        throw new UnavailableException("msg", 1);
    }
}
 
Example #20
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {

    if (getServletConfig().getInitParameter("debug") != null)
        debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));

    if (getServletConfig().getInitParameter("input") != null)
        input = Integer.parseInt(getServletConfig().getInitParameter("input"));

    if (getServletConfig().getInitParameter("output") != null)
        output = Integer.parseInt(getServletConfig().getInitParameter("output"));

    listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings"));

    if (getServletConfig().getInitParameter("readonly") != null)
        readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly"));

    compressionFormats = parseCompressionFormats(
            getServletConfig().getInitParameter("precompressed"),
            getServletConfig().getInitParameter("gzip"));

    if (getServletConfig().getInitParameter("sendfileSize") != null)
        sendfileSize =
            Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024;

    fileEncoding = getServletConfig().getInitParameter("fileEncoding");
    if (fileEncoding == null) {
        fileEncodingCharset = Charset.defaultCharset();
        fileEncoding = fileEncodingCharset.name();
    } else {
        try {
            fileEncodingCharset = B2CConverter.getCharset(fileEncoding);
        } catch (UnsupportedEncodingException e) {
            throw new ServletException(e);
        }
    }

    if (getServletConfig().getInitParameter("useBomIfPresent") != null)
        useBomIfPresent = Boolean.parseBoolean(
                getServletConfig().getInitParameter("useBomIfPresent"));

    globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
    contextXsltFile = getServletConfig().getInitParameter("contextXsltFile");
    localXsltFile = getServletConfig().getInitParameter("localXsltFile");
    readmeFile = getServletConfig().getInitParameter("readmeFile");

    if (getServletConfig().getInitParameter("useAcceptRanges") != null)
        useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges"));

    // Sanity check on the specified buffer sizes
    if (input < 256)
        input = 256;
    if (output < 256)
        output = 256;

    if (debug > 0) {
        log("DefaultServlet.init:  input buffer size=" + input +
            ", output buffer size=" + output);
    }

    // Load the web resources
    resources = (WebResourceRoot) getServletContext().getAttribute(
            Globals.RESOURCES_ATTR);

    if (resources == null) {
        throw new UnavailableException(sm.getString("defaultServlet.noResources"));
    }

    if (getServletConfig().getInitParameter("showServerInfo") != null) {
        showServerInfo = Boolean.parseBoolean(getServletConfig().getInitParameter("showServerInfo"));
    }

    if (getServletConfig().getInitParameter("sortListings") != null) {
        sortListings = Boolean.parseBoolean(getServletConfig().getInitParameter("sortListings"));

        if(sortListings) {
            boolean sortDirectoriesFirst;
            if (getServletConfig().getInitParameter("sortDirectoriesFirst") != null) {
                sortDirectoriesFirst = Boolean.parseBoolean(getServletConfig().getInitParameter("sortDirectoriesFirst"));
            } else {
                sortDirectoriesFirst = false;
            }

            sortManager = new SortManager(sortDirectoriesFirst);
        }
    }

    if (getServletConfig().getInitParameter("allowPartialPut") != null) {
        allowPartialPut = Boolean.parseBoolean(getServletConfig().getInitParameter("allowPartialPut"));
    }
}
 
Example #21
Source File: DefaultServlet.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {

    if (getServletConfig().getInitParameter("debug") != null)
        debug = Integer.parseInt(getServletConfig().getInitParameter("debug"));

    if (getServletConfig().getInitParameter("input") != null)
        input = Integer.parseInt(getServletConfig().getInitParameter("input"));

    if (getServletConfig().getInitParameter("output") != null)
        output = Integer.parseInt(getServletConfig().getInitParameter("output"));

    listings = Boolean.parseBoolean(getServletConfig().getInitParameter("listings"));

    if (getServletConfig().getInitParameter("readonly") != null)
        readOnly = Boolean.parseBoolean(getServletConfig().getInitParameter("readonly"));

    if (getServletConfig().getInitParameter("sendfileSize") != null)
        sendfileSize =
            Integer.parseInt(getServletConfig().getInitParameter("sendfileSize")) * 1024;

    fileEncoding = getServletConfig().getInitParameter("fileEncoding");

    globalXsltFile = getServletConfig().getInitParameter("globalXsltFile");
    contextXsltFile = getServletConfig().getInitParameter("contextXsltFile");
    localXsltFile = getServletConfig().getInitParameter("localXsltFile");
    readmeFile = getServletConfig().getInitParameter("readmeFile");

    if (getServletConfig().getInitParameter("useAcceptRanges") != null)
        useAcceptRanges = Boolean.parseBoolean(getServletConfig().getInitParameter("useAcceptRanges"));

    // Sanity check on the specified buffer sizes
    if (input < 256)
        input = 256;
    if (output < 256)
        output = 256;

    if (debug > 0) {
        log("DefaultServlet.init:  input buffer size=" + input +
            ", output buffer size=" + output);
    }

    // Load the proxy dir context.
    resources = (ProxyDirContext) getServletContext()
        .getAttribute(Globals.RESOURCES_ATTR);
    if (resources == null) {
        try {
            resources =
                (ProxyDirContext) new InitialContext()
                .lookup(RESOURCES_JNDI_NAME);
        } catch (NamingException e) {
            // Failed
            throw new ServletException("No resources", e);
        }
    }

    if (resources == null) {
        throw new UnavailableException("No resources");
    }

    if (getServletConfig().getInitParameter("showServerInfo") != null) {
        showServerInfo = Boolean.parseBoolean(getServletConfig().getInitParameter("showServerInfo"));
    }
}
 
Example #22
Source File: SpaceUtils.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static Space getSpaceFloorWithIntermediary(Space space) throws UnavailableException {
    if (isFloor(space)) {
        return space;
    }
    return space.getParent() == null ? null : getSpaceFloorWithIntermediary(space.getParent());
}
 
Example #23
Source File: InterfaceB_EngineBasedServer.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void init() throws ServletException {
    int maxWaitSeconds = 5;                             // a default

    try {
        ServletContext context = getServletContext();

        // set the path to external db gateway plugin classes (if any)
        String pluginPath = context.getInitParameter("ExternalPluginsPath");
        ExternalDataGatewayFactory.setExternalPaths(pluginPath);
        PredicateEvaluatorFactory.setExternalPaths(pluginPath);

        // init engine reference
        _engine = (EngineGateway) context.getAttribute("engine");
        if (_engine == null) {
            Class<? extends YEngine> engineImpl = getEngineImplClass();
            boolean persist = getBooleanFromContext("EnablePersistence");
            boolean enableHbnStats = getBooleanFromContext("EnableHibernateStatisticsGathering");
            boolean redundantMode = getBooleanFromContext("StartInRedundantMode");
            _engine = new EngineGatewayImpl(engineImpl, persist,
                    enableHbnStats, redundantMode);
            _engine.setActualFilePath(context.getRealPath("/"));
            context.setAttribute("engine", _engine);
        }

        // enable performance statistics gathering if requested
        _gatherPerfStats = getBooleanFromContext("EnablePerformanceStatisticsGathering");

        // set flag to disable logging (only if false) - enabled with persistence by
        // default
        String logStr = context.getInitParameter("EnableLogging");
        if ((logStr != null) && logStr.equalsIgnoreCase("false")) {
            _engine.disableLogging();
        }

        // add the reference to the default worklist
        _engine.setDefaultWorklist(context.getInitParameter("DefaultWorklist"));

        // set flag for generic admin account (only if set to true)
        String allowAdminID = context.getInitParameter("AllowGenericAdminID");
        if ((allowAdminID != null) && allowAdminID.equalsIgnoreCase("true")) {
            _engine.setAllowAdminID(true);
        }

        // override the max time that initialisation events wait for between
        // final engine init and server start completion
        int maxWait = StringUtil.strToInt(
                context.getInitParameter("InitialisationAnnouncementTimeout"), -1);
        if (maxWait >= 0) maxWaitSeconds = maxWait;

        // set the country/region codes used for calculating work-day-only timers (if any)
        String timerLocationConfig = context.getInitParameter("WorkdayTimerGeoCodes");
        if (timerLocationConfig != null) {
            new HolidayLoader(false).startupCheck(timerLocationConfig);
        }

        // read the current version properties
        _engine.initBuildProperties(context.getResourceAsStream(
                           "/WEB-INF/classes/version.properties"));

        // init any 3rd party observer gateways
        String gatewayStr = context.getInitParameter("ObserverGateway");
        if (gatewayStr != null) {

            // split multiples on the semi-colon (if any)
            for (String gateway : gatewayStr.split(";")) {
                registerObserverGateway(gateway);
            }
        }
    }
    catch (YPersistenceException e) {
        _log.fatal("Failure to initialise runtime (persistence failure)", e);
        throw new UnavailableException("Persistence failure");
    }

    if (_engine != null) {
        _engine.notifyServletInitialisationComplete(maxWaitSeconds);
    }
    else {
        _log.fatal("Failed to initialise Engine (unspecified failure). Please " +
                "consult the logs for details");
        throw new UnavailableException("Unspecified engine failure");
    }
}
 
Example #24
Source File: ITSpanCustomizingHandlerInterceptor.java    From brave with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/exception")
public void notReady() throws UnavailableException {
  throw NOT_READY_UE;
}
 
Example #25
Source File: UndertowServletLogger.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@LogMessage(level = ERROR)
@Message(id = 15002, value = "Stopping servlet %s due to permanent unavailability")
void stoppingServletDueToPermanentUnavailability(final String servlet, @Cause UnavailableException e);
 
Example #26
Source File: Servlet25TestController.java    From brave with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(value = HttpStatus.SERVICE_UNAVAILABLE)
@RequestMapping(value = "/exception")
public ResponseEntity<Void> notReady() throws UnavailableException {
  throw NOT_READY_UE;
}
 
Example #27
Source File: UndertowServletLogger.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@LogMessage(level = ERROR)
@Message(id = 15003, value = "Stopping servlet %s till %s due to temporary unavailability")
void stoppingServletUntilDueToTemporaryUnavailability(String name, Date till, @Cause UnavailableException e);
 
Example #28
Source File: LastaPrepareFilter.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected void initModuleConfig(ServletContext servletContext) throws UnavailableException {
    servletContext.setAttribute(LastaWebKey.MODULE_CONFIG_KEY, newModuleConfig());
}
 
Example #29
Source File: ServletHandler.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws IOException, ServletException {
    if (managedServlet.isPermanentlyUnavailable()) {
        UndertowServletLogger.REQUEST_LOGGER.debugf("Returning 404 for servlet %s due to permanent unavailability", managedServlet.getServletInfo().getName());
        exchange.setStatusCode(StatusCodes.NOT_FOUND);
        return;
    }

    if (managedServlet.isTemporarilyUnavailable()) {
        UndertowServletLogger.REQUEST_LOGGER.debugf("Returning 503 for servlet %s due to temporary unavailability", managedServlet.getServletInfo().getName());
        exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        return;
    }
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if(!managedServlet.getServletInfo().isAsyncSupported()) {
        servletRequestContext.setAsyncSupported(false);
    }
    ServletRequest request = servletRequestContext.getServletRequest();
    ServletResponse response = servletRequestContext.getServletResponse();
    InstanceHandle<? extends Servlet> servlet = null;
    try {
        servlet = managedServlet.getServlet();
        servlet.getInstance().service(request, response);

        //according to the spec we have to call AsyncContext.complete() at this point
        //straight after the service method
        //not super sure about this, surely it would make more sense to do this when the request has returned to the container, however the spec is quite clear wording wise
        //todo: should we actually enable this? Apparently other containers do not do it
        //if(!request.isAsyncStarted()) {
        //    AsyncContextImpl existingAsyncContext = servletRequestContext.getOriginalRequest().getAsyncContextInternal();
        //    if (existingAsyncContext != null) {
        //        existingAsyncContext.complete();
        //    }
        //}
    } catch (UnavailableException e) {
        managedServlet.handleUnavailableException(e);
        if (e.isPermanent()) {
            exchange.setStatusCode(StatusCodes.NOT_FOUND);
        } else {
            exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
        }
    } finally {
        if(servlet != null) {
            servlet.release();
        }
    }
}
 
Example #30
Source File: SolrDispatchFilter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain, boolean retry) throws IOException, ServletException {
  if (!(_request instanceof HttpServletRequest)) return;
  HttpServletRequest request = closeShield((HttpServletRequest)_request, retry);
  HttpServletResponse response = closeShield((HttpServletResponse)_response, retry);
  Scope scope = null;
  Span span = null;
  try {

    if (cores == null || cores.isShutDown()) {
      try {
        init.await();
      } catch (InterruptedException e) { //well, no wait then
      }
      final String msg = "Error processing the request. CoreContainer is either not initialized or shutting down.";
      if (cores == null || cores.isShutDown()) {
        log.error(msg);
        throw new UnavailableException(msg);
      }
    }

    String requestPath = ServletUtils.getPathAfterContext(request);
    // No need to even create the HttpSolrCall object if this path is excluded.
    if (excludePatterns != null) {
      for (Pattern p : excludePatterns) {
        Matcher matcher = p.matcher(requestPath);
        if (matcher.lookingAt()) {
          chain.doFilter(request, response);
          return;
        }
      }
    }

    SpanContext parentSpan = GlobalTracer.get().extract(request);
    Tracer tracer = GlobalTracer.getTracer();

    Tracer.SpanBuilder spanBuilder = null;
    String hostAndPort = request.getServerName() + "_" + request.getServerPort();
    if (parentSpan == null) {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort);
    } else {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort)
          .asChildOf(parentSpan);
    }

    spanBuilder
        .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
        .withTag(Tags.HTTP_URL.getKey(), request.getRequestURL().toString());
    span = spanBuilder.start();
    scope = tracer.scopeManager().activate(span);

    AtomicReference<HttpServletRequest> wrappedRequest = new AtomicReference<>();
    if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been sent
      return;
    }
    if (wrappedRequest.get() != null) {
      request = wrappedRequest.get();
    }

    if (cores.getAuthenticationPlugin() != null) {
      if (log.isDebugEnabled()) {
        log.debug("User principal: {}", request.getUserPrincipal());
      }
    }

    HttpSolrCall call = getHttpSolrCall(request, response, retry);
    ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
    try {
      Action result = call.call();
      switch (result) {
        case PASSTHROUGH:
          chain.doFilter(request, response);
          break;
        case RETRY:
          doFilter(request, response, chain, true); // RECURSION
          break;
        case FORWARD:
          request.getRequestDispatcher(call.getPath()).forward(request, response);
          break;
        case ADMIN:
        case PROCESS:
        case REMOTEQUERY:
        case RETURN:
          break;
      }
    } finally {
      call.destroy();
      ExecutorUtil.setServerThreadFlag(null);
    }
  } finally {
    if (span != null) span.finish();
    if (scope != null) scope.close();

    GlobalTracer.get().clearContext();
    consumeInputFully(request, response);
    SolrRequestInfo.reset();
    SolrRequestParsers.cleanupMultipartFiles(request);
  }
}