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

The following are Jave code examples for showing how to use closeQuietly() of the org.apache.commons.io.IOUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: docx4j-template   File: Docx4jUtils.java   View Source Code Vote up 8 votes
/**
 * 把docx转成html
 * @param docxFilePath
 * @param htmlPath
 * @throws Exception
 */
public static void docxToHtml(String docxFilePath, String htmlPath) throws Exception {
	OutputStream output = null;
	try {
		//
		WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(new File(docxFilePath));

		WMLPACKAGE_BUILDER.configChineseFonts(wmlPackage).configSimSunFont(wmlPackage);
		
		WMLPACKAGE_WRITER.writeToHtml(wmlPackage, htmlPath);

	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {
		IOUtils.closeQuietly(output);
	}

}
 
Example 2
Project: ureport   File: DesignerServletAction.java   View Source Code Vote up 6 votes
public void saveReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String file=req.getParameter("file");
	file=ReportUtils.decodeFileName(file);
	String content=req.getParameter("content");
	ReportProvider targetReportProvider=null;
	for(ReportProvider provider:reportProviders){
		if(file.startsWith(provider.getPrefix())){
			targetReportProvider=provider;
			break;
		}
	}
	if(targetReportProvider==null){
		throw new ReportDesignException("File ["+file+"] not found available report provider.");
	}
	targetReportProvider.saveReport(file, content);
	InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
	ReportDefinition reportDef=reportParser.parse(inputStream, file);
	reportRender.rebuildReportDefinition(reportDef);
	CacheUtils.cacheReportDefinition(file, reportDef);
	IOUtils.closeQuietly(inputStream);
}
 
Example 3
Project: NoMoreOversleeps   File: WebServlet.java   View Source Code Vote up 6 votes
private void sendFavicon(HttpServletResponse response) throws IOException
{
	InputStream fis = null;
	OutputStream out = null;
	try
	{
		response.setContentType("image/x-icon");
		fis = WebServlet.class.getResourceAsStream("/resources/icon.ico");
		out = response.getOutputStream();
		IOUtils.copy(fis, out);
	}
	finally
	{
		IOUtils.closeQuietly(out);
		IOUtils.closeQuietly(fis);
	}
	return;
}
 
Example 4
Project: aliyun-cupid-sdk   File: OdpsCltWrapper.java   View Source Code Vote up 5 votes
private static URL[] tryExtractSparkLibZip(String sparkLibZipPath, String extractTo) throws IOException {
    java.util.zip.ZipFile zipFile = new ZipFile(sparkLibZipPath);
    List<URL> urls = new ArrayList<>();

    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(extractTo, entry.getName());
            urls.add(entryDestination.toURI().toURL());
            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();
    }

    return urls.toArray(new URL[urls.size()]);
}
 
Example 5
Project: uflo   File: ProcessParser.java   View Source Code Vote up 5 votes
public static ProcessDefinition parseProcess(byte[] bytes,long processId,boolean parseChildren) throws Exception{
	ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
	try{
		SAXReader reader=new SAXReader();
		Document document=reader.read(bin);
		Element root=document.getRootElement();
		if(processParser.support(root)){
			ProcessDefinition pd=(ProcessDefinition)processParser.parse(root,processId,parseChildren);
			return pd;
		}
		return null;
	}finally{
		IOUtils.closeQuietly(bin);
	}
}
 
Example 6
Project: otter-G   File: Exec.java   View Source Code Vote up 5 votes
public void run() {
    try {
        IOUtils.copy(input, output);
    } catch (IOException e) {
        logger.error("", e);
    } finally {
        IOUtils.closeQuietly(output);
    }
}
 
Example 7
Project: hadoop   File: DFSInputStream.java   View Source Code Vote up 5 votes
@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 8
Project: syndesis   File: SqlIconFileStore.java   View Source Code Vote up 5 votes
/**
 * Derby does not allow to read from the blob after the connection has been closed.
 * It also requires an outcome of commit/rollback.
 */
@SuppressWarnings("PMD.EmptyCatchBlock")
private InputStream doReadDerby(String id) {
    Handle h = dbi.open();
    try {
        h.getConnection().setAutoCommit(false);

        List<Map<String, Object>> res = h.select("SELECT data FROM icon_filestore WHERE id=?", id);

        Optional<Blob> blob = res.stream()
            .map(row -> row.get("data"))
            .map(Blob.class::cast)
            .findFirst();

        if (blob.isPresent()) {
            return new HandleCloserInputStream(h, blob.get().getBinaryStream());
        } else {
            h.commit();
            h.close();
            return null;
        }

    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception e) {
        // Do cleanup
        try {
            h.rollback();
        } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception ex) {
            // ignore
        }
        IOUtils.closeQuietly(h);

        throw IconDataAccessException.launderThrowable(e);
    }
}
 
Example 9
Project: CustomWorldGen   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
public void closeResourcePack()
{
    if (this.reResourcePack instanceof Closeable)
    {
        IOUtils.closeQuietly((Closeable)this.reResourcePack);
    }
}
 
Example 10
Project: BaseClient   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
public void closeResourcePack()
{
    if (this.reResourcePack instanceof Closeable)
    {
        IOUtils.closeQuietly((Closeable)this.reResourcePack);
    }
}
 
Example 11
Project: waggle-dance   File: StaticDatabaseMappingService.java   View Source Code Vote up 5 votes
private void remove(AbstractMetaStore metaStore) {
  if (metaStore.getFederationType() == PRIMARY) {
    primaryDatabaseMapping = null;
    primaryDatabasesCache.invalidateAll();
  } else {
    for (String databaseName : ((FederatedMetaStore) metaStore).getMappedDatabases()) {
      mappingsByDatabaseName.remove(databaseName.toLowerCase());
    }
  }
  DatabaseMapping removed = mappingsByMetaStoreName.remove(metaStore.getName());
  IOUtils.closeQuietly(removed);
}
 
Example 12
Project: cyberduck   File: PlistWriter.java   View Source Code Vote up 5 votes
@Override
public void write(final S item, final Local file) throws AccessDeniedException {
    final String content = item.<NSDictionary>serialize(SerializerFactory.get()).toXMLPropertyList();
    final OutputStream out = file.getOutputStream(false);
    try {
        IOUtils.write(content, out, Charset.forName("UTF-8"));
    }
    catch(IOException e) {
        throw new AccessDeniedException(String.format("Cannot create file %s", file.getAbsolute()), e);
    }
    finally {
        IOUtils.closeQuietly(out);
    }
}
 
Example 13
Project: vscrawler   File: JedisQueueStore.java   View Source Code Vote up 5 votes
private void unLockQueue(String queueID) {
    if (locked.get() == null) {
        return;
    }
    if (locked.get().decrementAndGet() > 0) {
        return;
    }
    Jedis jedis = jedisPool.getResource();
    try {
        jedis.del(makeRedisLockKey(queueID));
        locked.remove();
    } finally {
        IOUtils.closeQuietly(jedis);
    }
}
 
Example 14
Project: atlas   File: ClazzBasicHandler.java   View Source Code Vote up 5 votes
protected void copyStreamToJar(InputStream zin, ZipOutputStream out, String currentName, long fileTime) throws IOException {
    // Create new entry for zip file.

    ZipEntry newEntry = new ZipEntry(currentName);
    // Make sure there is date and time set.
    if (fileTime != -1) {
        newEntry.setTime(fileTime); // If found set it into output file.
    }
    out.putNextEntry(newEntry);
    if (zin != null) {
        IOUtils.copy(zin, out);
    }
    IOUtils.closeQuietly(zin);

}
 
Example 15
Project: docx4j-template   File: WordprocessingMLPackageExtractor.java   View Source Code Vote up 5 votes
public String extract(WordprocessingMLPackage wmlPackage) throws Exception {
	StringBuilderWriter output = new StringBuilderWriter(); 
	try {
		this.extract(wmlPackage, output);
	} finally {
		IOUtils.closeQuietly(output);
	}
	return output.toString();
}
 
Example 16
Project: vscrawler   File: JedisQueueStore.java   View Source Code Vote up 5 votes
@Override
public long size(String queueID) {
    Jedis jedis = jedisPool.getResource();
    try {
        return jedis.hlen(makeDataKey(queueID));
    } finally {
        IOUtils.closeQuietly(jedis);
    }
}
 
Example 17
Project: ontonethub   File: PrefixccProvider.java   View Source Code Vote up 5 votes
protected final void loadMappings() {
    try {
        log.info("Load Namespace Prefix Mappings form {}",GET_ALL);
        HttpURLConnection con = (HttpURLConnection)GET_ALL.openConnection();
        con.setReadTimeout(5000); //set the max connect & read timeout to 5sec
        con.setConnectTimeout(5000);
        con.connect();
        String contentType = con.getContentType().split(";")[0];
        if("text/plain".equalsIgnoreCase(contentType)){
            InputStream in = con.getInputStream();
            try {
                cache = new NamespacePrefixProviderImpl(in);
                cacheStamp = System.currentTimeMillis();
                log.info("  ... completed");
            } finally {
                IOUtils.closeQuietly(in);
            }
        } else {
            log.warn("Response from prefix.cc does have the wrong content type '"
                + contentType + "' (expected: text/plain). This indicates that the "
                + "service is currently unavailable!");
        }
        con.disconnect(); //we connect once every {long-period}
    } catch (IOException e) {
        log.warn("Unable to load prefix.cc NamespaceMappings (Message: "
            + e.getMessage() +")",e);
        ;
    }
}
 
Example 18
Project: ditb   File: MDScanner.java   View Source Code Vote up 4 votes
@Override public void close() {
  IOUtils.closeQuietly(admin);
  admin = null;
}
 
Example 19
Project: Wurst-MC-1.12   File: FrameHook.java   View Source Code Vote up 4 votes
public static void createFrame(DefaultResourcePack mcDefaultResourcePack,
	Logger logger) throws LWJGLException
{
	// check if frame should be created
	if(!isAutoMaximize() && !WurstBot.isEnabled())
		return;
	
	// create frame
	frame = new JFrame("Minecraft " + WMinecraft.DISPLAY_VERSION);
	
	// add LWJGL
	Canvas canvas = new Canvas();
	canvas.setBackground(new Color(16, 16, 16));
	Display.setParent(canvas);
	Minecraft mc = Minecraft.getMinecraft();
	canvas.setSize(mc.displayWidth, mc.displayHeight);
	frame.add(canvas);
	
	// configure frame
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.pack();
	frame.setLocationRelativeTo(null);
	
	// add icons
	InputStream icon16 = null;
	InputStream icon32 = null;
	try
	{
		icon16 = mcDefaultResourcePack.getInputStreamAssets(
			new ResourceLocation("icons/icon_16x16.png"));
		icon32 = mcDefaultResourcePack.getInputStreamAssets(
			new ResourceLocation("icons/icon_32x32.png"));
		ArrayList<BufferedImage> icons = new ArrayList<>();
		icons.add(ImageIO.read(icon16));
		icons.add(ImageIO.read(icon32));
		frame.setIconImages(icons);
	}catch(Exception e)
	{
		logger.error("Couldn't set icon", e);
	}finally
	{
		IOUtils.closeQuietly(icon16);
		IOUtils.closeQuietly(icon32);
	}
	
	// show frame
	if(!WurstBot.isEnabled())
		frame.setVisible(true);
}
 
Example 20
Project: ECFileCache   File: ECFileCacheTest.java   View Source Code Vote up 4 votes
private void testPutGetDeleteImpl() throws IOException, ECFileCacheException {

    Random random = new Random();
    int size = 4 * 64 * 1024;
    byte[] buffer = new byte[size];
    random.nextBytes(buffer);

    // create file cache key
    String fileCacheKey = client.createFileCacheKey(size);

    // put file
    int chunkPos = 0;
    int endPos = 64 * 1024;
    putChunk(fileCacheKey, buffer, chunkPos, endPos);

    chunkPos = endPos;
    endPos += 2 * 64 * 1024;
    putChunk(fileCacheKey, buffer, chunkPos, endPos);

    chunkPos = endPos;
    endPos += 64 * 1024;
    putChunk(fileCacheKey, buffer, chunkPos, endPos);

    // get file
    byte[] cachedFile = client.getFile(fileCacheKey);

    Assert.assertArrayEquals(buffer, cachedFile);

    // get file stream
    InputStream inputStream = client.asInputStream(fileCacheKey);
    cachedFile = IOUtils.toByteArray(inputStream);
    IOUtils.closeQuietly(inputStream);

    Assert.assertArrayEquals(buffer, cachedFile);

    // delete file
    client.deleteFile(fileCacheKey);
    try {
      client.getFile(fileCacheKey);
      Assert.fail("should not reach here");
    } catch (ECFileCacheException e) {
      Assert.assertTrue(StringUtils.contains(e.getMessage(), "fail count > CODING_BLOCK_NUM."));
    }
  }