/*
This method manages the whitelist of all acceptable Throwables (and Exceptions) that
will not cause the Server harm if they occur while invoking the initializer of a stored
procedure or while calling the stored procedure.
437809
public static final boolean isStoredProcThrowableFatalToServer(Throwable th) {
        if (th instanceof LinkageError || th instanceof AssertionError) {
            return false;
        }
        if (th instanceof Exception) {
            return false;
        }
        return true;
    }
225176
void checkThrown() throws SSLException {
        synchronized (thrownLock) {
            if (thrown != null) {

                String msg = thrown.getMessage();

                if (msg == null) {
                    msg = "Delegated task threw Exception/Error";
                }

                /*
                 * See what the underlying type of exception is.  We should
                 * throw the same thing.  Chain thrown to the new exception.
                 */
                Exception e = thrown;
                thrown = null;

                if (e instanceof RuntimeException) {
                    throw (RuntimeException)
                        new RuntimeException(msg).initCause(e);
                } else if (e instanceof SSLHandshakeException) {
                    throw (SSLHandshakeException)
                        new SSLHandshakeException(msg).initCause(e);
                } else if (e instanceof SSLKeyException) {
                    throw (SSLKeyException)
                        new SSLKeyException(msg).initCause(e);
                } else if (e instanceof SSLPeerUnverifiedException) {
                    throw (SSLPeerUnverifiedException)
                        new SSLPeerUnverifiedException(msg).initCause(e);
                } else if (e instanceof SSLProtocolException) {
                    throw (SSLProtocolException)
                        new SSLProtocolException(msg).initCause(e);
                } else {
                    /*
                     * If it's SSLException or any other Exception,
                     * we'll wrap it in an SSLException.
                     */
                    throw (SSLException)
                        new SSLException(msg).initCause(e);
                }
            }
        }
    }
386459
protected final void checkIntegrity () throws InternetSCSIException {

        String exceptionMessage = "";
        switch (t) {
            case OUI_FORMAT :
                break;

            case IANA_ENTERPRISE_NUMBER :
                break;

            case RANDOM :
//                if (d != 0) {
//                    exceptionMessage = "The D field is reserved in this ISID Format.";
//                }
                break;

            case RESERVED :
                if (a != 0 && b != 0 && c != 0 && d != 0) {
                    exceptionMessage = "This ISID is not valid. All";
                }
                break;

            default :
                exceptionMessage = "This format is not supported.";
        }

        if (exceptionMessage.length() > 0) {
            throw new InternetSCSIException(exceptionMessage);
        } else {
            // no error occured... Nice! :-)
        }
    }
524046
private static void initPrefixHandlers()
    {
        PrefixHandlerConfig[] prefixHandlers = ConfigUtil.getConfig().getPrefixHandlers();
        if ( prefixHandlers == null )
        {
            return;
        }
        for ( int i = 0; i < prefixHandlers.length; i++ )
        {
            try
            {
                Class prefixClass = Class.forName( prefixHandlers[i].getHandlerClass() );
                String name = prefixHandlers[i].getName();
                if ( name == null || name.equals( "" ) )
                {
                    _log.warn( "The name for the prefix handler '" + prefixHandlers[i].getHandlerClass()
                            + "' must not be null" );
                    continue;
                }
                Object o = prefixClass.newInstance();
                if ( !( o instanceof RequestParameterHandler ) )
                {
                    _log.warn( "The class '" + prefixHandlers[i].getHandlerClass()
                            + "' must be an instance of RequestParameterHandler" );
                    continue;
                }
                ProcessPopulate.registerPrefixHandler( name, ( RequestParameterHandler ) o );
            }
            catch ( ClassNotFoundException e )
            {
                _log.warn( "Class '" + prefixHandlers[i].getHandlerClass() + "' not found", e );
            }
            catch ( IllegalAccessException e )
            {
                _log.warn( "Illegal access on Class '" + prefixHandlers[i].getHandlerClass() + "'", e );

            }
            catch ( InstantiationException e )
            {
                _log.warn( "InstantiationException on Class '" + prefixHandlers[i].getHandlerClass() + "'",
                        e.getCause() );
            }
        }
    }
380408
@FFDCIgnore(NoSuchElementException.class)
    private void doInvalidations() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        try {
            long now = System.currentTimeMillis();

            // loop through all the candidates eligible for invalidation
            BackedSession pmiStatSession = null; // fake session for pmi stats
            SessionStatistics pmiStats = null;

            if (trace && tc.isDebugEnabled())
                tcInvoke(tcSessionMetaCache, "iterator");

            @SuppressWarnings("rawtypes")
            Iterator<Cache.Entry<String, ArrayList>> it = sessionMetaCache.iterator();

            if (trace && tc.isDebugEnabled())
                tcReturn(tcSessionMetaCache, "iterator", it);

            while (it.hasNext()) {
                if (trace && tc.isDebugEnabled())
                    tcInvoke(tcSessionMetaCache, "_iterator.next");

                @SuppressWarnings("rawtypes")
                Cache.Entry<String, ArrayList> entry;
                try {
                    entry = it.next();
                } catch (NoSuchElementException x) {
                    // ignore - some JCache providers might raise this instead of returning null when modified during iterator
                    entry = null;
                }
                String id = entry == null ? null : entry.getKey();
                ArrayList<?> value = id == null ? null : entry.getValue();

                if (trace && tc.isDebugEnabled())
                    tcReturn(tcSessionMetaCache, "_iterator.next", id, value);

                if (id != null && !INVAL_KEY.equals(id)) {
                    SessionInfo sessionInfo = new SessionInfo(value);
                    long lastAccessTime = sessionInfo.getLastAccess();
                    short listenerTypes = sessionInfo.getListenerTypes();
                    int maxInactiveTime = sessionInfo.getMaxInactiveTime();
                    if ((listenerTypes & BackedSession.HTTP_SESSION_BINDING_LISTENER) == 0 // sessions that do NOT have binding listeners
                                    && maxInactiveTime >= 0
                                    && maxInactiveTime < (now - lastAccessTime) / 1000) {
                        if (now + _smc.getInvalidationCheckInterval() * 1000 <= System.currentTimeMillis()) {
                            // If the scan is taking more than pollInterval, just break and
                            // invalidate the sessions so far determined
                            break;
                        }

                        if (trace && tc.isDebugEnabled())
                            tcInvoke(tcSessionMetaCache, "remove", id, value);

                        boolean removed = sessionMetaCache.remove(id, value);

                        if (trace && tc.isDebugEnabled())
                            tcReturn(tcSessionMetaCache, "remove", removed);

                        if (removed) {
                            //delete sub rows
                            Set<String> propIds = sessionInfo.getSessionPropertyIds();
                            if (propIds != null && !propIds.isEmpty()) {
                                HashSet<String> propKeys = new HashSet<String>();
                                for (String propId : propIds)
                                    propKeys.add(createSessionAttributeKey(id, propId));

                                if (trace && tc.isDebugEnabled())
                                    tcInvoke(tcSessionAttrCache, "removeAll", propKeys);

                                sessionAttributeCache.removeAll(propKeys);

                                if (trace && tc.isDebugEnabled())
                                    tcReturn(tcSessionAttrCache, "removeAll");
                            }
                        }

                        /*
                         * We already did cleanUpCache during the invalidation processing. Therefore, the session is no longer
                         * in our cache, and superRemove should return null. We need to create a temporary Session with an
                         * accurate Id and creationTime to send to the PMI counters.
                         */
                        superRemove(id);
                        long createTime = sessionInfo.getCreationTime();
                        //we don't want to retrieve session, so use a fake one for pmi
                        if (pmiStatSession == null)
                            pmiStatSession = new CacheSession();
                        if (pmiStats == null)
                            pmiStats = _iStore.getSessionStatistics();
                        pmiStatSession.setId(id);
                        pmiStatSession.setCreationTime(createTime);
                        if (pmiStats != null) {
                            pmiStats.sessionDestroyed(pmiStatSession);
                            pmiStats.sessionDestroyedByTimeout(pmiStatSession);
                        }
                    }
                }
            }
        } catch (Exception x) {
            // auto FFDC
            Tr.error(tc, "ERROR_SESSION_INVAL", x);
        }
    }
605233
@SuppressWarnings("unchecked")
    private ImmutableMap<String, ProcedureRunnerNTGenerator> loadSystemProcedures(boolean startup) {
        ImmutableMap.Builder<String, ProcedureRunnerNTGenerator> builder =
                ImmutableMap.<String, ProcedureRunnerNTGenerator>builder();

        Set<Entry<String,Config>> entrySet = SystemProcedureCatalog.listing.entrySet();
        for (Entry<String, Config> entry : entrySet) {
            String procName = entry.getKey();
            Config sysProc = entry.getValue();

            // transactional sysprocs handled by LoadedProcedureSet
            if (sysProc.transactional) {
                continue;
            }

            final String className = sysProc.getClassname();
            Class<? extends VoltNonTransactionalProcedure> procClass = null;

            // this check is for sysprocs that don't have a procedure class
            if (className != null) {
                try {
                    procClass = (Class<? extends VoltNonTransactionalProcedure>) Class.forName(className);
                }
                catch (final ClassNotFoundException e) {
                    if (sysProc.commercial) {
                        continue;
                    }
                    VoltDB.crashLocalVoltDB("Missing Java class for NT System Procedure: " + procName);
                }

                if (startup) {
                    // This is a startup-time check to make sure we can instantiate
                    try {
                        if ((procClass.newInstance() instanceof VoltNTSystemProcedure) == false) {
                            VoltDB.crashLocalVoltDB("NT System Procedure is incorrect class type: " + procName);
                        }
                    }
                    catch (InstantiationException | IllegalAccessException e) {
                        VoltDB.crashLocalVoltDB("Unable to instantiate NT System Procedure: " + procName);
                    }
                }

                ProcedureRunnerNTGenerator prntg = new ProcedureRunnerNTGenerator(procClass);
                builder.put(procName, prntg);
            }
        }
        return builder.build();
    }
699106
public static void ensureValidBindAddresses(List<Protocol> protocols) throws Exception {
        for(Protocol protocol : protocols) {
            String protocolName=protocol.getName();

            //traverse class hierarchy and find all annotated fields and add them to the list if annotated
            Field[] fields=Util.getAllDeclaredFieldsWithAnnotations(protocol.getClass(), LocalAddress.class);
            for(int i=0; i < fields.length; i++) {
                Object val=getValueFromProtocol(protocol, fields[i]);
                if(val == null)
                    continue;
                if(!(val instanceof InetAddress))
                    throw new Exception("field " + protocolName + "." + fields[i].getName() + " is not an InetAddress");
                Util.checkIfValidAddress((InetAddress)val, protocolName);
            }
        }
    }
1006943
@Override
    public void init(NamedList args) {

        Object regex = args.remove(PARAM_REGEX);
        if (null == regex) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REGEX);
        }
        try {
            m_regex = Pattern.compile(regex.toString());
        } catch (PatternSyntaxException e) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Invalid regex: " + regex, e);
        }

        Object replacement = args.remove(PARAM_REPLACEMENT);
        if (null == replacement) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_REPLACEMENT);
        }
        m_replacement = replacement.toString();

        Object source = args.remove(PARAM_SOURCE);
        if (null == source) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_SOURCE);
        }
        m_source = source.toString();

        Object target = args.remove(PARAM_TARGET);
        if (null == target) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Missing required init parameter: " + PARAM_TARGET);
        }
        m_target = target.toString();

    }
1308734
protected void postInit(Connection connection) throws SQLException
   {
      String select =
         "select * from " + DBInitializerHelper.getItemTableName(containerConfig) + " where ID='"
            + Constants.ROOT_PARENT_UUID + "' and PARENT_ID='" + Constants.ROOT_PARENT_UUID + "'";

      if (!connection.createStatement().executeQuery(select).next())
      {
         String insert = DBInitializerHelper.getRootNodeInitializeScript(containerConfig);
         connection.createStatement().executeUpdate(insert);
      }
   }
929385
protected void doRestore() throws Throwable
   {
      PlainChangesLog changes = read();

      TransactionChangesLog tLog = new TransactionChangesLog(changes);
      tLog.setSystemId(Constants.JCR_CORE_RESTORE_WORKSPACE_INITIALIZER_SYSTEM_ID); // mark changes

      dataManager.save(tLog);
   }
1260829
protected void closeSurrogate() throws Throwable {

        if (this.surrogateClosed) {
            return;
        }

        if (this.resultSets != null) {
            Iterator it = this.resultSets.iterator();

            // Changed to set of ResultSet invocation handlers so
            // that handler resources can be cleaned up too.
            while (it.hasNext()) {
                WrapperInvocationHandler handler =
                    (WrapperInvocationHandler) it.next();

                try {
                    ((ResultSet) handler.delegate).close();
                } catch (Exception ex) {}

                try {
                    handler.closeSurrogate();
                } catch (Exception e) {}
            }
        }

        if (this.statements != null) {
            Iterator it = this.statements.iterator();

            while (it.hasNext()) {
                WrapperInvocationHandler handler =
                    (WrapperInvocationHandler) it.next();

                try {
                    handler.closeSurrogate();
                } catch (Exception e) {}
            }
        }

        if (this.dbmdHandler != null) {
            try {
                this.dbmdHandler.closeSurrogate();
            } catch (Throwable ex) {}
        }

        Object delegate = this.delegate;

        try {
            if (delegate instanceof Connection) {
                closeConnectionSurrogate();
            } else if (delegate instanceof Statement) {
                closeStatementSurrogate();
            }
        } finally {
            this.delegate        = null;
            this.surrogate       = null;
            this.dbmdHandler     = null;
            this.parentHandler   = null;
            this.statementKey    = null;
            this.statementPool   = null;
            this.connectionPool  = null;
            this.surrogateClosed = true;
        }
    }
364029
public static void safelyIgnoreException(Throwable t)
    {
        if (t instanceof ThreadDeath)
        {
            throw (ThreadDeath) t;
        }

        if (t instanceof OutOfMemoryError)
        {
            throw (OutOfMemoryError) t;
        }

    }
684463
public static void throwSQLException(Exception cause, String theType, String value)
            throws SQLException {
        throw new SQLException("Invalid " + theType + " value: " + value, cause);
    }
186949
public void doCatch(Throwable t) throws Throwable {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                // Ignore to not hide orignal exception
            }
        }
        throw t;
    }
896380
function checkWhitelist(str, whitelist, context) {
    if (whitelist.indexOf(str) === -1) {
        throw new ImplementationError(
            'Invalid "' + str + '" (allowed: ' + whitelist.join(', ') + ')' + context.errorContext
        );
    }
    return str;
}
1266636
public static void throwServletException(Throwable cause)
            throws ServletException
    {
        ServletException servletException = new ServletException(cause);

        // todo: future cleanup
        // the servlet 2.5 api sets does the equivalent of initCause in its constructor
        // where the servlet 2.4 api does not, so check for the 2.5 behavior before setting initCause
        if (servletException.getCause() == null) {
            servletException.initCause(cause);
        }
        throw servletException;
    }
116628
@Override
    public final void before() throws Throwable {
        HostConfig.Builder hostConfigBuilder = HostConfig.builder()
                .publishAllPorts(builder.publishAllPorts())//
                .portBindings(builder.hostPortBindings())//
                .binds(builder.binds())//
                .links(links());
        if (builder.restartPolicy() != null) {
            hostConfigBuilder.restartPolicy(builder.restartPolicy().getRestartPolicy());
        }
        HostConfig hostConfig = hostConfigBuilder
                .extraHosts(builder.extraHosts())//
                .ulimits(builder.getUlimits())
                .build();
        ContainerConfig.Builder containerConfigBuilder = ContainerConfig.builder()//
                .hostConfig(hostConfig)//
                .image(imageNameWithTag)//
                .env(builder.env())//
                .networkDisabled(false)//
                .exposedPorts(builder.containerExposedPorts())
                .labels(builder.getLabels());
        if (builder.entrypoint().length > 0) {
            containerConfigBuilder.entrypoint(builder.entrypoint());
        }
        if (builder.cmd().length > 0) {
            containerConfigBuilder.cmd(builder.cmd());
        }
        ContainerConfig containerConfig = containerConfigBuilder.build();
        try {
            if (StringUtils.isNotBlank(builder.name())) {
                this.container = dockerClient.createContainer(containerConfig, builder.name());
            } else {
                this.container = dockerClient.createContainer(containerConfig);
            }

            this.containerShortId = StringUtils.left(container.id(), SHORT_ID_LEN);
            log.info("container {} created, id {}, short id {}", imageNameWithTag, container.id(), containerShortId);
            log.debug("rule before {}", containerShortId);

            dockerClient.startContainer(container.id());
            log.debug("{} started", containerShortId);

            LineListenerProxy proxyLineListener = new LineListenerProxy();
            attachLogs(dockerClient, container.id(), proxyLineListener);

            ContainerInfo containerInfo = dockerClient.inspectContainer(container.id());
            containerIp = containerInfo.networkSettings().ipAddress();
            containerPorts = containerInfo.networkSettings().ports();
            containerGateway = containerInfo.networkSettings().gateway();
            this.containerInfo = containerInfo;

            executeWaitForConditions(proxyLineListener);
            logNetworkSettings();

            isStarted = true;
        } catch (DockerRequestException e) {
            throw new IllegalStateException(e.getResponseBody(), e);
        } catch (DockerException | InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }