List of usage examples for java.util.concurrent CompletableFuture runAsync
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
From source file:acmi.l2.clientmod.l2_version_switcher.Main.java
public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>"); System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME + " 1 \"system\\*\""); System.out.println(/*from www. j ava2s. c om*/ " l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48"); System.exit(0); } List<String> argsList = new ArrayList<>(Arrays.asList(args)); String host = argsList.get(0); String game = argsList.get(1); int version = Integer.parseInt(argsList.get(2)); Helper helper = new Helper(host, game, version); boolean available = false; try { available = helper.isAvailable(); } catch (IOException e) { System.err.print(e.getClass().getSimpleName()); if (e.getMessage() != null) { System.err.print(": " + e.getMessage()); } System.err.println(); } System.out.println(String.format("Version %d available: %b", version, available)); if (!available) { System.exit(0); } List<FileInfo> fileInfoList = null; try { fileInfoList = helper.getFileInfoList(); } catch (IOException e) { System.err.println("Couldn\'t get file info map"); System.exit(1); } boolean splash = argsList.remove("--splash"); if (splash) { Optional<FileInfo> splashObj = fileInfoList.stream() .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny(); if (splashObj.isPresent()) { try (InputStream is = new FilterInputStream( Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) { @Override public int read() throws IOException { int b = super.read(); if (b >= 0) b ^= 0x36; return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r >= 0) { for (int i = 0; i < r; i++) b[off + i] ^= 0x36; } return r; } }) { new DataInputStream(is).readFully(new byte[28]); BufferedImage bi = ImageIO.read(is); JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath()); frame.setContentPane(new JComponent() { { setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight())); } @Override protected void paintComponent(Graphics g) { g.drawImage(bi, 0, 0, null); } }); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Splash not found"); } return; } String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null; File l2Folder = new File(System.getProperty("user.dir")); List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> { String filePath = separatorsToSystem(fi.getPath()); if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE)) return false; File file = new File(l2Folder, filePath); try { if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) { System.out.println(filePath + ": OK"); return false; } } catch (IOException e) { System.out.println(filePath + ": couldn't check hash: " + e); return true; } System.out.println(filePath + ": need update"); return true; }).collect(Collectors.toList()); List<String> errors = Collections.synchronizedList(new ArrayList<>()); ExecutorService executor = Executors.newFixedThreadPool(16); CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> { String filePath = separatorsToSystem(fi.getPath()); File file = new File(l2Folder, filePath); File folder = file.getParentFile(); if (!folder.exists()) { if (!folder.mkdirs()) { errors.add(filePath + ": couldn't create parent dir"); return; } } try (InputStream input = Util .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath()))); OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)]; int pos = 0; int r; while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) { pos += r; if (pos == buffer.length) { output.write(buffer, 0, pos); pos = 0; } } if (pos != 0) { output.write(buffer, 0, pos); } System.out.println(filePath + ": OK"); } catch (IOException e) { String msg = filePath + ": FAIL: " + e.getClass().getSimpleName(); if (e.getMessage() != null) { msg += ": " + e.getMessage(); } errors.add(msg); } }, executor)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(tasks).thenRun(() -> { for (String err : errors) System.err.println(err); executor.shutdown(); }); }
From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java
AutoScaleProcessor(AutoScalerConfig configuration, Executor executor, ScheduledExecutorService maintenanceExecutor) { this.configuration = configuration; this.maintenanceExecutor = maintenanceExecutor; this.executor = executor; serializer = new JavaSerializer<>(); writerConfig = EventWriterConfig.builder().build(); writer = new AtomicReference<>(); cache = CacheBuilder.newBuilder().initialCapacity(INITIAL_CAPACITY).maximumSize(MAX_CACHE_SIZE) .expireAfterAccess(configuration.getCacheExpiry().getSeconds(), TimeUnit.SECONDS).removalListener( RemovalListeners.asynchronous((RemovalListener<String, Pair<Long, Long>>) notification -> { if (notification.getCause().equals(RemovalCause.EXPIRED)) { triggerScaleDown(notification.getKey(), true); }/* ww w .j a v a 2 s .c om*/ }, maintenanceExecutor)) .build(); CompletableFuture.runAsync(this::bootstrapRequestWriters, maintenanceExecutor); }
From source file:ws.salient.session.Sessions.java
public CompletableFuture execute(List<Command> commands) { Instant now = Instant.now(); CompletableFuture result;/*from w w w. j a v a2s. c o m*/ try { commands.stream().filter(command -> command instanceof ModifyProfile).forEach((command) -> { log.info(toJson(command)); profiles.modified(command.getAccountId()); }); commands.stream().filter(command -> command.getKnowledgeBaseId() != null).forEach((command) -> { String knowledgeBaseId = command.getKnowledgeBaseId(); Map<String, String> aliases = profiles.getAliases(command.getAccountId(), command.getProfiles()); if (aliases.containsKey(knowledgeBaseId)) { knowledgeBaseId = aliases.get(knowledgeBaseId); } command.setKnowledgeBaseId(knowledgeBaseId); }); commands.forEach((command) -> { command.setTimestamp(now); }); // Load knowledge bases in parallel List<CompletableFuture<KnowledgeBase>> knowledgeBases = commands.stream() .filter(command -> command.getKnowledgeBaseId() != null) .collect(Collectors.groupingBy((command) -> { // Group commands by knowledgeBaseId return command.getKnowledgeBaseId(); })).values().stream().map((kbaseCommands) -> { return CompletableFuture.supplyAsync(() -> { // Load each knowledge base return repository.getKnowledgeBase(kbaseCommands.get(0).getKnowledgeBaseId()); }); }).collect(Collectors.toList()); CompletableFuture.allOf(knowledgeBases.toArray(new CompletableFuture[knowledgeBases.size()])).get(); // Load sessions in parallel List<CompletableFuture<Session>> sessions = commands.stream() .filter(command -> command.getSessionId() != null).collect(Collectors.groupingBy((command) -> { // Group commands by sessionId return command.getSessionId(); })).values().stream().map((sessionCommands) -> { return CompletableFuture.supplyAsync(() -> { // Load each session return getSession(sessionCommands.get(0)); }); }).collect(Collectors.toList()); CompletableFuture.allOf(sessions.toArray(new CompletableFuture[sessions.size()])).get(); result = CompletableFuture.runAsync(() -> { int requestIndex = 0; for (Command command : commands) { if (command.getSessionId() != null) { command.setTimestamp(now); Session session = getSession(command); session.accept(command); store.put(session, command, requestIndex); requestIndex++; } } }, commandExecutor).thenRun(() -> { this.sessions.forEach((id, session) -> { if (session.expired(now)) { if (session.getProcessCount() == 0) { int oldcount = sessions.size(); sessions.remove(id); session.dispose(); log.info("Session count was " + oldcount + " now " + sessions.size()); } } }); }); } catch (InterruptedException | ExecutionException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return result; }
From source file:io.pravega.controller.server.eventProcessor.ControllerEventProcessors.java
@Override public CompletableFuture<Void> handleFailedProcess(String process) { List<CompletableFuture<Void>> futures = new ArrayList<>(); if (commitEventProcessors != null) { futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> { try { commitEventProcessors.notifyProcessFailure(process); } catch (CheckpointStoreException e) { throw new CompletionException(e); }//from w w w.ja va 2s. c om }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)); } if (abortEventProcessors != null) { futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> { try { abortEventProcessors.notifyProcessFailure(process); } catch (CheckpointStoreException e) { throw new CompletionException(e); } }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)); } if (requestEventProcessors != null) { futures.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> { try { requestEventProcessors.notifyProcessFailure(process); } catch (CheckpointStoreException e) { throw new CompletionException(e); } }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)); } return FutureHelpers.allOf(futures); }
From source file:io.pravega.segmentstore.server.host.stat.AutoScaleProcessor.java
private CompletableFuture<Void> writeRequest(AutoScaleEvent event) { CompletableFuture<Void> result = new CompletableFuture<>(); try {/* ww w.j a va 2s. co m*/ CompletableFuture.runAsync(() -> { try { writer.get().writeEvent(event.getKey(), event).get(); result.complete(null); } catch (InterruptedException | ExecutionException e) { log.error("error sending request to requeststream {}", e); result.completeExceptionally(e); } }, executor); } catch (RejectedExecutionException e) { log.error("our executor queue is full. failed to post scale event for {}/{}/{}", event.getScope(), event.getStream(), event.getSegmentNumber()); result.completeExceptionally(e); } return result; }
From source file:io.pravega.service.server.host.stat.AutoScaleProcessor.java
private CompletableFuture<Void> writeRequest(ScaleEvent event) { CompletableFuture<Void> result = new CompletableFuture<>(); try {/*from ww w . j a v a 2 s. c o m*/ CompletableFuture.runAsync(() -> { try { writer.get().writeEvent(event.getKey(), event).get(); result.complete(null); } catch (InterruptedException | ExecutionException e) { log.error("error sending request to requeststream {}", e); result.completeExceptionally(e); } }, executor); } catch (RejectedExecutionException e) { log.error("our executor queue is full. failed to post scale event for {}/{}/{}", event.getScope(), event.getStream(), event.getSegmentNumber()); result.completeExceptionally(e); } return result; }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);/*from w ww . ja va 2 s.co m*/ return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:io.sqp.client.impl.SqpConnectionImpl.java
CompletableFuture<Void> send(SqpMessage msg, ResponseHandler responseHandler) { // TODO: use a timeout for response handler! if (responseHandler != null) { _messageHandler.addResponseHandler(responseHandler); }/*www . ja v a 2 s . c om*/ // TODO: optionally depend on previous future, so consecutive operations aren't executed if one fails? // as we always use the same, single threaded ExecutionService to run this send operation, all operations // are queued. This allows async-operations while assuring their order is kept return CompletableFuture.runAsync(() -> { try { if (_config.getProtocolFormat() == DataFormat.Binary) { _messageEncoder.encode(_endpoint.getSendStream(), DataFormat.Binary, msg); } else { _messageEncoder.encode(_endpoint.getSendWriter(), msg); } } catch (IOException e) { throw new CompletionException(new SqpIOException(e)); } }, _sendingService).exceptionally(new FailHandler(this)); }
From source file:com.xylocore.cassandra.query.SharedResultSetProcessor.java
/** * FILLIN//from ww w .java 2s. c o m */ private void scheduleCurrentWorkTask() { WorkTask myRunnableWorkTask = currentWorkTask; currentWorkTask = null; CompletableFuture.runAsync(() -> { try { runWorkTask(myRunnableWorkTask); handleTaskCompletion(myRunnableWorkTask, null); } catch (Throwable myThrowable) { handleTaskCompletion(null, myThrowable); } }, executor); }
From source file:io.sqp.client.impl.SqpConnectionImpl.java
CompletableFuture<Void> send(InputStream stream) { // TODO: optionally depend on previous future, so consecutive operations aren't executed if one fails? int bufSize = Math.min(MAX_MSG_BUFFER_SIZE, _session.getMaxBinaryMessageBufferSize()); return CompletableFuture.runAsync(() -> { byte[] buffer = new byte[bufSize]; int bytesRead; try (OutputStream output = _endpoint.getSendStream()) { while ((bytesRead = stream.read(buffer)) > 0) { output.write(buffer, 0, bytesRead); }/*from w w w . jav a 2 s . c om*/ } catch (IOException e) { throw new CompletionException(new SqpIOException(e)); } }, _sendingService).exceptionally(new FailHandler(this)); }