List of usage examples for java.io Closeable close
public void close() throws IOException;
From source file:org.flowerplatform.communication.public_resources.PublicResourcesServlet.java
protected Pair<InputStream, Closeable> getInputStreamForFileWithinZip(final InputStream fileInputStream, String fileWithinZip) throws IOException { final BufferedInputStream bis = new BufferedInputStream(fileInputStream, DEFAULT_BUFFER_SIZE); final ZipInputStream zis = new ZipInputStream(bis); Closeable closeable = new Closeable() { @Override//from w w w. j ava 2 s . c o m public void close() throws IOException { zis.close(); bis.close(); fileInputStream.close(); } }; for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) { if (fileWithinZip.equals(ze.getName())) { return new Pair<InputStream, Closeable>(zis, closeable); } } closeable.close(); return null; }
From source file:org.wildfly.security.sasl.entity.EntityTest.java
private void safeClose(Closeable c) { if (c != null) { try {//from w w w . j a va2s . c om c.close(); } catch (Throwable ignored) { } } }
From source file:org.apache.carbondata.core.util.CarbonUtil.java
/** * This method closes stream/*from w ww .ja va 2 s. co m*/ * * @param stream * @throws IOException */ public static void closeStream(Closeable stream) throws IOException { if (null != stream) { stream.close(); } }
From source file:org.openqa.selendroid.server.model.DefaultSelendroidDriver.java
@Override @SuppressWarnings("deprecation") public byte[] takeScreenshot() { ViewHierarchyAnalyzer viewAnalyzer = ViewHierarchyAnalyzer.getDefaultInstance(); // TODO ddary review later, but with getRecentDecorView() it seems to work better // long drawingTime = 0; // View container = null; // for (View view : viewAnalyzer.getTopLevelViews()) { // if (view != null && view.isShown() && view.hasWindowFocus() // && view.getDrawingTime() > drawingTime) { // container = view; // drawingTime = view.getDrawingTime(); // }//from w w w .j a v a 2 s.c om // } // final View mainView = container; final View mainView = viewAnalyzer.getRecentDecorView(); if (mainView == null) { throw new SelendroidException("No open windows."); } done = false; long end = System.currentTimeMillis() + serverInstrumentation.getAndroidWait().getTimeoutInMillis(); final byte[][] rawPng = new byte[1][1]; ServerInstrumentation.getInstance().getCurrentActivity().runOnUiThread(new Runnable() { public void run() { synchronized (syncObject) { Display display = serverInstrumentation.getCurrentActivity().getWindowManager() .getDefaultDisplay(); Point size = new Point(); try { display.getSize(size); } catch (NoSuchMethodError ignore) { // Older than api level 13 size.x = display.getWidth(); size.y = display.getHeight(); } // Get root view View view = mainView.getRootView(); // Create the bitmap to use to draw the screenshot final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); // Get current theme to know which background to use final Activity activity = serverInstrumentation.getCurrentActivity(); final Theme theme = activity.getTheme(); final TypedArray ta = theme .obtainStyledAttributes(new int[] { android.R.attr.windowBackground }); final int res = ta.getResourceId(0, 0); final Drawable background = activity.getResources().getDrawable(res); // Draw background background.draw(canvas); // Draw views view.draw(canvas); ByteArrayOutputStream stream = new ByteArrayOutputStream(); if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)) { throw new RuntimeException("Error while compressing screenshot image."); } try { stream.flush(); stream.close(); } catch (IOException e) { throw new RuntimeException("I/O Error while capturing screenshot: " + e.getMessage()); } finally { Closeable closeable = (Closeable) stream; try { if (closeable != null) { closeable.close(); } } catch (IOException ioe) { // ignore } } rawPng[0] = stream.toByteArray(); mainView.destroyDrawingCache(); done = true; syncObject.notify(); } } }); waitForDone(end, serverInstrumentation.getAndroidWait().getTimeoutInMillis(), "Failed to take screenshot."); return rawPng[0]; }
From source file:org.apache.hadoop.tools.rumen.Folder.java
public int run() throws IOException { class JobEntryComparator implements Comparator<Pair<LoggedJob, JobTraceReader>> { public int compare(Pair<LoggedJob, JobTraceReader> p1, Pair<LoggedJob, JobTraceReader> p2) { LoggedJob j1 = p1.first();/*from w ww . jav a 2 s . c om*/ LoggedJob j2 = p2.first(); return (j1.getSubmitTime() < j2.getSubmitTime()) ? -1 : (j1.getSubmitTime() == j2.getSubmitTime()) ? 0 : 1; } } // we initialize an empty heap so if we take an error before establishing // a real one the finally code goes through Queue<Pair<LoggedJob, JobTraceReader>> heap = new PriorityQueue<Pair<LoggedJob, JobTraceReader>>(); try { LoggedJob job = reader.nextJob(); if (job == null) { LOG.error("The job trace is empty"); return EMPTY_JOB_TRACE; } // If starts-after time is specified, skip the number of jobs till we reach // the starting time limit. if (startsAfter > 0) { LOG.info("starts-after time is specified. Initial job submit time : " + job.getSubmitTime()); long approximateTime = job.getSubmitTime() + startsAfter; job = reader.nextJob(); long skippedCount = 0; while (job != null && job.getSubmitTime() < approximateTime) { job = reader.nextJob(); skippedCount++; } LOG.debug("Considering jobs with submit time greater than " + startsAfter + " ms. Skipped " + skippedCount + " jobs."); if (job == null) { LOG.error("No more jobs to process in the trace with 'starts-after'" + " set to " + startsAfter + "ms."); return EMPTY_JOB_TRACE; } LOG.info("The first job has a submit time of " + job.getSubmitTime()); } firstJobSubmitTime = job.getSubmitTime(); long lastJobSubmitTime = firstJobSubmitTime; int numberJobs = 0; long currentIntervalEnd = Long.MIN_VALUE; Path nextSegment = null; Outputter<LoggedJob> tempGen = null; if (debug) { LOG.debug("The first job has a submit time of " + firstJobSubmitTime); } final Configuration conf = getConf(); try { // At the top of this loop, skewBuffer has at most // skewBufferLength entries. while (job != null) { final Random tempNameGenerator = new Random(); lastJobSubmitTime = job.getSubmitTime(); ++numberJobs; if (job.getSubmitTime() >= currentIntervalEnd) { if (tempGen != null) { tempGen.close(); } nextSegment = null; for (int i = 0; i < 3 && nextSegment == null; ++i) { try { nextSegment = new Path(tempDir, "segment-" + tempNameGenerator.nextLong() + ".json.gz"); if (debug) { LOG.debug("The next segment name is " + nextSegment); } FileSystem fs = nextSegment.getFileSystem(conf); try { if (!fs.exists(nextSegment)) { break; } continue; } catch (IOException e) { // no code -- file did not already exist } } catch (IOException e) { // no code -- file exists now, or directory bad. We try three // times. } } if (nextSegment == null) { throw new RuntimeException("Failed to create a new file!"); } if (debug) { LOG.debug("Creating " + nextSegment + " for a job with a submit time of " + job.getSubmitTime()); } deletees.add(nextSegment); tempPaths.add(nextSegment); tempGen = new DefaultOutputter<LoggedJob>(); tempGen.init(nextSegment, conf); long currentIntervalNumber = (job.getSubmitTime() - firstJobSubmitTime) / inputCycle; currentIntervalEnd = firstJobSubmitTime + ((currentIntervalNumber + 1) * inputCycle); } // the temp files contain UDadjusted times, but each temp file's // content is in the same input cycle interval. if (tempGen != null) { tempGen.output(job); } job = reader.nextJob(); } } catch (DeskewedJobTraceReader.OutOfOrderException e) { return OUT_OF_ORDER_JOBS; } finally { if (tempGen != null) { tempGen.close(); } } if (lastJobSubmitTime <= firstJobSubmitTime) { LOG.error("All of your job[s] have the same submit time." + " Please just use your input file."); return ALL_JOBS_SIMULTANEOUS; } double submitTimeSpan = lastJobSubmitTime - firstJobSubmitTime; LOG.warn("Your input trace spans " + (lastJobSubmitTime - firstJobSubmitTime) + " ticks."); double foldingRatio = submitTimeSpan * (numberJobs + 1) / numberJobs / inputCycle; if (debug) { LOG.warn("run: submitTimeSpan = " + submitTimeSpan + ", numberJobs = " + numberJobs + ", inputCycle = " + inputCycle); } if (reader.neededSkewBufferSize() > 0) { LOG.warn("You needed a -skew-buffer-length of " + reader.neededSkewBufferSize() + " but no more, for this input."); } double tProbability = timeDilation * concentration / foldingRatio; if (debug) { LOG.warn("run: timeDilation = " + timeDilation + ", concentration = " + concentration + ", foldingRatio = " + foldingRatio); LOG.warn("The transcription probability is " + tProbability); } transcriptionRateInteger = (int) Math.floor(tProbability); transcriptionRateFraction = tProbability - Math.floor(tProbability); // Now read all the inputs in parallel heap = new PriorityQueue<Pair<LoggedJob, JobTraceReader>>(tempPaths.size(), new JobEntryComparator()); for (Path tempPath : tempPaths) { JobTraceReader thisReader = new JobTraceReader(tempPath, conf); closees.add(thisReader); LoggedJob streamFirstJob = thisReader.getNext(); long thisIndex = (streamFirstJob.getSubmitTime() - firstJobSubmitTime) / inputCycle; if (debug) { LOG.debug("A job with submit time of " + streamFirstJob.getSubmitTime() + " is in interval # " + thisIndex); } adjustJobTimes(streamFirstJob); if (debug) { LOG.debug("That job's submit time is adjusted to " + streamFirstJob.getSubmitTime()); } heap.add(new Pair<LoggedJob, JobTraceReader>(streamFirstJob, thisReader)); } Pair<LoggedJob, JobTraceReader> next = heap.poll(); while (next != null) { maybeOutput(next.first()); if (debug) { LOG.debug("The most recent job has an adjusted submit time of " + next.first().getSubmitTime()); LOG.debug(" Its replacement in the heap will come from input engine " + next.second()); } LoggedJob replacement = next.second().getNext(); if (replacement == null) { next.second().close(); if (debug) { LOG.debug("That input engine is depleted."); } } else { adjustJobTimes(replacement); if (debug) { LOG.debug("The replacement has an adjusted submit time of " + replacement.getSubmitTime()); } heap.add(new Pair<LoggedJob, JobTraceReader>(replacement, next.second())); } next = heap.poll(); } } finally { IOUtils.cleanup(null, reader); if (outGen != null) { outGen.close(); } for (Pair<LoggedJob, JobTraceReader> heapEntry : heap) { heapEntry.second().close(); } for (Closeable closee : closees) { closee.close(); } if (!debug) { Configuration conf = getConf(); for (Path deletee : deletees) { FileSystem fs = deletee.getFileSystem(conf); try { fs.delete(deletee, false); } catch (IOException e) { // no code } } } } return 0; }
From source file:com.helpinput.spring.SourceScaner.java
private void closeWithWarning(Closeable c) { if (c != null) { try {// w ww. jav a2 s . c om c.close(); } catch (IOException e) { System.err.println("Caught exception during close(): " + e); } } }
From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java
public synchronized void start(final Class<?> marker, final Properties config, final String... args) throws Exception { if (started) { return;/*from ww w.ja va2 s .c o m*/ } ensureAppInit(marker); started = true; final Class<?> appClass = app.getClass(); final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(ancestors(appClass))); // setup the container config reading class annotation, using a randome http port and deploying the classpath final Configuration configuration = new Configuration(); final ContainerProperties props = appClass.getAnnotation(ContainerProperties.class); if (props != null) { final Properties runnerProperties = new Properties(); for (final ContainerProperties.Property p : props.value()) { final String name = p.name(); if (name.startsWith("tomee.embedded.application.runner.")) { // allow to tune the Configuration // no need to filter there since it is done in loadFromProperties() runnerProperties.setProperty(name.substring("tomee.embedded.application.runner.".length()), p.value()); } else { configuration.property(name, StrSubstitutor.replaceSystemProperties(p.value())); } } if (!runnerProperties.isEmpty()) { configuration.loadFromProperties(runnerProperties); } } configuration.loadFromProperties(System.getProperties()); // overrides, note that some config are additive by design final List<Method> annotatedMethods = finder .findAnnotatedMethods(org.apache.openejb.testing.Configuration.class); if (annotatedMethods.size() > 1) { throw new IllegalArgumentException("Only one @Configuration is supported: " + annotatedMethods); } for (final Method m : annotatedMethods) { final Object o = m.invoke(app); if (Properties.class.isInstance(o)) { final Properties properties = Properties.class.cast(o); if (configuration.getProperties() == null) { configuration.setProperties(new Properties()); } configuration.getProperties().putAll(properties); } else { throw new IllegalArgumentException("Unsupported " + o + " for @Configuration"); } } final Collection<org.apache.tomee.embedded.LifecycleTask> lifecycleTasks = new ArrayList<>(); final Collection<Closeable> postTasks = new ArrayList<>(); final LifecycleTasks tasks = appClass.getAnnotation(LifecycleTasks.class); if (tasks != null) { for (final Class<? extends org.apache.tomee.embedded.LifecycleTask> type : tasks.value()) { final org.apache.tomee.embedded.LifecycleTask lifecycleTask = type.newInstance(); lifecycleTasks.add(lifecycleTask); postTasks.add(lifecycleTask.beforeContainerStartup()); } } final Map<String, Field> ports = new HashMap<>(); { Class<?> type = appClass; while (type != null && type != Object.class) { for (final Field f : type.getDeclaredFields()) { final RandomPort annotation = f.getAnnotation(RandomPort.class); final String value = annotation == null ? null : annotation.value(); if (value != null && value.startsWith("http")) { f.setAccessible(true); ports.put(value, f); } } type = type.getSuperclass(); } } if (ports.containsKey("http")) { configuration.randomHttpPort(); } // at least after LifecycleTasks to inherit from potential states (system properties to get a port etc...) final Configurers configurers = appClass.getAnnotation(Configurers.class); if (configurers != null) { for (final Class<? extends Configurer> type : configurers.value()) { type.newInstance().configure(configuration); } } final Classes classes = appClass.getAnnotation(Classes.class); String context = classes != null ? classes.context() : ""; context = !context.isEmpty() && context.startsWith("/") ? context.substring(1) : context; Archive archive = null; if (classes != null && classes.value().length > 0) { archive = new ClassesArchive(classes.value()); } final Jars jars = appClass.getAnnotation(Jars.class); final List<URL> urls; if (jars != null) { final Collection<File> files = ApplicationComposers.findFiles(jars); urls = new ArrayList<>(files.size()); for (final File f : files) { urls.add(f.toURI().toURL()); } } else { urls = null; } final WebResource resources = appClass.getAnnotation(WebResource.class); if (resources != null && resources.value().length > 1) { throw new IllegalArgumentException("Only one docBase is supported for now using @WebResource"); } String webResource = null; if (resources != null && resources.value().length > 0) { webResource = resources.value()[0]; } else { final File webapp = new File("src/main/webapp"); if (webapp.isDirectory()) { webResource = "src/main/webapp"; } } if (config != null) { // override other config from annotations configuration.loadFromProperties(config); } final Container container = new Container(configuration); SystemInstance.get().setComponent(TomEEEmbeddedArgs.class, new TomEEEmbeddedArgs(args, null)); SystemInstance.get().setComponent(LifecycleTaskAccessor.class, new LifecycleTaskAccessor(lifecycleTasks)); container.deploy(new Container.DeploymentRequest(context, // call ClasspathSearcher that lazily since container needs to be started to not preload logging urls == null ? new DeploymentsResolver.ClasspathSearcher() .loadUrls(Thread.currentThread().getContextClassLoader()).getUrls() : urls, webResource != null ? new File(webResource) : null, true, null, archive)); for (final Map.Entry<String, Field> f : ports.entrySet()) { switch (f.getKey()) { case "http": setPortField(f.getKey(), f.getValue(), configuration, context, app); break; case "https": break; default: throw new IllegalArgumentException("port " + f.getKey() + " not yet supported"); } } SystemInstance.get().addObserver(app); composerInject(app); final AnnotationFinder appFinder = new AnnotationFinder(new ClassesArchive(appClass)); for (final Method mtd : appFinder.findAnnotatedMethods(PostConstruct.class)) { if (mtd.getParameterTypes().length == 0) { if (!mtd.isAccessible()) { mtd.setAccessible(true); } mtd.invoke(app); } } hook = new Thread() { @Override public void run() { // ensure to log errors but not fail there for (final Method mtd : appFinder.findAnnotatedMethods(PreDestroy.class)) { if (mtd.getParameterTypes().length == 0) { if (!mtd.isAccessible()) { mtd.setAccessible(true); } try { mtd.invoke(app); } catch (final IllegalAccessException e) { throw new IllegalStateException(e); } catch (final InvocationTargetException e) { throw new IllegalStateException(e.getCause()); } } } try { container.close(); } catch (final Exception e) { e.printStackTrace(); } for (final Closeable c : postTasks) { try { c.close(); } catch (final IOException e) { e.printStackTrace(); } } postTasks.clear(); app = null; try { SHUTDOWN_TASKS.remove(this); } catch (final Exception e) { // no-op: that's ok at that moment if not called manually } } }; SHUTDOWN_TASKS.put(hook, hook); }
From source file:com.microsoft.live.LiveConnectClient.java
private static void closeSilently(Closeable c) { try {// ww w .j a v a2s. co m c.close(); } catch (Exception e) { // Silently...ssshh } }
From source file:org.openstreetmap.josm.tools.Utils.java
/** * <p>Utility method for closing a {@link java.io.Closeable} object.</p> * * @param c the closeable object. May be null. */// w w w .j a va 2 s. co m public static void close(Closeable c) { if (c == null) return; try { c.close(); } catch (IOException e) { Logging.warn(e); } }
From source file:hudson.cli.CLI.java
/** * Shuts down the channel and closes the underlying connection. *//* w ww . j ava2 s . c o m*/ public void close() throws IOException, InterruptedException { channel.close(); channel.join(); if (ownsPool) pool.shutdown(); for (Closeable c : closables) c.close(); }