List of usage examples for java.io Closeable Closeable
Closeable
From source file:dlauncher.dialogs.Login.java
private String login_getResponse() throws IOException { URL website = new URL("http://authserver.mojang.com/authenticate"); final HttpURLConnection connection = (HttpURLConnection) website.openConnection(); connection.setReadTimeout(3000);//from w ww. j a v a 2 s .c o m try (Closeable c = new Closeable() { @Override public void close() throws IOException { connection.disconnect(); } }) { StringBuilder response; try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { response = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } return response.toString(); } }
From source file:org.artifactory.rest.resource.archive.ArchiveResource.java
private void markForDeletionAtResponseEnd(final File buildArtifactsArchive) { // delete the file after jersey streamed it back to the client closeableService.add(new Closeable() { @Override//w w w . j a v a 2 s .c o m public void close() throws IOException { FileUtils.deleteQuietly(buildArtifactsArchive); } }); }
From source file:org.nuxeo.ecm.core.io.registry.context.WrappedContext.java
/** * Open the context and make all embedded entities available. Returns a {@link Closeable} which must be closed at * the end./*from ww w. j av a 2 s. co m*/ * <p> * Note the same context could be opened and closed several times. * </p> * * @return A {@link Closeable} instance. * @since 7.2 */ public final Closeable open() { ctx.setParameterValues(WRAPPED_CONTEXT, this); return new Closeable() { @Override public void close() throws IOException { ctx.setParameterValues(WRAPPED_CONTEXT, parent); } }; }
From source file:com.tinspx.util.io.ChannelSourceTest.java
static Closeable teardownTestDir(@NonNull final File testDir) throws IOException { return new Closeable() { @Override/* www . j av a 2s . c om*/ public void close() throws IOException { FileUtils.deleteDirectory(testDir); } }; }
From source file:cz.cas.lib.proarc.webapp.server.rest.ExportResource.java
/** * Gets the exported package built by {@link #newDesaExport() } with {@code forDownload=true}. * The package data are removed after completion of the response. * * @param token token to identify the prepared package * @return the package contents in ZIP format *//*from w w w . j av a2s .c om*/ @GET @Path(ExportResourceApi.DESA_PATH) @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response getDesaExport(@QueryParam(ExportResourceApi.RESULT_TOKEN) String token, @Context CloseableService finalizer) { URI exportUri = user.getExportFolder(); File exportFolder = new File(exportUri); final File file = DesaExport.findExportedPackage(exportFolder, token); if (file == null) { return Response.status(Status.NOT_FOUND).type(MediaType.TEXT_PLAIN_TYPE) .entity("The contents not found!").build(); } finalizer.add(new Closeable() { @Override public void close() throws IOException { FileUtils.deleteQuietly(file.getParentFile()); } }); return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + file.getName() + '"').build(); }
From source file:hudson.cli.CLI.java
/** * @deprecated Specific to {@link Mode#REMOTING}. *//*from w w w . j a v a2 s. co m*/ @Deprecated private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException { LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint); if (authorization != null) { LOGGER.warning("-auth ignored when using JNLP agent port"); } final Socket s = new Socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); OutputStream out; if (httpsProxyTunnel != null) { String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[] { tokens[0], tokens[1] }); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); // read the response from the proxy ByteArrayOutputStream rsp = new ByteArrayOutputStream(); while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) { int ch = s.getInputStream().read(); if (ch < 0) throw new IOException("Failed to read the HTTP proxy response: " + rsp); rsp.write(ch); } String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine(); if (head == null) { throw new IOException("Unexpected empty response"); } if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) { s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); } // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well. // So instead of relying on it, we'll just send the close command and then let the server // cut their side, then close the socket after the join. out = new SocketOutputStream(s) { @Override public void close() throws IOException { // ignore } }; } else { s.connect(clip.endpoint, 3000); out = SocketChannelStream.out(s); } closables.add(new Closeable() { public void close() throws IOException { s.close(); } }); Connection c = new Connection(SocketChannelStream.in(s), out); switch (clip.version) { case 1: DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor. break; case 2: DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF(); if (!greeting.equals("Welcome")) throw new IOException("Handshaking failed: " + greeting); try { byte[] secret = c.diffieHellman(false).generateSecret(); SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES"); c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding"); // validate the instance identity, so that we can be sure that we are talking to the same server // and there's no one in the middle. byte[] signature = c.readByteArray(); if (clip.identity != null) { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(clip.getIdentity()); verifier.update(secret); if (!verifier.verify(signature)) throw new IOException("Server identity signature validation failed."); } } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to negotiate transport security").initCause(e); } } return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in), new BufferedOutputStream(c.out)); }
From source file:org.callimachusproject.server.chain.TransactionHandler.java
private CloseableEntity endEntity(HttpEntity entity, final ObjectConnection con) { return new CloseableEntity(entity, new Closeable() { public void close() { try { executor.execute(new Runnable() { public void run() { endTransaction(con); }//from w w w. j a va 2 s . c o m }); } catch (RejectedExecutionException ex) { endTransaction(con); } } }); }
From source file:org.wikidata.wdtk.client.DumpProcessingOutputAction.java
/** * Creates a separate thread for writing into the given output stream and * returns a pipe output stream that can be used to pass data to this * thread./*w w w .ja va 2 s . c o m*/ * <p> * This code is inspired by * http://stackoverflow.com/questions/12532073/gzipoutputstream * -that-does-its-compression-in-a-separate-thread * * @param outputStream * the stream to write to in the thread * @return a new stream that data should be written to * @throws IOException * if the pipes could not be created for some reason */ protected OutputStream getAsynchronousOutputStream(final OutputStream outputStream) throws IOException { final int SIZE = 1024 * 1024 * 10; final PipedOutputStream pos = new PipedOutputStream(); final PipedInputStream pis = new PipedInputStream(pos, SIZE); final FinishableRunnable run = new FinishableRunnable() { volatile boolean finish = false; volatile boolean hasFinished = false; @Override public void finish() { this.finish = true; while (!this.hasFinished) { // loop until thread is really finished } } @Override public void run() { try { byte[] bytes = new byte[SIZE]; // Note that we finish really gently here, writing all data // that is still in the input first (in theory, new data // could arrive asynchronously, so that the thread never // finishes, but this is not the intended mode of // operation). for (int len; (!this.finish || pis.available() > 0) && (len = pis.read(bytes)) > 0;) { outputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { close(pis); close(outputStream); this.hasFinished = true; } } }; new Thread(run, "async-output-stream").start(); this.outputStreams.add(new Closeable() { @Override public void close() throws IOException { run.finish(); } }); return pos; }
From source file:org.apache.jackrabbit.oak.plugins.tika.TextExtractorMain.java
private static Closeable asCloseable(final FileStore fs) { return new Closeable() { @Override/* w w w .j a va2 s . c o m*/ public void close() throws IOException { fs.close(); } }; }
From source file:org.apache.jackrabbit.oak.plugins.tika.TextExtractorMain.java
private static Closeable asCloseable(final DataStore ds) { return new Closeable() { @Override//w ww . jav a 2 s . c o m public void close() throws IOException { try { ds.close(); } catch (DataStoreException e) { throw new IOException(e); } } }; }