Search in sources :

Example 6 with SimpleTimeLimiter

use of com.google.common.util.concurrent.SimpleTimeLimiter in project eclipse.jdt.ls by eclipse.

the class CompletionResolveHandler method resolve.

public CompletionItem resolve(CompletionItem param, IProgressMonitor monitor) {
    @SuppressWarnings("unchecked") Map<String, String> data = JSONUtility.toModel(param.getData(), Map.class);
    // clean resolve data
    param.setData(null);
    if (!data.containsKey(DATA_FIELD_URI) || !data.containsKey(DATA_FIELD_REQUEST_ID) || !data.containsKey(DATA_FIELD_PROPOSAL_ID)) {
        return param;
    }
    int proposalId = Integer.parseInt(data.get(DATA_FIELD_PROPOSAL_ID));
    long requestId = Long.parseLong(data.get(DATA_FIELD_REQUEST_ID));
    CompletionResponse completionResponse = CompletionResponses.get(requestId);
    if (completionResponse == null || completionResponse.getProposals().size() <= proposalId) {
        throw new IllegalStateException("Invalid completion proposal");
    }
    String uri = data.get(DATA_FIELD_URI);
    ICompilationUnit unit = JDTUtils.resolveCompilationUnit(uri);
    if (unit == null) {
        throw new IllegalStateException(NLS.bind("Unable to match Compilation Unit from {0} ", uri));
    }
    CompletionProposalReplacementProvider proposalProvider = new CompletionProposalReplacementProvider(unit, completionResponse.getContext(), completionResponse.getOffset(), this.manager.getClientPreferences());
    proposalProvider.updateReplacement(completionResponse.getProposals().get(proposalId), param, '\0');
    if (monitor.isCanceled()) {
        param.setData(null);
        return param;
    }
    if (data.containsKey(DATA_FIELD_DECLARATION_SIGNATURE)) {
        String typeName = stripSignatureToFQN(String.valueOf(data.get(DATA_FIELD_DECLARATION_SIGNATURE)));
        try {
            IMember member = null;
            IType type = unit.getJavaProject().findType(typeName);
            if (type != null && data.containsKey(DATA_FIELD_NAME)) {
                String name = data.get(DATA_FIELD_NAME);
                String[] paramSigs = CharOperation.NO_STRINGS;
                if (data.containsKey(DATA_FIELD_SIGNATURE)) {
                    String[] parameters = Signature.getParameterTypes(String.valueOf(fix83600(data.get(DATA_FIELD_SIGNATURE).toCharArray())));
                    for (int i = 0; i < parameters.length; i++) {
                        parameters[i] = getLowerBound(parameters[i]);
                    }
                    paramSigs = parameters;
                }
                IMethod method = type.getMethod(name, paramSigs);
                if (method.exists()) {
                    member = method;
                } else {
                    IField field = type.getField(name);
                    if (field.exists()) {
                        member = field;
                    }
                }
            } else {
                member = type;
            }
            if (member != null && member.exists() && !monitor.isCanceled()) {
                String javadoc = null;
                try {
                    final IMember curMember = member;
                    javadoc = new SimpleTimeLimiter().callWithTimeout(() -> {
                        Reader reader = JavadocContentAccess.getPlainTextContentReader(curMember);
                        return reader == null ? null : CharStreams.toString(reader);
                    }, 500, TimeUnit.MILLISECONDS, true);
                } catch (UncheckedTimeoutException tooSlow) {
                    // Ignore error for now as it's spamming clients on content assist.
                    // TODO cache javadoc resolution results?
                    // JavaLanguageServerPlugin.logError("Unable to get documentation under 500ms");
                    monitor.setCanceled(true);
                } catch (Exception e) {
                    JavaLanguageServerPlugin.logException("Unable to read documentation", e);
                    monitor.setCanceled(true);
                }
                param.setDocumentation(javadoc);
            }
        } catch (JavaModelException e) {
            JavaLanguageServerPlugin.logException("Unable to resolve compilation", e);
            monitor.setCanceled(true);
        }
    }
    if (monitor.isCanceled()) {
        param.setData(null);
    }
    return param;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) Reader(java.io.Reader) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) IField(org.eclipse.jdt.core.IField) IMember(org.eclipse.jdt.core.IMember) JavaModelException(org.eclipse.jdt.core.JavaModelException) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) IType(org.eclipse.jdt.core.IType) CompletionProposalReplacementProvider(org.eclipse.jdt.ls.core.internal.contentassist.CompletionProposalReplacementProvider) IMethod(org.eclipse.jdt.core.IMethod) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter)

Example 7 with SimpleTimeLimiter

use of com.google.common.util.concurrent.SimpleTimeLimiter in project Openfire by igniterealtime.

the class XMPPServer method shutdownServer.

/**
 * Makes a best effort attempt to shutdown the server
 */
private void shutdownServer() {
    shuttingDown = true;
    if (terminatorTimer != null) {
        terminatorTimer.cancel();
    }
    ClusterManager.shutdown();
    // Notify server listeners that the server is about to be stopped
    for (XMPPServerListener listener : listeners) {
        try {
            listener.serverStopping();
        } catch (Exception ex) {
            logger.error("Exception during listener shutdown", ex);
        }
    }
    // If we don't have modules then the server has already been shutdown
    if (modules.isEmpty()) {
        return;
    }
    // Stop all plugins
    logger.info("Shutting down plugins ...");
    if (pluginManager != null) {
        try {
            pluginManager.shutdown();
        } catch (Exception ex) {
            logger.error("Exception during plugin shutdown", ex);
        }
    }
    logger.info("Shutting down " + modules.size() + " modules ...");
    final SimpleTimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("shutdown-thread-%d").build()));
    // OF-1996" Get all modules and stop and destroy them. Do this in the reverse order in which the were created.
    // This ensures that the 'most important' / core modules are shut down last, giving other modules the
    // opportunity to make use of their functionality during their shutdown (eg: MUC wants to send messages during
    // shutdown).
    final List<Class> reverseInsertionOrder = new ArrayList<>(modules.keySet());
    Collections.reverse(reverseInsertionOrder);
    for (final Class moduleClass : reverseInsertionOrder) {
        final Module module = modules.get(moduleClass);
        try {
            // OF-1607: Apply a configurable timeout to the duration of stop/destroy invocation.
            timeLimiter.runWithTimeout(() -> {
                stopAndDestroyModule(module);
            }, JiveGlobals.getLongProperty("shutdown.modules.timeout-millis", Long.MAX_VALUE), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            logger.warn("An exception occurred while stopping / destroying module '{}'.", module.getName(), e);
            System.err.println(e);
        }
    }
    modules.clear();
    // Stop the Db connection manager.
    try {
        DbConnectionManager.destroyConnectionProvider();
    } catch (Exception ex) {
        logger.error("Exception during DB shutdown", ex);
    }
    // Shutdown the task engine.
    TaskEngine.getInstance().shutdown();
    // hack to allow safe stopping
    logger.info("Openfire stopped");
    // Shut down the logging framework (causing the last few log entries to be flushed)
    LogManager.shutdown();
}
Also used : CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) PubSubModule(org.jivesoftware.openfire.pubsub.PubSubModule) Module(org.jivesoftware.openfire.container.Module) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException)

Example 8 with SimpleTimeLimiter

use of com.google.common.util.concurrent.SimpleTimeLimiter in project presto by prestodb.

the class QueryRewriter method getColumns.

private List<Column> getColumns(Connection connection, CreateTableAsSelect createTableAsSelect) throws SQLException {
    com.facebook.presto.sql.tree.Query createSelectClause = createTableAsSelect.getQuery();
    // Rewrite the query to select zero rows, so that we can get the column names and types
    QueryBody innerQuery = createSelectClause.getQueryBody();
    com.facebook.presto.sql.tree.Query zeroRowsQuery;
    if (innerQuery instanceof QuerySpecification) {
        QuerySpecification querySpecification = (QuerySpecification) innerQuery;
        innerQuery = new QuerySpecification(querySpecification.getSelect(), querySpecification.getFrom(), querySpecification.getWhere(), querySpecification.getGroupBy(), querySpecification.getHaving(), querySpecification.getOrderBy(), Optional.of("0"));
        zeroRowsQuery = new com.facebook.presto.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.empty());
    } else {
        zeroRowsQuery = new com.facebook.presto.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.of("0"));
    }
    ImmutableList.Builder<Column> columns = ImmutableList.builder();
    try (java.sql.Statement jdbcStatement = connection.createStatement()) {
        TimeLimiter limiter = new SimpleTimeLimiter();
        java.sql.Statement limitedStatement = limiter.newProxy(jdbcStatement, java.sql.Statement.class, timeout.toMillis(), TimeUnit.MILLISECONDS);
        try (ResultSet resultSet = limitedStatement.executeQuery(formatSql(zeroRowsQuery, Optional.empty()))) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String name = metaData.getColumnName(i);
                int type = metaData.getColumnType(i);
                columns.add(new Column(name, APPROXIMATE_TYPES.contains(type)));
            }
        }
    }
    return columns.build();
}
Also used : SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) TimeLimiter(com.google.common.util.concurrent.TimeLimiter) ImmutableList(com.google.common.collect.ImmutableList) ResultSetMetaData(java.sql.ResultSetMetaData) QuerySpecification(com.facebook.presto.sql.tree.QuerySpecification) SingleColumn(com.facebook.presto.sql.tree.SingleColumn) ResultSet(java.sql.ResultSet) QueryBody(com.facebook.presto.sql.tree.QueryBody) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter)

Example 9 with SimpleTimeLimiter

use of com.google.common.util.concurrent.SimpleTimeLimiter in project graylog2-server by Graylog2.

the class LdapConnector method connect.

public LdapNetworkConnection connect(LdapConnectionConfig config) throws LdapException {
    final LdapNetworkConnection connection = new LdapNetworkConnection(config);
    connection.setTimeOut(connectionTimeout);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Connecting to LDAP server {}:{}, binding with user {}", config.getLdapHost(), config.getLdapPort(), config.getName());
    }
    // this will perform an anonymous bind if there were no system credentials
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("ldap-connector-%d").build();
    final SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter(Executors.newSingleThreadExecutor(threadFactory));
    @SuppressWarnings("unchecked") final Callable<Boolean> timeLimitedConnection = timeLimiter.newProxy(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return connection.connect();
        }
    }, Callable.class, connectionTimeout, TimeUnit.MILLISECONDS);
    try {
        final Boolean connected = timeLimitedConnection.call();
        if (!connected) {
            return null;
        }
    } catch (UncheckedTimeoutException e) {
        LOG.error("Timed out connecting to LDAP server", e);
        throw new LdapException("Could not connect to LDAP server", e.getCause());
    } catch (LdapException e) {
        throw e;
    } catch (Exception e) {
        // unhandled different exception, should really not happen here.
        throw new LdapException("Unexpected error connecting to LDAP", e);
    }
    connection.bind();
    return connection;
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) IOException(java.io.IOException) LdapInvalidDnException(org.apache.directory.api.ldap.model.exception.LdapInvalidDnException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 10 with SimpleTimeLimiter

use of com.google.common.util.concurrent.SimpleTimeLimiter in project etcd-java by IBM.

the class EtcdTestSuite method waitForStartup.

static void waitForStartup() throws Exception {
    if (etcdProcess == null)
        return;
    TimeLimiter tl = new SimpleTimeLimiter();
    tl.callWithTimeout(() -> {
        Reader isr = new InputStreamReader(etcdProcess.getErrorStream());
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null && !line.contains("ready to serve client requests")) {
            System.out.println(line);
        }
        return null;
    }, 10L, TimeUnit.SECONDS, true);
}
Also used : SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter) TimeLimiter(com.google.common.util.concurrent.TimeLimiter) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) SimpleTimeLimiter(com.google.common.util.concurrent.SimpleTimeLimiter)

Aggregations

SimpleTimeLimiter (com.google.common.util.concurrent.SimpleTimeLimiter)11 TimeLimiter (com.google.common.util.concurrent.TimeLimiter)6 UncheckedTimeoutException (com.google.common.util.concurrent.UncheckedTimeoutException)5 IOException (java.io.IOException)5 Reader (java.io.Reader)3 ImmutableList (com.google.common.collect.ImmutableList)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)2 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)2 IMethod (org.eclipse.jdt.core.IMethod)2 IType (org.eclipse.jdt.core.IType)2 JavaModelException (org.eclipse.jdt.core.JavaModelException)2 IExpr (org.matheclipse.core.interfaces.IExpr)2 MathException (org.matheclipse.parser.client.math.MathException)2 PrestoConnection (com.facebook.presto.jdbc.PrestoConnection)1 PrestoStatement (com.facebook.presto.jdbc.PrestoStatement)1 QueryStats (com.facebook.presto.jdbc.QueryStats)1 QueryBody (com.facebook.presto.sql.tree.QueryBody)1 QuerySpecification (com.facebook.presto.sql.tree.QuerySpecification)1 SingleColumn (com.facebook.presto.sql.tree.SingleColumn)1 State (com.facebook.presto.verifier.QueryResult.State)1