List of usage examples for java.io Closeable close
public void close() throws IOException;
From source file:fr.gael.dhus.olingo.v1.Processor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/*from ww w . java 2s .c o m*/ public ODataResponse readEntitySet(GetEntitySetUriInfo uri_info, String content_type) throws ODataException { // Gets values for `skip` and `top` (pagination). int defaultTop = CONFIGURATION_MANAGER.getOdataConfiguration().getDefaultTop(); int skip = (uri_info.getSkip() == null) ? 0 : uri_info.getSkip(); int top = (uri_info.getTop() == null) ? defaultTop : uri_info.getTop(); // Gets the `collection` part of the URI. EdmEntitySet targetES = uri_info.getTargetEntitySet(); AbstractEntitySet target = Model.getEntitySet(targetES.getName()); boolean is_navlink = !uri_info.getNavigationSegments().isEmpty(); // Validity and security checks. if (!target.isAuthorized(Security.getCurrentUser()) || !is_navlink && !target.isTopLevel()) { throw new NotAllowedException(); } // Contained target workaround (non OData2: non standard!) if (is_navlink) { int last_id = getContext().getPathInfo().getODataSegments().size() - 1; String navlinkname = getContext().getPathInfo().getODataSegments().get(last_id).getPath(); if (!navlinkname.equals(targetES.getName())) { targetES = new ContainedEntitySetDecorator(navlinkname, targetES); } } // Builds the response. KeyPredicate startKP = (uri_info.getKeyPredicates().isEmpty()) ? null : uri_info.getKeyPredicates().get(0); Map results = Navigator.<Map>navigate(uri_info.getStartEntitySet(), startKP, uri_info.getNavigationSegments(), Map.class); int inlineCount = -1; FilterExpression filter = uri_info.getFilter(); OrderByExpression orderBy = uri_info.getOrderBy(); if (uri_info.getInlineCount() != null && uri_info.getInlineCount().equals(InlineCount.ALLPAGES) && results instanceof SubMap && filter != null) { SubMapBuilder smb = ((SubMap) results).getSubMapBuilder(); smb.setFilter(filter); results = smb.build(); inlineCount = results.size(); } // Skip, Sort and Filter. if (results instanceof SubMap && (filter != null || orderBy != null || skip != 0 || top != 0)) { SubMapBuilder smb = ((SubMap) results).getSubMapBuilder(); smb.setFilter(filter).setOrderBy(orderBy); smb.setSkip(skip); smb.setTop(top); results = smb.build(); } // Custom formats (eg: metalink, csv) if (uri_info.getFormat() != null) { if (uri_info.getFormat().equals(MetalinkBuilder.CONTENT_TYPE)) { return MetalinkFormatter.writeFeed(targetES, results.values(), makeLink().toString()); } if (uri_info.getFormat().equals(CsvFormatter.CONTENT_TYPE)) { return CsvFormatter.writeFeed(targetES, results.values(), uri_info.getSelect()); } } // Feeds the EntitySetResponseBuilder. final String requestLink = makeLink().toString(); final Iterator<AbstractEntity> iterator = results.values().iterator(); final Iterator<Map<String, Object>> it = new Iterator<Map<String, Object>>() { private AbstractEntity entity; @Override public boolean hasNext() { boolean value = iterator.hasNext(); if (!value && entity != null) { try { Closeable closeable = Closeable.class.cast(entity); try { closeable.close(); } catch (IOException e) { LOGGER.warn("Cannot close resource: {}", entity); } } catch (ClassCastException e) { } } return value; } @Override public Map<String, Object> next() { entity = iterator.next(); return entity.toEntityResponse(requestLink); } @Override public void remove() { iterator.remove(); } }; ODataEntityProviderPropertiesBuilder builder = EntityProviderWriteProperties.serviceRoot(makeLink()); // $expand. ExpandSelectTreeNode expand_select_tree = UriParser.createExpandSelectTree(uri_info.getSelect(), uri_info.getExpand()); builder.expandSelectTree(expand_select_tree).callbacks( makeCallbacks(target.getExpandableNavLinkNames(), new Expander(makeLink(false), target, results))); // inlinecount. if (uri_info.getInlineCount() != null && uri_info.getInlineCount().equals(InlineCount.ALLPAGES)) { if (inlineCount == -1) { inlineCount = results.size(); } builder.inlineCountType(uri_info.getInlineCount()); builder.inlineCount(inlineCount); } return EntityProvider.writeFeed(content_type, targetES, new ListFromIterator<>(it), builder.build()); }
From source file:org.carbondata.core.util.CarbonUtil.java
/** * This method closes the streams/*w ww .ja v a2s. c om*/ * * @param streams - streams to close. */ public static void closeStreams(Closeable... streams) { // Added if to avoid NullPointerException in case one stream is being passed as null if (null != streams) { for (Closeable stream : streams) { if (null != stream) { try { stream.close(); } catch (IOException e) { LOGGER.error("Error while closing stream" + stream); } } } } }
From source file:io.fabric8.maven.core.service.PortForwardService.java
/** * Forwards a port to the newest pod matching the given selector. * If another pod is created, it forwards connections to the new pod once it's ready. *//* w w w . ja v a 2 s .co m*/ public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector, final int remotePort, final int localPort) throws Fabric8ServiceException { final Lock monitor = new ReentrantLock(true); final Condition podChanged = monitor.newCondition(); final Pod[] nextForwardedPod = new Pod[1]; final Thread forwarderThread = new Thread() { @Override public void run() { Pod currentPod = null; Closeable currentPortForward = null; try { monitor.lock(); while (true) { if (podEquals(currentPod, nextForwardedPod[0])) { podChanged.await(); } else { Pod nextPod = nextForwardedPod[0]; // may be null try { monitor.unlock(); // out of critical section if (currentPortForward != null) { log.info("Closing port-forward from pod %s", KubernetesHelper.getName(currentPod)); currentPortForward.close(); currentPortForward = null; } if (nextPod != null) { log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod)); currentPortForward = forwardPortAsync(externalProcessLogger, KubernetesHelper.getName(nextPod), remotePort, localPort); } else { log.info("Waiting for a pod to become ready before starting port-forward"); } currentPod = nextPod; } finally { monitor.lock(); } } } } catch (InterruptedException e) { log.debug("Port-forwarding thread interrupted", e); Thread.currentThread().interrupt(); } catch (Exception e) { log.warn("Error while port-forwarding to pod", e); } finally { monitor.unlock(); if (currentPortForward != null) { try { currentPortForward.close(); } catch (Exception e) { } } } } }; // Switching forward to the current pod if present Pod newPod = getNewestPod(podSelector); nextForwardedPod[0] = newPod; final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log) .watch(new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod pod) { monitor.lock(); try { List<Pod> candidatePods; if (nextForwardedPod[0] != null) { candidatePods = new LinkedList<>(); candidatePods.add(nextForwardedPod[0]); candidatePods.add(pod); } else { candidatePods = Collections.singletonList(pod); } Pod newPod = getNewestPod(candidatePods); // may be null if (!podEquals(nextForwardedPod[0], newPod)) { nextForwardedPod[0] = newPod; podChanged.signal(); } } finally { monitor.unlock(); } } @Override public void onClose(KubernetesClientException e) { // don't care } }); forwarderThread.start(); final Closeable handle = new Closeable() { @Override public void close() throws IOException { try { watch.close(); } catch (Exception e) { } try { forwarderThread.interrupt(); forwarderThread.join(15000); } catch (Exception e) { } } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { handle.close(); } catch (Exception e) { // suppress } } }); return handle; }
From source file:com.android.launcher3.Utilities.java
public static void closeSilently(Closeable c) { if (c != null) { try {//from www.j a va 2 s . c om c.close(); } catch (IOException e) { if (ProviderConfig.IS_DOGFOOD_BUILD) { Log.d(TAG, "Error closing", e); } } } }
From source file:org.ow2.proactive.scheduler.rest.SchedulerClient.java
private void closeIfPossible(Closeable closeable) { if (closeable != null) { try {// ww w.ja va2s . c om closeable.close(); } catch (IOException ioe) { // ignore } } }
From source file:com.colorchen.qbase.utils.FileUtil.java
/** * IO/* ww w. j av a 2 s . c o m*/ * * @param closeables closeable */ public static void closeIO(Closeable... closeables) { if (closeables == null) return; try { for (Closeable closeable : closeables) { if (closeable != null) { closeable.close(); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.flexive.shared.FxSharedUtils.java
/** * Close the given resources and log a warning message if closing fails. * * @param resources the resource(s) to be closed * @since 3.1/*from w w w . j av a 2 s . c om*/ */ public static void close(Closeable... resources) { if (resources != null) { for (Closeable resource : resources) { if (resource != null) { try { resource.close(); } catch (IOException e) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to close resource " + resource + ": " + e.getMessage(), e); } } } } } }
From source file:com.colorchen.qbase.utils.FileUtil.java
/** * ?IO// w w w . ja v a 2s. com * * @param closeables closeable */ public static void closeIOQuietly(Closeable... closeables) { if (closeables == null) return; for (Closeable closeable : closeables) { if (closeable != null) { try { closeable.close(); } catch (IOException ignored) { } } } }
From source file:io.druid.segment.realtime.plumber.RealtimePlumber.java
@Override public <T> QueryRunner<T> getQueryRunner(final Query<T> query) { final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); final QueryToolChest<T, Query<T>> toolchest = factory.getToolchest(); final Function<Query<T>, ServiceMetricEvent.Builder> builderFn = new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override/*from w w w. ja v a 2 s . co m*/ public ServiceMetricEvent.Builder apply(@Nullable Query<T> input) { return toolchest.makeMetricBuilder(query); } }; List<TimelineObjectHolder<String, Sink>> querySinks = Lists.newArrayList(); for (Interval interval : query.getIntervals()) { querySinks.addAll(sinkTimeline.lookup(interval)); } return toolchest.mergeResults(factory.mergeRunners(queryExecutorService, FunctionalIterable .create(querySinks).transform(new Function<TimelineObjectHolder<String, Sink>, QueryRunner<T>>() { @Override public QueryRunner<T> apply(TimelineObjectHolder<String, Sink> holder) { if (holder == null) { throw new ISE("No timeline entry at all!"); } // The realtime plumber always uses SingleElementPartitionChunk final Sink theSink = holder.getObject().getChunk(0).getObject(); if (theSink == null) { throw new ISE("Missing sink for timeline entry[%s]!", holder); } final SegmentDescriptor descriptor = new SegmentDescriptor(holder.getInterval(), theSink.getSegment().getVersion(), theSink.getSegment().getShardSpec().getPartitionNum()); return new SpecificSegmentQueryRunner<T>(new MetricsEmittingQueryRunner<T>(emitter, builderFn, factory.mergeRunners(MoreExecutors.sameThreadExecutor(), Iterables.transform(theSink, new Function<FireHydrant, QueryRunner<T>>() { @Override public QueryRunner<T> apply(FireHydrant input) { // It is possible that we got a query for a segment, and while that query // is in the jetty queue, the segment is abandoned. Here, we need to retry // the query for the segment. if (input == null || input.getSegment() == null) { return new ReportTimelineMissingSegmentQueryRunner<T>( descriptor); } // Prevent the underlying segment from closing when its being iterated final Closeable closeable = input.getSegment().increment(); try { return factory.createRunner(input.getSegment()); } finally { try { if (closeable != null) { closeable.close(); } } catch (IOException e) { throw Throwables.propagate(e); } } } }))).withWaitMeasuredFromNow(), new SpecificSegmentSpec(descriptor)); } }))); }