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: 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 #2
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 #3
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 #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: 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 #6
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 #7
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 #8
Source File: SettingsBackup.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public static void close(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch (IOException e) {
    }
}
 
Example #9
Source File: Cmd.java    From Genius-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Can close the in or out thread
 *
 * @param closeable Closeable
 */
static void closeIO(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #10
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 #11
Source File: IsmReaderImpl.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public boolean start() throws IOException {
  checkState(delegate == null, "Already started");
  try (Closeable counterCloser = IsmReader.setSideInputReadContext(readCounter)) {
    delegate = overKeyComponents(getKeyComponents());
  }
  return delegate.start();
}
 
Example #12
Source File: CloseUtils.java    From encrypt with Apache License 2.0 5 votes vote down vote up
public static void close(Closeable closeable) {
    if (null == closeable) return;
    try {
        closeable.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: PerfMarkTransformer.java    From perfmark with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] transform(
    ClassLoader loader,
    final String className,
    Class<?> classBeingRedefined,
    ProtectionDomain protectionDomain,
    byte[] classfileBuffer) {
  if (!validatedClassLoaders.containsKey(loader)) {
    InputStream stream = loader.getResourceAsStream(DST_OWNER + ".class");
    if (stream != null) {
      try (Closeable c = stream) {
        validatedClassLoaders.put(loader, true);
        // TODO: validate dst methods
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      validatedClassLoaders.put(loader, false);
    }
  }
  if (validatedClassLoaders.get(loader)) {
    List<String> meth1 =
        Arrays.asList("io.perfmark.agent.PerfMarkTransformerTest$ClzAutoRecord", "recordMe");
    return transform(className, Collections.singletonList(meth1), classfileBuffer);
  } else {
    return classfileBuffer;
  }
}
 
Example #14
Source File: IOUtils.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException ignore) {
            // skip
        }
    }
}
 
Example #15
Source File: OwnerTest.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void borrowHasNoImpactOnRelease() throws Exception {
  try (Owner<Closeable, IOException> owner = own(contained, IOException.class)) {
    owner.borrow();
    owner.release();
  }

  verifyNoMoreInteractions(contained);
}
 
Example #16
Source File: NativeLibraryLoader.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void closeQuietly(Closeable c) {
    if (c != null) {
        try {
            c.close();
        } catch (IOException ignore) {
            // ignore
        }
    }
}
 
Example #17
Source File: Utils.java    From understand-plugin-framework with Apache License 2.0 5 votes vote down vote up
private static void closeSilently(Closeable closeable) {
    if (closeable == null) {
        return;
    }
    try {
        closeable.close();
    } catch (Throwable e) {
        // ignore
    }
}
 
Example #18
Source File: JrpipLog.java    From jrpip with Apache License 2.0 5 votes vote down vote up
protected void closeCloseable(Closeable closeable)
{
    try
    {
        if (closeable != null)
        {
            closeable.close();
        }
    }
    catch (Exception e)
    {
        LOGGER.warn("Unable to close.", e);
    }
}
 
Example #19
Source File: JavaUtils.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/** Closes the given object, ignoring IOExceptions. */
public static void closeQuietly(Closeable closeable) {
  try {
    if (closeable != null) {
      closeable.close();
    }
  } catch (IOException e) {
    logger.error("IOException should not have been thrown.", e);
  }
}
 
Example #20
Source File: Utils.java    From fit with Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(Closeable closeable) {
  try {
    if (closeable != null) {
      closeable.close();
    }
  } catch (IOException ioe) {
    // ignore
  }
}
 
Example #21
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 #22
Source File: WorkerPool.java    From questdb with Apache License 2.0 5 votes vote down vote up
public void start(@Nullable Log log) {
    if (running.compareAndSet(false, true)) {
        for (int i = 0; i < workerCount; i++) {
            final int index = i;
            Worker worker = new Worker(
                    workerJobs.getQuick(i),
                    halted,
                    workerAffinity[i],
                    log,
                    (ex) -> {
                        final ObjList<Closeable> cl = cleaners.getQuick(index);
                        for (int j = 0, n = cl.size(); j < n; j++) {
                            Misc.free(cl.getQuick(j));
                        }
                        if (log != null) {
                            log.info().$("cleaned [worker=").$(index).$(']').$();
                        }
                    },
                    haltOnError,
                    i
            );
            worker.setDaemon(daemons);
            workers.add(worker);
            worker.start();
        }
        if (log != null) {
            log.info().$("started").$();
        }
        started.countDown();
    }
}
 
Example #23
Source File: NIOUtil.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
public static void close(Closeable closeable) {
  if (closeable == null) {
    return;
  }
  try {
    closeable.close();
  } catch (IOException e) {
  }
}
 
Example #24
Source File: QTalkPatchDownloadHelper.java    From imsdk-android with MIT License 5 votes vote down vote up
public static void closeReaderWriter(Closeable closeable) {

        try {
            if (closeable != null) {
                closeable.close();
            }
        }
        catch (IOException e) {
            LogUtil.e(TAG, e.toString());
        }
    }
 
Example #25
Source File: DelegateToOwnerLookupTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDelegateLookup() throws IOException {
    //Assert we have enclosing project
    assertNotNull(owner);
    //Assert we have correct Lookup in enclosing project
    assertNotNull(owner.getLookup().lookup(Sources.class));
    assertNotNull(owner.getLookup().lookup(SourcesImpl.class));
    assertNotNull(owner.getLookup().lookup(ProjectOpenedHook.class));
    assertNotNull(owner.getLookup().lookup(ProjectOpenedHookImpl.class));
    assertNotNull(owner.getLookup().lookup(ProjectInformation.class));
    assertNotNull(owner.getLookup().lookup(ProjectInformationImpl.class));
    //Test delegating lookup
    final Lookup lkp = ProjectConvertors.createDelegateToOwnerLookup(automaticProjectHome);
    assertNotNull(lkp);
    //Test do not have black listed services
    assertNull(lkp.lookup(ProjectOpenedHook.class));
    assertNull(lkp.lookup(ProjectOpenedHookImpl.class));
    assertNull(lkp.lookup(ProjectInformation.class));
    assertNull(lkp.lookup(ProjectInformationImpl.class));
    //Test have other services
    assertNotNull(lkp.lookup(Sources.class));
    assertNotNull(lkp.lookup(SourcesImpl.class));
    //Close lookup
    ((Closeable)lkp).close();
    //Nothing should be in the Lookup
    assertNull(lkp.lookup(ProjectOpenedHook.class));
    assertNull(lkp.lookup(ProjectOpenedHookImpl.class));
    assertNull(lkp.lookup(ProjectInformation.class));
    assertNull(lkp.lookup(ProjectInformationImpl.class));
    assertNull(lkp.lookup(Sources.class));
    assertNull(lkp.lookup(SourcesImpl.class));
}
 
Example #26
Source File: DefaultAnswerTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAnswering() throws IOException {
    Closeable mock = mock(Closeable.class);
    try {
        mock.close();
        fail();
    } catch (UnstubbedMethodException e) {
        assertEquals("closeable.close(); was not stubbed", e.getMessage());
    }
}
 
Example #27
Source File: ZipHelper.java    From MVVMArms with Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) {
        }
    }
}
 
Example #28
Source File: ConfiguredRMFailoverProxyProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Close all the proxy objects which have been opened over the lifetime of
 * this proxy provider.
 */
@Override
public synchronized void close() throws IOException {
  for (T proxy : proxies.values()) {
    if (proxy instanceof Closeable) {
      ((Closeable)proxy).close();
    } else {
      RPC.stopProxy(proxy);
    }
  }
}
 
Example #29
Source File: RenderWriter.java    From text-ui with GNU General Public License v3.0 5 votes vote down vote up
public RenderWriter(ScreenContext out, Closeable closeable) throws NullPointerException {
  if (out == null) {
    throw new NullPointerException("No null appendable expected");
  }

  //
  this.out = out;
  this.empty = true;
  this.closeable = closeable;
}
 
Example #30
Source File: Misc.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean urlExists(URL url) {
        try {
            URLConnection connection = url.openConnection();
            if ( connection instanceof JarURLConnection ) {
                JarURLConnection jarURLConnection = (JarURLConnection)connection;
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
jarURLConnection.getJarFileURL()
                                                                   });
                try {
                    return urlClassLoader.findResource(jarURLConnection.getEntryName())!=null;
                }
                finally {
                    if ( urlClassLoader instanceof Closeable ) {
                        ((Closeable)urlClassLoader).close();
                    }
                }
            }
            InputStream is = null;
            try {
                is = url.openStream();
            }
            finally {
                if ( is!=null ) {
                    is.close();
                }
            }
            return is!=null;
        }
        catch (IOException ioe) {
            return false;
        }
    }