java.io.Closeable Java Examples

The following examples show how to use java.io.Closeable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RFABIOUtil.java    From RapidFloatingActionButton with Apache License 2.0 6 votes vote down vote up
/**
 * 关闭流
 *
 * @param closeables
 */
public static void closeIO(Closeable... closeables) {
    if (null == closeables || closeables.length <= 0) {
        return;
    }
    for (Closeable cb : closeables) {
        try {
            if (null == cb) {
                continue;
            }
            cb.close();
        } catch (IOException e) {
            Log.e(TAG, "close IO ERROR...", e);
        }
    }
}
 
Example #2
Source File: CHMUseCasesTest.java    From Chronicle-Map with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcquireUsingWithCharSequence() throws IOException {

    ChronicleMapBuilder<CharSequence, CharSequence> builder = ChronicleMapBuilder
            .of(CharSequence.class, CharSequence.class)
            .entries(1);

    try (ChronicleMap<CharSequence, CharSequence> map = newInstance(builder)) {

        CharSequence using = new StringBuilder();

        try (net.openhft.chronicle.core.io.Closeable c = map.acquireContext("1", using)) {
            assertTrue(using instanceof StringBuilder);
            ((StringBuilder) using).append("Hello World");
        }

        assertEquals("Hello World", map.get("1").toString());
        mapChecks();
    }
}
 
Example #3
Source File: Client.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        if (args.length == 0) {
            System.out.println("please specify wsdl");
            System.exit(1);
        }

        File wsdl = new File(args[0]);

        JMSGreeterService service = new JMSGreeterService(wsdl.toURI().toURL(), SERVICE_NAME);
        JMSGreeterPortType greeter = (JMSGreeterPortType)service.getPort(PORT_NAME, JMSGreeterPortType.class);

        System.out.println("Invoking greetMeOneWay...");
        greeter.greetMeOneWay(System.getProperty("user.name"));
        System.out.println("No response from server as method is OneWay");
        System.out.println();

        if (greeter instanceof Closeable) {
            ((Closeable)greeter).close();
        }

        System.exit(0);
    }
 
Example #4
Source File: ChannelDataOutputTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests write operations followed by seek operations.
 *
 * @throws IOException should never happen since we read and write in memory only.
 */
@Test
@DependsOnMethod("testAllWriteMethods")
public void testWriteAndSeek() throws IOException {
    initialize("testWriteAndSeek", STREAM_LENGTH, random.nextInt(BUFFER_MAX_CAPACITY) + Double.BYTES);
    writeInStreams();
    ((Closeable) referenceStream).close();
    final byte[] expectedArray = expectedData.toByteArray();
    final int seekRange = expectedArray.length - Long.BYTES;
    final ByteBuffer arrayView = ByteBuffer.wrap(expectedArray);
    for (int i=0; i<100; i++) {
        final int position = random.nextInt(seekRange);
        testedStream.seek(position);
        assertEquals("getStreamPosition()", position, testedStream.getStreamPosition());
        final long v = random.nextLong();
        testedStream.writeLong(v);
        arrayView.putLong(position, v);
    }
    testedStream.flush();
    assertArrayEquals(expectedArray, Arrays.copyOf(testedStreamBackingArray, expectedArray.length));
}
 
Example #5
Source File: DependCenter.java    From simple-robot-core with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
    // 单例工厂中,如果为closeable的,关闭
    synchronized (SINGLE_FACTORY) {
        SINGLE_FACTORY.forEach((k, v) -> {
            if (v instanceof Closeable) {
                Closeable cl = (Closeable) v;
                try {
                    cl.close();
                    QQLog.debug("depend.center.close", k);
                } catch (IOException e) {
                    QQLog.error("depend.center.close.failed", e, k, v.getClass(), e.getLocalizedMessage());
                }
            }
        });
        // 清除
        SINGLE_FACTORY.clear();
    }
}
 
Example #6
Source File: Closeables.java    From phoenix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static IOException closeAllQuietly(Iterable<? extends Closeable> iterable) {
    if (iterable == null) return null;
    
    LinkedList<IOException> exceptions = null;
    for (Closeable closeable : iterable) {
        try {
            closeable.close();
        } catch (IOException x) {
            if (exceptions == null) exceptions = new LinkedList<IOException>();
            exceptions.add(x);
        }
    }
    
    IOException ex = MultipleCausesIOException.fromIOExceptions(exceptions);
    return ex;
}
 
Example #7
Source File: RMDeliveryInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handle(Message message) throws SequenceFault, RMException {
    final AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, false, false);
    //if wsrmp:RMAssertion and addressing is optional
    if (maps == null && isRMPolicyEnabled(message)) {
        return;
    }
    LOG.entering(getClass().getName(), "handleMessage");
    Destination dest = getManager().getDestination(message);
    final boolean robust =
        MessageUtils.getContextualBoolean(message, Message.ROBUST_ONEWAY, false);
    if (robust) {
        message.remove(RMMessageConstants.DELIVERING_ROBUST_ONEWAY);
        dest.acknowledge(message);
    }
    dest.processingComplete(message);

    // close InputStream of RMCaptureInInterceptor, to delete tmp files in filesystem
    Closeable closable = (Closeable)message.get("org.apache.cxf.ws.rm.content.closeable");
    if (null != closable) {
        try {
            closable.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}
 
Example #8
Source File: IOUtil.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * 在final中安静的关闭, 不再往外抛出异常避免影响原有异常,最常用函数. 同时兼容Closeable为空未实际创建的情况.
 * 
 * @see {@link Closeables#close}
 */
public static void closeQuietly(Closeable closeable) {
	if (closeable == null) {
		return;
	}
	try {
		closeable.close();
	} catch (IOException e) {
		logger.warn(CLOSE_ERROR_MESSAGE, e);
	}
}
 
Example #9
Source File: PoolBasedLimiter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public Closeable acquirePermits(long permits)
    throws InterruptedException {
  int permitsToAcquire = Ints.checkedCast(permits);
  this.permitPool.acquire(permitsToAcquire);
  return new PoolPermitCloseable(this.permitPool, permitsToAcquire);
}
 
Example #10
Source File: WriteOperation.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Object outputElem) throws Exception {
  try (Closeable scope = context.enterProcess()) {
    checkStarted();
    mayInitializeWriterInProcess();
    byteCount.addValue(writer.add(outputElem));
  }
}
 
Example #11
Source File: GatewayThread.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
protected void closeQuietly(Closeable closable) {
    try {
        closable.close();
    } catch (IOException e) {
        // ignore
    }
}
 
Example #12
Source File: MyUtils.java    From android-art-res with Apache License 2.0 5 votes vote down vote up
public static void close(Closeable closeable) {
    try {
        if (closeable != null) {
            closeable.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: CloseableTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void test(Class<?> c) {
    System.out.println("\nTest " + c);
    if (Closeable.class.isAssignableFrom(c)) {
        System.out.println("Test passed!");
    } else {
        error++;
        System.out.println("Test failed!");
    }
}
 
Example #14
Source File: IoUtils.java    From base-imageloader with Apache License 2.0 5 votes vote down vote up
public static void closeSilently(Closeable closeable) {
	if (closeable != null) {
		try {
			closeable.close();
		} catch (Exception ignored) {
		}
	}
}
 
Example #15
Source File: MockDirectoryWrapper.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
synchronized void addFileHandle(Closeable c, String name, Handle handle) {
  Integer v = openFiles.get(name);
  if (v != null) {
    v = Integer.valueOf(v.intValue()+1);
    openFiles.put(name, v);
  } else {
    openFiles.put(name, Integer.valueOf(1));
  }
  
  openFileHandles.put(c, new RuntimeException("unclosed Index" + handle.name() + ": " + name));
}
 
Example #16
Source File: ThrottledFileSystem.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private void acquirePermits(int permits, String op) throws IOException {
  try {
    Closeable closeable = getRateLimiter().acquirePermits(permits);
    if (closeable == null) {
      throw new NotEnoughPermitsException(op);
    }
  } catch (InterruptedException e) {
    throw new NotEnoughPermitsException(op, e);
  }
}
 
Example #17
Source File: CarlifeUtil.java    From apollo-DuerOS with Apache License 2.0 5 votes vote down vote up
public static void closeCloseable(Closeable closeable) {
    if (closeable != null) {
        try {
           closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e.getMessage());
        } finally {
            closeable = null;
        }
    }
}
 
Example #18
Source File: ProcessDataBinding.java    From VirtualAPK with Apache License 2.0 5 votes vote down vote up
private static void closeSafely(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #19
Source File: ResourceUtils.java    From Smarty-Streets-AutoCompleteTextView with Apache License 2.0 5 votes vote down vote up
public static void closeResourceQuietly(@Nullable Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            Log.e(ResourceUtils.class.getName(), e.getMessage(), e);
        }
    }
}
 
Example #20
Source File: URLClassLoader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
* Closes this URLClassLoader, so that it can no longer be used to load
* new classes or resources that are defined by this loader.
* Classes and resources defined by any of this loader's parents in the
* delegation hierarchy are still accessible. Also, any classes or resources
* that are already loaded, are still accessible.
* <p>
* In the case of jar: and file: URLs, it also closes any files
* that were opened by it. If another thread is loading a
* class when the {@code close} method is invoked, then the result of
* that load is undefined.
* <p>
* The method makes a best effort attempt to close all opened files,
* by catching {@link IOException}s internally. Unchecked exceptions
* and errors are not caught. Calling close on an already closed
* loader has no effect.
* <p>
* @exception IOException if closing any file opened by this class loader
* resulted in an IOException. Any such exceptions are caught internally.
* If only one is caught, then it is re-thrown. If more than one exception
* is caught, then the second and following exceptions are added
* as suppressed exceptions of the first one caught, which is then re-thrown.
*
* @exception SecurityException if a security manager is set, and it denies
*   {@link RuntimePermission}{@code ("closeClassLoader")}
*
* @since 1.7
*/
public void close() throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkPermission(new RuntimePermission("closeClassLoader"));
    }
    List<IOException> errors = ucp.closeLoaders();

    // now close any remaining streams.

    synchronized (closeables) {
        Set<Closeable> keys = closeables.keySet();
        for (Closeable c : keys) {
            try {
                c.close();
            } catch (IOException ioex) {
                errors.add(ioex);
            }
        }
        closeables.clear();
    }

    if (errors.isEmpty()) {
        return;
    }

    IOException firstex = errors.remove(0);

    // Suppress any remaining exceptions

    for (IOException error: errors) {
        firstex.addSuppressed(error);
    }
    throw firstex;
}
 
Example #21
Source File: Utils.java    From SimpleCropView with MIT License 5 votes vote down vote up
public static void closeQuietly(Closeable closeable) {
  if (closeable == null) return;
  try {
    closeable.close();
  } catch (Throwable ignored) {
  }
}
 
Example #22
Source File: ImapChannelUpstreamHandler.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    try (Closeable closeable = IMAPMDCContext.from(ctx, attributes)) {
        imapCommandsMetric.increment();
        ImapSession session = (ImapSession) attributes.get(ctx.getChannel());
        ImapResponseComposer response = (ImapResponseComposer) ctx.getAttachment();
        ImapMessage message = (ImapMessage) e.getMessage();
        ChannelPipeline cp = ctx.getPipeline();

        try {
            if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
                cp.addBefore(NettyConstants.EXECUTION_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
            } else {
                cp.addBefore(NettyConstants.CORE_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);

            }
            final ResponseEncoder responseEncoder = new ResponseEncoder(encoder, response);
            processor.process(message, responseEncoder, session);

            if (session.getState() == ImapSessionState.LOGOUT) {
                // Make sure we close the channel after all the buffers were flushed out
                Channel channel = ctx.getChannel();
                if (channel.isConnected()) {
                    channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
            final IOException failure = responseEncoder.getFailure();

            if (failure != null) {
                LOGGER.info(failure.getMessage());
                LOGGER.debug("Failed to write {}", message, failure);
                throw failure;
            }
        } finally {
            ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
        }

        super.messageReceived(ctx, e);
    }
}
 
Example #23
Source File: Utils.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(/* Auto */Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) {
        }
    }
}
 
Example #24
Source File: CloseableUtils.java    From springreplugin with Apache License 2.0 5 votes vote down vote up
/**
 * 大部分Close关闭流,以及实现Closeable的功能可使用此方法
 *
 * @param c Closeable对象,包括Stream等
 */
public static void closeQuietly(Closeable c) {
    try {
        if (c != null) {
            c.close();
        }
    } catch (final IOException ioe) {
        // ignore
    }
}
 
Example #25
Source File: MCREpubZipResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static void suppressedClose(Closeable... closeus) {
    for (Closeable closeme : closeus) {
        if (closeme != null) {
            try {
                closeme.close();
            } catch (IOException ignored) {
            }
        }
    }
}
 
Example #26
Source File: WSDiscoveryClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void uncache() {
    if (dispatch instanceof Closeable) {
        try {
            ((Closeable)dispatch).close();
        } catch (IOException e) {
            //ignorable
        }
    }
    dispatch = null;
    service = null;
}
 
Example #27
Source File: HBaseBasedAuditRepository.java    From atlas with Apache License 2.0 5 votes vote down vote up
private void close(Closeable closeable) throws AtlasException {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            throw new AtlasException(e);
        }
    }
}
 
Example #28
Source File: Files.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a Closeable to a Runnable by converting checked IOException
 * to UncheckedIOException
 */
private static Runnable asUncheckedRunnable(Closeable c) {
    return () -> {
        try {
            c.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    };
}
 
Example #29
Source File: URLClassLoader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
* Closes this URLClassLoader, so that it can no longer be used to load
* new classes or resources that are defined by this loader.
* Classes and resources defined by any of this loader's parents in the
* delegation hierarchy are still accessible. Also, any classes or resources
* that are already loaded, are still accessible.
* <p>
* In the case of jar: and file: URLs, it also closes any files
* that were opened by it. If another thread is loading a
* class when the {@code close} method is invoked, then the result of
* that load is undefined.
* <p>
* The method makes a best effort attempt to close all opened files,
* by catching {@link IOException}s internally. Unchecked exceptions
* and errors are not caught. Calling close on an already closed
* loader has no effect.
* <p>
* @exception IOException if closing any file opened by this class loader
* resulted in an IOException. Any such exceptions are caught internally.
* If only one is caught, then it is re-thrown. If more than one exception
* is caught, then the second and following exceptions are added
* as suppressed exceptions of the first one caught, which is then re-thrown.
*
* @exception SecurityException if a security manager is set, and it denies
*   {@link RuntimePermission}{@code ("closeClassLoader")}
*
* @since 1.7
*/
public void close() throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkPermission(new RuntimePermission("closeClassLoader"));
    }
    List<IOException> errors = ucp.closeLoaders();

    // now close any remaining streams.

    synchronized (closeables) {
        Set<Closeable> keys = closeables.keySet();
        for (Closeable c : keys) {
            try {
                c.close();
            } catch (IOException ioex) {
                errors.add(ioex);
            }
        }
        closeables.clear();
    }

    if (errors.isEmpty()) {
        return;
    }

    IOException firstex = errors.remove(0);

    // Suppress any remaining exceptions

    for (IOException error: errors) {
        firstex.addSuppressed(error);
    }
    throw firstex;
}
 
Example #30
Source File: ShellCmdUtil.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
private static void close(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (Exception e) {
            // nothing
        }
    }
}