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

The following examples show how to use org.apache.commons.io.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: CertServiceImpl.java    From cosmic with Apache License 2.0 7 votes vote down vote up
public PrivateKey parsePrivateKey(final String key, final String password) throws IOException {

        PasswordFinder pGet = null;

        if (password != null) {
            pGet = new KeyPassword(password.toCharArray());
        }

        final PEMReader privateKey = new PEMReader(new StringReader(key), pGet);
        Object obj = null;
        try {
            obj = privateKey.readObject();
        } finally {
            IOUtils.closeQuietly(privateKey);
        }

        try {

            if (obj instanceof KeyPair) {
                return ((KeyPair) obj).getPrivate();
            }

            return (PrivateKey) obj;
        } catch (final Exception e) {
            throw new IOException("Invalid Key format or invalid password.", e);
        }
    }
 
Example 2
Source File: Timer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void saveData(String op) {
    try {
        File f = new File(DATA_DIR, op.replace(" ", "_") + ".txt");
        if (!f.createNewFile()) {
            throw new IOException("Couldn't create file: " + f);
        }
        OutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
        for (Long duration : stats.get(op)) {
            IOUtils.write(duration.toString(), stream, "UTF-8");
            IOUtils.write("\n", stream, "UTF-8");
        }
        stream.flush();
        IOUtils.closeQuietly(stream);
    } catch (IOException ex) {
        log.error("Unable to save data for operation '" + op + "'", ex);
    }
}
 
Example 3
Source File: CrawlersManager.java    From ache with Apache License 2.0 6 votes vote down vote up
private void unzipFile(Path file, Path outputDir) throws IOException {
    ZipFile zipFile = new ZipFile(file.toFile());
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith("training_data")) {
                logger.info("Skiping training_data folder/file.");
                continue;
            }
            File entryDestination = new File(outputDir.toFile(), entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    } finally {
        zipFile.close();
    }
}
 
Example 4
Source File: DriverUnregisterer.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void run(ClassLoader loader) throws Throwable {
	if (loader instanceof ClassDefinitionFactory) {
		ClassDefinitionFactory factory = (ClassDefinitionFactory) loader;
		final ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
		try {
			Thread.currentThread().setContextClassLoader(DriverUnregisterer.class.getClassLoader()); // prevents CLO-4787
			// get DriverUnregisterer's code, load it using driver's class loader and perform deregistration
			InputStream classData = DriverUnregisterer.class.getResourceAsStream(DriverUnregisterer.class.getSimpleName().concat(".class"));
			byte classBytes[] = IOUtils.toByteArray(classData);
			IOUtils.closeQuietly(classData);
			Class<?> unregisterer = factory.defineClass(DriverUnregisterer.class.getName(), classBytes);
			Method unregister = unregisterer.getMethod("unregisterDrivers", ClassLoader.class);
			unregister.invoke(null, loader);
		} finally {
			Thread.currentThread().setContextClassLoader(originalLoader);
		}
	}
}
 
Example 5
Source File: MonetaTopicListServlet.java    From moneta with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	// TODO Implement security check
	
	SearchResult searchResult = null;
	response.setContentType("text/json");
	
	try{
		searchResult = new Moneta().findAllTopics();
		ServletUtils.writeResult(searchResult, response.getOutputStream());
	}
	catch (Exception e) {
		response.setStatus(500);
		ServletUtils.writeError(500, e, response.getOutputStream());
	}
					
	IOUtils.closeQuietly(response.getOutputStream());
}
 
Example 6
Source File: CassandraArchiveRepositoryTest.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() throws Exception {
    gateway = mock(CassandraGateway.class);
    Keyspace mockKeyspace = mock(Keyspace.class);
    when(mockKeyspace.getKeyspaceName()).thenReturn("testKeySpace");

    when(gateway.getKeyspace()).thenReturn(mockKeyspace);
    when(gateway.getColumnFamily()).thenReturn("testColumnFamily");

    config = new BasicCassandraRepositoryConfig.Builder(gateway)
        .setRepositoryId("TestRepo")
        .setArchiveOutputDirectory(Files.createTempDirectory(this.getClass().getSimpleName() + "_"))
        .build();
    repository = new CassandraArchiveRepository(config);


    URL testJarUrl = getClass().getClassLoader().getResource(TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    if (testJarUrl == null) {
        fail("Couldn't locate " + TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    }
    testArchiveJarFile = Files.createTempFile(TestResource.TEST_HELLOWORLD_JAR.getModuleId().toString(), ".jar");
    InputStream inputStream = testJarUrl.openStream();
    Files.copy(inputStream, testArchiveJarFile, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(inputStream);
}
 
Example 7
Source File: ResourceScanner.java    From AsyncDao with MIT License 5 votes vote down vote up
private static void findFileInJarWithinJar(String filePath, String packagePath, Set<String> classes) throws IOException {
    URL url = new URL("jar", null, 0, filePath);
    URLConnection con = url.openConnection();
    if (con instanceof JarURLConnection) {
        JarURLConnection jarURLConnection = (JarURLConnection) con;
        JarInputStream jarInputStream = new JarInputStream(jarURLConnection.getInputStream());
        JarEntry entry;
        while ((entry = jarInputStream.getNextJarEntry()) != null) {
            filterClass(entry.getName(), packagePath, classes);
        }
        IOUtils.closeQuietly(jarInputStream);
    }
}
 
Example 8
Source File: GenTableServiceImpl.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 批量生成代码
 * 
 * @param tableNames 表数组
 * @return 数据
 */
@Override
public byte[] generatorCode(String[] tableNames)
{
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(outputStream);
    for (String tableName : tableNames)
    {
        generatorCode(tableName, zip);
    }
    IOUtils.closeQuietly(zip);
    return outputStream.toByteArray();
}
 
Example 9
Source File: WithingsAccount.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, String> store(Map<String, String> config, File file) throws IOException {
    FileOutputStream os = new FileOutputStream(file);

    List<String> lines = new ArrayList<String>();
    for (Entry<String, String> line : config.entrySet()) {
        String value = isBlank(line.getValue()) ? "" : "=" + line.getValue();
        lines.add(line.getKey() + value);
    }

    IOUtils.writeLines(lines, System.getProperty("line.separator"), os);
    IOUtils.closeQuietly(os);
    return config;
}
 
Example 10
Source File: JasperSmokeTest.java    From yarg with Apache License 2.0 5 votes vote down vote up
@Test
public void jasperTestDoc() throws Exception {
    BandData root = createRootTree();

    FileOutputStream outputStream = new FileOutputStream("./result/smoke/jasper-result.doc");
    ReportFormatter formatter = new DefaultFormatterFactory().createFormatter(new FormatterFactoryInput("jasper", root,
            new ReportTemplateImpl("", "test.jasper", "./modules/core/test/smoketest/test.jasper", ReportOutputType.doc), outputStream));
    formatter.renderDocument();

    IOUtils.closeQuietly(outputStream);
}
 
Example 11
Source File: ActiveDocument.java    From eclipse-encoding-plugin with Eclipse Public License 1.0 5 votes vote down vote up
protected String getContentString() {
	InputStream inputStream = getInputStream();
	try {
		return IOUtils.toString(inputStream, getCurrentEncoding());
	} catch (IOException e) {
		throw new IllegalStateException(e);
	} finally {
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example 12
Source File: JedisScoredQueueStore.java    From vscrawler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(String queueID, ResourceItem e) {
    if (!lockQueue(queueID)) {
        return false;
    }
    Jedis jedis = jedisPool.getResource();
    try {
        String dataJson = jedis.hget(makeDataKey(queueID), e.getKey());
        jedis.hset(makeDataKey(queueID), e.getKey(), JSONObject.toJSONString(e));
        return !isNil(dataJson);
    } finally {
        IOUtils.closeQuietly(jedis);
        unLockQueue(queueID);
    }
}
 
Example 13
Source File: MultipartController.java    From nio-multipart with Apache License 2.0 5 votes vote down vote up
static Metadata unmarshalMetadata(final InputStream inputStream){
    try {
        return GSON.fromJson(new BufferedReader(new InputStreamReader(inputStream)), Metadata.class);
    }finally {
        IOUtils.closeQuietly(inputStream);
    }
}
 
Example 14
Source File: DFSInputStream.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void releaseBuffer(ByteBuffer buffer) {
  if (buffer == EMPTY_BUFFER) return;
  Object val = getExtendedReadBuffers().remove(buffer);
  if (val == null) {
    throw new IllegalArgumentException("tried to release a buffer " +
        "that was not created by this stream, " + buffer);
  }
  if (val instanceof ClientMmap) {
    IOUtils.closeQuietly((ClientMmap)val);
  } else if (val instanceof ByteBufferPool) {
    ((ByteBufferPool)val).putBuffer(buffer);
  }
}
 
Example 15
Source File: ExtractFile.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private OutputStream getAppStream(String app) throws Exception {
    File archive = new File(parentDir, getFileName(app));
    OutputStream f = null;

    try {
        f = new BufferedOutputStream(new FileOutputStream(archive));
        createTarFile(archive);

        archiveFiles.put(app, archive);

        final Pair<Cipher, SecretKey> cipherSecretKeyPair = getCiphers();

        byte[] ivBytes = cipherSecretKeyPair.getLeft().getIV();
        byte[] secretBytes = cipherSecretKeyPair.getRight().getEncoded();

        PublicKey publicKey = getApplicationPublicKey(app);
        byte[] encryptedIV = encryptDataWithRSAPublicKey(ivBytes, publicKey);
        byte[] encryptedSecret = encryptDataWithRSAPublicKey(secretBytes, publicKey);

        f.write(encryptedIV);
        f.write(encryptedSecret);

         return new CipherOutputStream(f, cipherSecretKeyPair.getLeft());
    } catch(Exception e) {
        IOUtils.closeQuietly(f);
        throw e;
    }
}
 
Example 16
Source File: UrlsetTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSerializeDeserializeUrlset() throws Exception {

  Urlset urlset = createUrlset();
  String output1 = asXml(urlset);
  //System.out.println(output1);

  InputStream in = IOUtils.toInputStream(output1);
  RsRoot returned = (RsRoot) jaxbUnmarshaller.unmarshal(in);
  IOUtils.closeQuietly(in);
  String output2 = asXml(returned);
  //System.out.println(output2);

  assertThat(output2, equalTo(output1));
}
 
Example 17
Source File: HBaseResourceStore.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected void putSmallResource(String resPath, ContentWriter content, long ts) throws IOException {
    byte[] row = Bytes.toBytes(resPath);
    byte[] bytes = content.extractAllBytes();

    Table table = getConnection().getTable(TableName.valueOf(tableName));
    RollbackablePushdown pushdown = null;
    try {
        if (bytes.length > kvSizeLimit) {
            pushdown = writePushdown(resPath, ContentWriter.create(bytes));
            bytes = BytesUtil.EMPTY_BYTE_ARRAY;
        }

        Put put = new Put(row);
        put.addColumn(B_FAMILY, B_COLUMN, bytes);
        put.addColumn(B_FAMILY, B_COLUMN_TS, Bytes.toBytes(ts));

        table.put(put);

    } catch (Exception ex) {
        if (pushdown != null)
            pushdown.rollback();
        throw ex;
    } finally {
        if (pushdown != null)
            pushdown.close();
        IOUtils.closeQuietly(table);
    }
}
 
Example 18
Source File: TestAsyncSingleRequestRpcRetryingCaller.java    From hbase with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void tearDownAfterClass() throws Exception {
  IOUtils.closeQuietly(CONN);
  TEST_UTIL.shutdownMiniCluster();
}
 
Example 19
Source File: AbstractDebugServer.java    From unidbg with Apache License 2.0 4 votes vote down vote up
private void runServer() {
    selector = null;
    serverSocketChannel = null;
    socketChannel = null;
    try {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.socket().bind(new InetSocketAddress(DEFAULT_PORT));

        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    } catch(IOException ex) {
        throw new IllegalStateException(ex);
    }

    serverShutdown = false;
    serverRunning = true;

    System.err.println("Start " + this + " server on port: " + DEFAULT_PORT);
    onServerStart();

    while(serverRunning) {
        try {
            int count = selector.select(50);
            if (count <= 0) {
                if (!isDebuggerConnected() && System.in.available() > 0) {
                    String line = new Scanner(System.in).nextLine();
                    if ("c".equals(line)) {
                        serverRunning = false;
                        break;
                    } else {
                        System.out.println("c: continue");
                    }
                }
                continue;
            }

            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = selectedKeys.next();
                if (key.isValid()) {
                    if (key.isAcceptable()) {
                        onSelectAccept(key);
                    }
                    if (key.isReadable()) {
                        onSelectRead(key);
                    }
                    if (key.isWritable()) {
                        onSelectWrite(key);
                    }
                }
                selectedKeys.remove();
            }

            processInput(input);
        } catch(Throwable e) {
            if (log.isDebugEnabled()) {
                log.debug("run server ex", e);
            }
        }
    }

    IOUtils.closeQuietly(serverSocketChannel);
    serverSocketChannel = null;
    IOUtils.closeQuietly(selector);
    selector = null;
    closeSocketChannel();
    resumeRun();
}
 
Example 20
Source File: FileUploading.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected void uploadFileIntoStorage(UUID fileId, FileDescriptor fileDescr,
                                     @Nullable UploadToStorageProgressListener listener)
        throws FileStorageException, InterruptedException {

    checkNotNullArgument(fileDescr);

    File file = getFile(fileId);
    if (file == null) {
        throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fileDescr.getName());
    }

    long fileSize = file.length();

    LazySupplier<InputStream> inputStreamSupplier = LazySupplier.of(() -> {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new FileLoader.InputStreamSupplierException("Temp file is not found " + file.getAbsolutePath());
        }
    });

    if (listener != null) {
        @SuppressWarnings("UnnecessaryLocalVariable")
        UploadToStorageProgressListener nonnullListener = listener;

        fileLoader.saveStream(fileDescr, inputStreamSupplier, transferredBytes -> {
            try {
                nonnullListener.progressChanged(fileId, transferredBytes, fileSize);
            } catch (InterruptedException ie) {
                // if thread is already interrupted we will restore interrupted flag
                Thread.currentThread().interrupt();
            }
        });
    } else {
        fileLoader.saveStream(fileDescr, inputStreamSupplier);
    }

    if (inputStreamSupplier.supplied()) {
        IOUtils.closeQuietly(inputStreamSupplier.get());
    }
}