Package com.google.common.io

Examples of com.google.common.io.Closer


     * @param requestFactory Request factory for making the request.
     * @param uri            the uri to load data from.
     * @return the data in string form.
     */
    public static String toString(final MfClientHttpRequestFactory requestFactory, final URI uri) throws IOException {
        Closer closer = Closer.create();
        try {
            ClientHttpResponse response = closer.register(requestFactory.createRequest(uri, HttpMethod.GET).execute());

            InputStream input = closer.register(response.getBody());
            InputStreamReader reader = closer.register(new InputStreamReader(input, Constants.DEFAULT_ENCODING));
            BufferedReader bufferedReader = closer.register(new BufferedReader(reader));

            return CharStreams.toString(bufferedReader);
        } finally {
            closer.close();
        }
    }
View Full Code Here


   */
  private List<FeedEvent> extractEntriesFromLogfile(final File logFile, final int entriesToExtract)
      throws IOException
  {
    final List<FeedEvent> entries = Lists.newArrayList();
    Closer closer = Closer.create();
    try {
      final BufferedReader reader =
          Files.newReader(logFile, Charset.forName("UTF-8"));
      String logLine = reader.readLine();
      while (logLine != null) {
        if (logLine.contains(" WARN ") || logLine.contains(" ERROR ")) {

          // FIXME: Grab following stacktrace if any in log
          // if ( StringUtils.isNotEmpty( item.getStackTrace() ) )
          // {
          // // we need <br/> and &nbsp; to display stack trace on RSS
          // String stackTrace = item.getStackTrace().replace(
          // (String) System.getProperties().get( "line.separator" ),
          // "<br/>" );
          // stackTrace = stackTrace.replace( "\t", "&nbsp;&nbsp;&nbsp;&nbsp;" );
          // contentValue.append( "<br/>" ).append( stackTrace );
          // }

          final FeedEvent entry = new FeedEvent(
              "LOG", // ignored
              "ERROR_WARNING", // ignored
              new Date(), // TODO: timestamp from log file?
              null, // author "system"
              null, // no link (maybe log config? or support?)
              Maps.<String, String>newHashMap()
          );
          if (logLine.contains(" ERROR ")) {
            entry.setTitle("Error");
          }
          else if (logLine.contains(" WARN ")) {
            entry.setTitle("Warning");
          }
          entry.setContent(logLine);

          entries.add(entry);
          if (entries.size() > entriesToExtract) {
            entries.remove(0);
          }
        }
        logLine = reader.readLine();
      }
    }
    catch (Throwable e) {
      throw closer.rethrow(e);
    }
    finally {
      closer.close();
    }
    return Lists.reverse(entries);
  }
View Full Code Here

   * @return a not {@code null Set} of service class names.
   * @throws IOException
   */
  static Set<String> readServiceFile(InputStream input) throws IOException {
    HashSet<String> serviceClasses = new HashSet<String>();
    Closer closer = Closer.create();
    try {
      // TODO(gak): use CharStreams
      BufferedReader r = closer.register(new BufferedReader(new InputStreamReader(input, UTF_8)));
      String line;
      while ((line = r.readLine()) != null) {
        int commentStart = line.indexOf('#');
        if (commentStart >= 0) {
          line = line.substring(0, commentStart);
        }
        line = line.trim();
        if (!line.isEmpty()) {
          serviceClasses.add(line);
        }
      }
      return serviceClasses;
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      closer.close();
    }
  }
View Full Code Here

        return reportURI.getScheme().equals("file");
    }

    @Override
    public final void loadReport(final URI reportURI, final OutputStream out) throws IOException {
        Closer closer = Closer.create();
        try {
            FileInputStream in = closer.register(new FileInputStream(reportURI.getPath()));
            FileChannel channel = closer.register(in.getChannel());
            channel.transferTo(0, Long.MAX_VALUE, Channels.newChannel(out));
        } finally {
            closer.close();
        }
    }
View Full Code Here

            final String graphicFile,
            final Color backgroundColor,
            final Double rotation,
            final File workingDir,
            final MfClientHttpRequestFactory clientHttpRequestFactory) throws Exception {
        final Closer closer = Closer.create();
        try {
            final RasterReference input = loadGraphic(graphicFile, clientHttpRequestFactory, closer);
            if (graphicFile == null || graphicFile.toLowerCase().trim().endsWith("svg")) {
                return createSvg(targetSize, input, rotation, backgroundColor, workingDir, clientHttpRequestFactory);
            } else {
                return createRaster(targetSize, input, rotation, backgroundColor, workingDir);
            }
        } finally {
            closer.close();
        }
    }
View Full Code Here

  /**
   * Create a temporary ANT file for executing JUnit4 ANT task.
   */
  private File createTemporaryAntFile(Document doc) throws IOException {
    Closer closer = Closer.create();
    try {
      File antFile = File.createTempFile("junit4-ant-", ".xml", dir);
      OutputStream os = closer.register(new FileOutputStream(antFile));
      XMLWriter xmlWriter = new XMLWriter(os, OutputFormat.createPrettyPrint());
      xmlWriter.write(doc);
      return antFile;
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      closer.close();
    }
  }
View Full Code Here

      public void receiveQuit(QuitEvent e) {
        slave.end = System.currentTimeMillis();
      }     
    });

    Closer closer = Closer.create();
    closer.register(eventStream);
    closer.register(w);
    try {
      OutputStream sysout = closer.register(new BufferedOutputStream(new FileOutputStream(sysoutFile)));
      OutputStream syserr = closer.register(new BufferedOutputStream(new FileOutputStream(syserrFile)));
      RandomAccessFile streamsBuffer = closer.register(new RandomAccessFile(streamsBufferFile, "rw"));

      Execute execute = forkProcess(slave, eventBus, commandline, eventStream, sysout, syserr, streamsBuffer);
      log("Forked JVM J" + slave.id + " finished with exit code: " + execute.getExitValue(), Project.MSG_DEBUG);

      if (execute.isFailure()) {
        final int exitStatus = execute.getExitValue();
        switch (exitStatus) {
          case SlaveMain.ERR_NO_JUNIT:
            throw new BuildException("Forked JVM's classpath must include a junit4 JAR.");
          case SlaveMain.ERR_OLD_JUNIT:
            throw new BuildException("Forked JVM's classpath must use JUnit 4.10 or newer.");
          default:
            Closeables.close(sysout, false);
            Closeables.close(syserr, false);

            StringBuilder message = new StringBuilder();
            if (exitStatus == SlaveMain.ERR_OOM) {
              message.append("Forked JVM ran out of memory.");
            } else {
              message.append("Forked process returned with error code: ").append(exitStatus).append(".");
            }

            if (sysoutFile.length() > 0 || syserrFile.length() > 0) {
              if (exitStatus != SlaveMain.ERR_OOM) {
                message.append(" Very likely a JVM crash. ");
              }

              if (jvmOutputAction.contains(JvmOutputAction.PIPE)) {
                message.append(" Process output piped in logs above.");
              } else if (!jvmOutputAction.contains(JvmOutputAction.IGNORE)) {
                if (sysoutFile.length() > 0) {
                  message.append(" See process stdout at: " + sysoutFile.getAbsolutePath());
                }
                if (syserrFile.length() > 0) {
                  message.append(" See process stderr at: " + syserrFile.getAbsolutePath());
                }
              }
            }
            throw new BuildException(message.toString());
        }
      }
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      try {
        closer.close();
      } finally {
        Files.asByteSource(classNamesDynamic).copyTo(Files.asByteSink(classNamesFile, FileWriteMode.APPEND));
        classNamesDynamic.delete();
        streamsBufferFile.delete();
       
View Full Code Here

                name = "ratings-" + UUID.randomUUID().toString() + ".csv";
            }
            logger.info("writing ratings to {}", name);
            File file = new File(workingDir, name);
            try {
                Closer closer = Closer.create();
                try {
                    PrintWriter writer = closer.register(new PrintWriter(file));
                    Cursor<Rating> ratings = closer.register(eventDAO.streamEvents(Rating.class));
                    for (Rating r: ratings) {
                        writer.printf("%d,%d,", r.getUserId(), r.getItemId());
                        Preference p = r.getPreference();
                        if (p != null) {
                            writer.print(p.getValue());
                        }
                        writer.print(",");
                        long ts = r.getTimestamp();
                        if (ts >= 0) {
                            writer.print(ts);
                        }
                        writer.println();
                    }
                } catch (Throwable th) {
                    throw closer.rethrow(th);
                } finally {
                    closer.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("Error creating ratings file", e);
            }
            return name;
View Full Code Here

                name = prefix + "-" + UUID.randomUUID().toString() + ".csv";
            }
            logger.info("writing {} to {}", prefix, name);
            File file = new File(workingDir, name);
            try {
                Closer closer = Closer.create();
                try {
                    PrintWriter writer = closer.register(new PrintWriter(file));
                    LongSet ids = getIds();
                    LongIterator iter = ids.iterator();
                    while (iter.hasNext()) {
                        writer.println(iter.nextLong());
                    }
                } catch (Throwable th) {
                    throw closer.rethrow(th);
                } finally {
                    closer.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("Error creating ratings file", e);
            }
            return name;
View Full Code Here

            if (cacheDir.mkdirs()) {
                logger.debug("created cache directory {}", cacheDir);
            }
            StagedWrite stage = StagedWrite.begin(cacheFile);
            try {
                Closer closer = Closer.create();
                try {
                    OutputStream out = closer.register(stage.openOutputStream());
                    OutputStream gzOut = closer.register(new GZIPOutputStream(out));
                    ObjectOutputStream objOut = closer.register(new ObjectOutputStream(gzOut));
                    objOut.writeObject(obj);
                } catch (Throwable th) {
                    throw closer.rethrow(th);
                } finally {
                    closer.close();
                }
                stage.commit();
            } finally {
                stage.close();
            }
View Full Code Here

TOP

Related Classes of com.google.common.io.Closer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.