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;
}
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();
}
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();
}
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;
}
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);
}
Aggregations