Java Code Examples for org.apache.commons.compress.utils.IOUtils#closeQuietly()

The following examples show how to use org.apache.commons.compress.utils.IOUtils#closeQuietly() . 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: JavaScriptCompilerMojo.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Create a source map file corresponding to the given compiled js file.
 *
 * @param output The compiled js file
 * @param sourceMap The {@link SourceMap} retrieved from the compiler
 * @throws WatchingException If an IOException occurred while creating the source map file.
 */
private void createSourceMapFile(File output,SourceMap sourceMap) throws WatchingException{
    if (googleClosureMap) {
        PrintWriter mapWriter = null;
        File mapFile = new File(output.getPath() + ".map");
        FileUtils.deleteQuietly(mapFile);

        try {
            mapWriter = new PrintWriter(mapFile, Charset.defaultCharset().name());
            sourceMap.appendTo(mapWriter, output.getName());
            FileUtils.write(output, "\n//# sourceMappingURL=" + mapFile.getName(), true);
        } catch (IOException e) {
            throw new WatchingException("Cannot create source map file for JavaScript file '" +
                    output.getAbsolutePath() + "'", e);
        } finally {
            IOUtils.closeQuietly(mapWriter);
        }
    }
}
 
Example 2
Source File: KafkaAvroPublisher.java    From doctorkafka with Apache License 2.0 6 votes vote down vote up
public void publish(BrokerStats brokerStats) throws IOException {
  try {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream, null);

    avroEventWriter.write(brokerStats, binaryEncoder);
    binaryEncoder.flush();
    IOUtils.closeQuietly(stream);

    String key = brokerStats.getName() + "_" + System.currentTimeMillis();
    int numPartitions = kafkaProducer.partitionsFor(destTopic).size();
    int partition = brokerStats.getId() % numPartitions;

    Future<RecordMetadata> future = kafkaProducer.send(
        new ProducerRecord<>(destTopic, partition, key.getBytes(), stream.toByteArray()));
    future.get();

    OpenTsdbMetricConverter.incr("kafka.stats.collector.success", 1, "host=" + HOSTNAME);
  } catch (Exception e) {
    LOG.error("Failure in publish stats", e);
    OpenTsdbMetricConverter.incr("kafka.stats.collector.failure", 1, "host=" + HOSTNAME);
    throw new RuntimeException("Avro serialization failure", e);
  }
}
 
Example 3
Source File: DoctorKafkaActionReporter.java    From doctorkafka with Apache License 2.0 6 votes vote down vote up
public synchronized void sendMessage(String clusterName, String message) {
  int numRetries = 0;
  while (numRetries < MAX_RETRIES) {
    try {
      long timestamp = System.currentTimeMillis();
      OperatorAction operatorAction = new OperatorAction(timestamp, clusterName, message);

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      BinaryEncoder binaryEncoder = avroEncoderFactory.binaryEncoder(stream, null);
      avroWriter.write(operatorAction, binaryEncoder);
      binaryEncoder.flush();
      IOUtils.closeQuietly(stream);

      String key = Long.toString(System.currentTimeMillis());
      ProducerRecord<byte[], byte[]>  producerRecord = 
          new ProducerRecord<>(topic, key.getBytes(), stream.toByteArray());
      Future<RecordMetadata> future = kafkaProducer.send(producerRecord);
      future.get();
      LOG.info("Send an message {} to action report : ", message);
      break;
    } catch (Exception e) {
      LOG.error("Failed to publish report message {}: {}", clusterName, message, e);
      numRetries++;
    }
  }
}
 
Example 4
Source File: GzipUtils.java    From talent-aio with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static byte[] gZip(byte[] data) throws IOException
{
	byte[] ret = null;
	ByteArrayOutputStream bos = null;
	GZIPOutputStream gzip = null;
	try
	{
		bos = new ByteArrayOutputStream();
		gzip = new GZIPOutputStream(bos);
		gzip.write(data);
		gzip.finish();
		ret = bos.toByteArray();
	} finally
	{
		IOUtils.closeQuietly(gzip);
		IOUtils.closeQuietly(bos);
	}
	return ret;
}
 
Example 5
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public void create(final String image, final InputStream imagePayload,
                   final ProgressHandler handler)
    throws DockerException, InterruptedException {
  WebTarget resource = resource().path("images").path("create");

  resource = resource
      .queryParam("fromSrc", "-")
      .queryParam("tag", image);

  final CreateProgressHandler createProgressHandler = new CreateProgressHandler(handler);
  final Entity<InputStream> entity = Entity.entity(imagePayload,
                                                   APPLICATION_OCTET_STREAM);
  try {
    requestAndTail(POST, createProgressHandler, resource,
            resource.request(APPLICATION_JSON_TYPE), entity);
    tag(createProgressHandler.getImageId(), image, true);
  } finally {
    IOUtils.closeQuietly(imagePayload);
  }
}
 
Example 6
Source File: StreamingJsonCompleteDataSetRegistrations.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void close()
{
    if ( jsonGenerator == null )
    {
        return;
    }

    try
    {
        if ( startedArray.get() )
        {
            jsonGenerator.writeEndArray();
        }

        jsonGenerator.writeEndObject();
    }
    catch ( IOException ignored )
    {
    }
    finally
    {
        IOUtils.closeQuietly( jsonGenerator );
    }
}
 
Example 7
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> load(final InputStream imagePayload, final ProgressHandler handler)
    throws DockerException, InterruptedException {
  final WebTarget resource = resource()
          .path("images")
          .path("load")
          .queryParam("quiet", "false");

  final LoadProgressHandler loadProgressHandler = new LoadProgressHandler(handler);
  final Entity<InputStream> entity = Entity.entity(imagePayload, APPLICATION_OCTET_STREAM);

  try (final ProgressStream load =
          request(POST, ProgressStream.class, resource,
                  resource.request(APPLICATION_JSON_TYPE), entity)) {
    load.tail(loadProgressHandler, POST, resource.getUri());
    return loadProgressHandler.getImageNames();
  } catch (IOException e) {
    throw new DockerException(e);
  } finally {
    IOUtils.closeQuietly(imagePayload);
  }
}
 
Example 8
Source File: ExtractionTools.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {
    final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        final File entryDestination = getDestinationFile(destination, entry.getName());

        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            final InputStream in = zipFile.getInputStream(entry);
            try (final OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}
 
Example 9
Source File: FileSystemTargetRepository.java    From ache with Apache License 2.0 6 votes vote down vote up
private Path readNext() {
    if(fileIt != null && !fileIt.hasNext()) {
        IOUtils.closeQuietly(filesStream); // no more files on this folder, close it.
        if(!hostIt.hasNext()) {
            IOUtils.closeQuietly(hostsStream);
            return null; // no more file and folders available
        }
        // iterate over next folder available
        Path hostPath = null;
        try {
            hostPath = hostIt.next();
            filesStream = Files.newDirectoryStream(hostPath);
            fileIt = filesStream.iterator();
        } catch (IOException e) {
            String f = hostPath == null ? null : hostPath.toString();
            throw new IllegalArgumentException("Failed to open host folder: "+f, e);
        }
    }
    
    if(fileIt != null && fileIt.hasNext()) {
        return fileIt.next();
    }
    
    return null;
}
 
Example 10
Source File: LayeredColorMaskTexture.java    From Et-Futurum with The Unlicense 5 votes vote down vote up
private BufferedImage readBufferedImage(InputStream imageStream) throws IOException {
	BufferedImage bufferedimage;

	try {
		bufferedimage = ImageIO.read(imageStream);
	} finally {
		IOUtils.closeQuietly(imageStream);
	}

	return bufferedimage;
}
 
Example 11
Source File: Properties2HoconConverter.java    From wisdom with Apache License 2.0 5 votes vote down vote up
private static Properties readFileAsProperties(File props) throws IOException {
    Properties properties = new Properties();
    InputStream stream = null;
    try {
        stream = FileUtils.openInputStream(props);
        properties.load(stream);
        return properties;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}
 
Example 12
Source File: CompressionFileUtil.java    From Jpom with MIT License 5 votes vote down vote up
private static List<String> unTar(InputStream inputStream, File destDir) throws Exception {
    List<String> fileNames = new ArrayList<>();
    TarArchiveInputStream tarIn = new TarArchiveInputStream(inputStream, BUFFER_SIZE, CharsetUtil.GBK);
    TarArchiveEntry entry;
    try {
        while ((entry = tarIn.getNextTarEntry()) != null) {
            fileNames.add(entry.getName());
            if (entry.isDirectory()) {
                //是目录
                FileUtil.mkdir(new File(destDir, entry.getName()));
                //创建空目录
            } else {
                //是文件
                File tmpFile = new File(destDir, entry.getName());
                //创建输出目录
                FileUtil.mkParentDirs(destDir);
                OutputStream out = null;
                try {
                    out = new FileOutputStream(tmpFile);
                    int length;
                    byte[] b = new byte[2048];
                    while ((length = tarIn.read(b)) != -1) {
                        out.write(b, 0, length);
                    }
                } finally {
                    IOUtils.closeQuietly(out);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(tarIn);
    }
    return fileNames;
}
 
Example 13
Source File: MavenTestHelper.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public Metadata parseMetadata(final InputStream is) throws Exception {
  try {
    assertThat(is, notNullValue());
    return reader.read(is);
  }
  finally {
    IOUtils.closeQuietly(is);
  }
}
 
Example 14
Source File: Dom4j.java    From cuba with Apache License 2.0 5 votes vote down vote up
public static Document readDocument(File file, SAXReader xmlReader) {
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file);
        return readDocument(inputStream, xmlReader);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Unable to read XML from file", e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 15
Source File: BasicExtractor.java    From embedded-rabbitmq with Apache License 2.0 5 votes vote down vote up
protected static void extractFile(InputStream archive, File destPath, String fileName) {
  BufferedOutputStream output = null;
  try {
    LOGGER.debug("Extracting '{}'...", fileName);
    output = new BufferedOutputStream(new FileOutputStream(destPath));
    IOUtils.copy(archive, output);
  } catch (IOException e) {
    throw new ExtractionException("Error extracting file '" + fileName + "' ", e);
  } finally {
    IOUtils.closeQuietly(output);
  }
}
 
Example 16
Source File: ZipUtil.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 添加文件到Zip
 * @param file
 * @param out
 * @param entryPath
 */
private static void addFileToZip(File file, ZipArchiveOutputStream out, String entryPath) {
    InputStream ins = null;
    try {
         
        String path=entryPath + file.getName();
        if(file.isDirectory()){
            path=formatDirPath(path); //为了在压缩文件中包含空文件夹
        }
        ZipArchiveEntry entry = new ZipArchiveEntry(path);
        entry.setTime(file.lastModified());
        // entry.setSize(files[i].length());
        out.putArchiveEntry(entry);
        if(!file.isDirectory()){
            ins = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
            IOUtils.copy(ins, out);
        }
        out.closeArchiveEntry();
    } catch (IOException e) {
      //  e.printStackTrace();
    	if (logger.isErrorEnabled()) {
         logger.error("添加文件到Zip",e);
     }
    } finally {
        IOUtils.closeQuietly(ins);
    }
}
 
Example 17
Source File: FileSystemTargetRepository.java    From ache with Apache License 2.0 4 votes vote down vote up
@Override
public void close() {
    IOUtils.closeQuietly(filesStream);
    IOUtils.closeQuietly(hostsStream);
}
 
Example 18
Source File: FilesTargetRepository.java    From ache with Apache License 2.0 4 votes vote down vote up
public void close() {
    IOUtils.closeQuietly(currentFile);
}
 
Example 19
Source File: FilesTargetRepository.java    From ache with Apache License 2.0 4 votes vote down vote up
@Override
public void close() {
    IOUtils.closeQuietly(linesReader);
    IOUtils.closeQuietly(filesStream);
}
 
Example 20
Source File: WarcTargetRepository.java    From ache with Apache License 2.0 4 votes vote down vote up
@Override
public void close() {
    IOUtils.closeQuietly(warcReader);
    IOUtils.closeQuietly(filesStream);
}