/** * Reads file into byte array, detects charset and converts from this charset to UTF8 * * @param file file to decode and convert to UTF8 * @return * @throws IOException * @throws CharacterCodingException */ public static synchronized byte[] convertFileToUTF8ByteArray(File file) throws IOException, CharacterCodingException { FileInputStream in = null; DataInputStream inStream = null; try { in = new FileInputStream(file); inStream = new DataInputStream(in); byte[] buf = new byte[(int) file.length()]; int nrRead = inStream.read(buf); UniversalDetector detector = new UniversalDetector(null); detector.handleData(buf, 0, nrRead); detector.dataEnd(); String encoding = detector.getDetectedCharset(); detector.reset(); if (encoding != null) { if (!encoding.equals(Jeeves.ENCODING)) { Log.error(Log.JEEVES, "Detected character set " + encoding + ", converting to UTF-8"); return convertByteArrayToUTF8ByteArray(buf, encoding); } } return buf; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (inStream != null) { IOUtils.closeQuietly(inStream); } } }
public String copyLibraryToTempFile(String library) throws IOException { InputStream in = null; OutputStream out = null; try { String libraryName = getContextAwareLibraryName(library); in = getClass().getClassLoader().getResourceAsStream("lib/" + libraryName); if (in == null) { fail("runtime not supported, '%s' missing in native bundle", libraryName); } File file = createTempFile(library); out = new FileOutputStream(file); int cnt; byte buf[] = new byte[16 * 1024]; while ((cnt = in.read(buf)) >= 1) { out.write(buf, 0, cnt); } return file.getAbsolutePath(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
@Override public List<AttributeMappingData> loadMappingsFromSource(InputStream inputStream) throws ParserDataException { List<AttributeMappingData> attributesMapping = new ArrayList<AttributeMappingData>(); BufferedReader br = null; try { Set<String> siteIds = siteService.getAllIds(); Set<String> categoryIds = categoryService.getAllIds(); br = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = br.readLine()) != null) { if (line == null || line.trim().isEmpty() || line.startsWith("#")) { continue; } AttributeMappingData att = parseObject(line); if (!siteIds.contains(att.getSiteKey())) { throw new ParserDataException("Site Key: " + att.getSiteKey() + " not found"); } if (!categoryIds.contains(att.getCategoryKey())) { throw new ParserDataException("Category Key: " + att.getCategoryKey() + " not found"); } attributesMapping.add(att); } } catch (IOException ex) { logger.error("Error loading Sites. Error: {}", ex); throw new ParserDataException(ex.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(inputStream); } return attributesMapping; }
private JarFile loadModuleJarFile(String moduleId, String version) throws IOException { InputStream moduleStream = null; File tempFile = null; OutputStream tempFileStream = null; JarFile jarFile = null; try { moduleStream = getClass() .getClassLoader() .getResourceAsStream( "org/openmrs/module/include/" + moduleId + "-" + version + ".omod"); Assert.assertNotNull(moduleStream); tempFile = File.createTempFile("moduleTest", "omod"); tempFileStream = new FileOutputStream(tempFile); IOUtils.copy(moduleStream, tempFileStream); jarFile = new JarFile(tempFile); } finally { IOUtils.closeQuietly(moduleStream); IOUtils.closeQuietly(tempFileStream); if (tempFile != null) { tempFile.delete(); } } return jarFile; }
/** * Gobbles up all the stuff coming from the InputStream and sends it to the OutputStream specified * during object construction. */ public void run() { InputStreamReader isr = null; BufferedReader br = null; try { // Set up the input stream isr = new InputStreamReader(in); br = new BufferedReader(isr); // Initialize the temporary results containers String line = null; // Main processing loop which captures the output while ((line = br.readLine()) != null) { if (quit) { break; } else { pwOut.println(line); } } } catch (final Throwable e) { LogUtils.debugf(this, e, "Unable to read lines."); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); } }
private void doSaveImage(final String diagramFileString, BpmnMemoryModel model) { boolean saveImage = PreferencesUtil.getBooleanPreference(Preferences.SAVE_IMAGE, ActivitiPlugin.getDefault()); if (saveImage) { List<String> languages = PreferencesUtil.getStringArray( Preferences.ACTIVITI_LANGUAGES, ActivitiPlugin.getDefault()); if (languages != null && languages.size() > 0) { for (String language : languages) { for (Process process : model.getBpmnModel().getProcesses()) { fillContainerWithLanguage(process, language); } ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator(); InputStream imageStream = processDiagramGenerator.generatePngDiagram(model.getBpmnModel()); if (imageStream != null) { String imageFileName = null; if (diagramFileString.endsWith(".bpmn20.xml")) { imageFileName = diagramFileString.substring(0, diagramFileString.length() - 11) + "_" + language + ".png"; } else { imageFileName = diagramFileString.substring(0, diagramFileString.lastIndexOf(".")) + "_" + language + ".png"; } File imageFile = new File(imageFileName); FileOutputStream outStream = null; ByteArrayOutputStream baos = null; try { outStream = new FileOutputStream(imageFile); baos = new ByteArrayOutputStream(); IOUtils.copy(imageStream, baos); baos.writeTo(outStream); } catch (Exception e) { e.printStackTrace(); } finally { if (outStream != null) { IOUtils.closeQuietly(outStream); } if (baos != null) { IOUtils.closeQuietly(baos); } } } } } else { marshallImage(model, diagramFileString); } } }
public <P extends AbstractProject<P, B>, B extends AbstractBuild<P, B>> String getContent( AbstractBuild<P, B> build, ExtendedEmailPublisher publisher, EmailType type, Map<String, ?> args) throws IOException, InterruptedException { InputStream inputStream = null; InputStream templateStream = null; String scriptName = Args.get(args, SCRIPT_NAME_ARG, DEFAULT_SCRIPT_NAME); String templateName = Args.get(args, SCRIPT_TEMPLATE_ARG, DEFAULT_TEMPLATE_NAME); boolean runInit = Args.get(args, SCRIPT_INIT_ARG, DEFAULT_INIT_VALUE); try { inputStream = getFileInputStream(scriptName); // sanity check on template as well templateStream = getFileInputStream(templateName); IOUtils.closeQuietly(templateStream); return renderContent(build, inputStream, scriptName, templateName, runInit); } catch (FileNotFoundException e) { String missingScriptError = generateMissingFile(scriptName, templateName); LOGGER.log(Level.SEVERE, missingScriptError); return missingScriptError; } catch (ScriptException e) { LOGGER.log(Level.SEVERE, null, e); return "Exception: " + e.getMessage(); } finally { IOUtils.closeQuietly(inputStream); } }
protected Void doInBackground() throws Exception { for (int n = 0; n < binaryAndFileList.size(); n++) { Map.Entry<Binary, File> binaryAndFile = binaryAndFileList.get(n); Binary binary = binaryAndFile.getKey(); File file = binaryAndFile.getValue(); setProgress(n + 1, 0, binaryAndFileList.size()); if (binaryAndFileList.size() == 1) { message(getFullResourceKey("progress.singular"), binary.getFileName()); } else { message( getFullResourceKey("progress.plural"), binary.getFileName(), n + 1, binaryAndFileList.size()); } InputStream in = null; OutputStream out = null; try { IOUtils.copy(in = binary.getDataStream(), out = new FileOutputStream(file)); wroteBinaryToFile(binaryAndFile); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return null; }
/** Register Process Definition */ public static void registerProcessDefinition(InputStream is) throws WorkflowException, ParseException, IOException { log.debug("registerProcessDefinition({})", is); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); InputStream isForms = null; ZipInputStream zis = null; if (Config.SYSTEM_READONLY) { throw new WorkflowException("System is in read-only mode"); } try { zis = new ZipInputStream(is); org.jbpm.graph.def.ProcessDefinition processDefinition = org.jbpm.graph.def.ProcessDefinition.parseParZipInputStream(zis); // Check xml form definition FileDefinition fileDef = processDefinition.getFileDefinition(); isForms = fileDef.getInputStream("forms.xml"); FormUtils.parseWorkflowForms(isForms); // If it is ok, deploy it jbpmContext.deployProcessDefinition(processDefinition); } catch (JbpmException e) { throw new WorkflowException(e.getMessage(), e); } finally { IOUtils.closeQuietly(isForms); IOUtils.closeQuietly(zis); jbpmContext.close(); } log.debug("registerProcessDefinition: void"); }
/** * 基类基于子类提供的相关参数数据, 生成JXLS报表 * * @see #exportXlsForGrid(List, Sort, GroupPropertyFilter) 此方法中基于参数组装好相关的data数据后,调用此方法生成Excel响应 * @param dataMap */ protected void exportExcel( String templateFileName, String exportFileName, Map<String, Object> dataMap) { // 日期格式定义 dataMap.put("dateFormatter", new SimpleDateFormat(DateUtils.DEFAULT_DATE_FORMAT)); dataMap.put("timeFormatter", new SimpleDateFormat(DateUtils.DEFAULT_TIME_FORMAT)); HttpServletResponse response = ServletActionContext.getResponse(); InputStream fis = null; OutputStream fos = null; try { Resource resource = new ClassPathResource("/template/xls/" + templateFileName); logger.debug("Open template file inputstream: {}", resource.getURL()); fis = resource.getInputStream(); XLSTransformer transformer = new XLSTransformer(); // generate the excel workbook according to the template and // parameters Workbook workbook = transformer.transformXLS(fis, dataMap); String filename = exportFileName; filename = new String(filename.getBytes("GBK"), "ISO-8859-1"); response.setHeader("Content-Disposition", "attachment;filename=" + filename); response.setContentType("application/vnd.ms-excel;charset=utf-8"); fos = response.getOutputStream(); // output the generated excel file workbook.write(fos); } catch (Exception e) { throw new WebException(e.getMessage(), e); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fos); } }
protected void loadProperties(Properties props) throws IOException { if (this.locations != null) for (int i = 0; i < this.locations.length; ++i) { Resource location = this.locations[i]; InputStream is = null; InputStream keyStream = null; InputStream readIs = null; try { is = location.getInputStream(); keyStream = this.keyLocation.getInputStream(); readIs = DesUtil.decrypt(is, DesUtil.getKey(keyStream)); if (location.getFilename().endsWith(".xml")) { this.propertiesPersister.loadFromXml(props, readIs); } else if (this.fileEncoding != null) this.propertiesPersister.load(props, new InputStreamReader(readIs, this.fileEncoding)); else this.propertiesPersister.load(props, readIs); } catch (Exception ex) { if ((this.ignoreResourceNotFound) && (this.logger.isWarnEnabled())) this.logger.warn("Could not load properties from " + location + ": " + ex.getMessage()); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(keyStream); IOUtils.closeQuietly(readIs); } } }
/** * Given confusion matrix, it writes it in CSV and LaTeX form to the tasks output directory, and * also prints evaluations (F-measure, Precision, Recall) * * @param context task context * @param confusionMatrix confusion matrix * @param filePrefix prefix of output files * @throws java.io.IOException */ public static void writeOutputResults( TaskContext context, ConfusionMatrix confusionMatrix, String filePrefix) throws IOException { // storing the results as latex confusion matrix String confMatrixFileTex = (filePrefix != null ? filePrefix : "") + "confusionMatrix.tex"; File matrixFolderTex = context.getFolder(Constants.TEST_TASK_OUTPUT_KEY, StorageService.AccessMode.READWRITE); File evaluationFileLaTeX = new File(matrixFolderTex, confMatrixFileTex); FileUtils.writeStringToFile(evaluationFileLaTeX, confusionMatrix.toStringLatex()); // as CSV confusion matrix String confMatrixFileCsv = (filePrefix != null ? filePrefix : "") + "confusionMatrix.csv"; File matrixFolder = context.getFolder(Constants.TEST_TASK_OUTPUT_KEY, StorageService.AccessMode.READWRITE); File evaluationFileCSV = new File(matrixFolder, confMatrixFileCsv); CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(evaluationFileCSV), CSVFormat.DEFAULT); csvPrinter.printRecords(confusionMatrix.toStringMatrix()); IOUtils.closeQuietly(csvPrinter); // and results File evalFolder = context.getFolder(Constants.TEST_TASK_OUTPUT_KEY, StorageService.AccessMode.READWRITE); String evalFileName = new SVMHMMAdapter() .getFrameworkFilename(TCMachineLearningAdapter.AdapterNameEntries.evaluationFile); File evaluationFile = new File(evalFolder, evalFileName); PrintWriter pw = new PrintWriter(evaluationFile); pw.println(confusionMatrix.printNiceResults()); pw.println(confusionMatrix.printLabelPrecRecFm()); pw.println(confusionMatrix.printClassDistributionGold()); IOUtils.closeQuietly(pw); }
/** * Creates a new file in the same directory as {@code featureVectorsFile} and replaces the first * token (outcome label) by its corresponding integer number from the bi-di map * * @param featureVectorsFile file * @param labelsToIntegers mapping * @return new file */ public static File replaceLabelsWithIntegers(File featureVectorsFile, BidiMap labelsToIntegers) throws IOException { File result = new File( featureVectorsFile.getParent(), "mappedLabelsToInt_" + featureVectorsFile.getName()); PrintWriter pw = new PrintWriter(new FileOutputStream(result)); BufferedReader br = new BufferedReader(new FileReader(featureVectorsFile)); String line = null; while ((line = br.readLine()) != null) { // split on the first whitespaces, keep the rest String[] split = line.split("\\s", 2); String label = split[0]; String remainingContent = split[1]; // find the integer Integer intOutput = (Integer) labelsToIntegers.get(label); // print to the output stream pw.printf("%d %s%n", intOutput, remainingContent); } IOUtils.closeQuietly(pw); IOUtils.closeQuietly(br); return result; }
@Override public void sendStream(InputStream is) throws IOException { OutputStream os = getOutputStream(); if (state == State.UNSET) { state = State.SUCCESS; } try { long bytesCopied = IOUtils.copyLarge(is, os); if (bytesCopied == 0) { log.warn("Zero bytes sent to client."); } else { long expectedLength = getContentLength(); if (expectedLength > 0 && bytesCopied != expectedLength) { log.warn( "Actual bytes sent to client ({}) are different than expected ({}).", bytesCopied, expectedLength); } else { log.debug("{} bytes sent to client.", bytesCopied); } } sendSuccess(); } catch (Exception e) { exception = e; sendInternalError(e, log); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
@Override public void close() { IOUtils.closeQuietly(socketChannelOutput); IOUtils.closeQuietly(channel); socketChannelOutput = null; channel = null; }
@Override public void exportSchema(String user, String password, String schema, File dumpFile) throws MojoExecutionException { BufferedInputStream in = null; FileOutputStream out = null; try { ProcessBuilder pb = new ProcessBuilder("mysqldump", schema, "-u", user, "--password="******"mysqldump", e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
private File getCachedImage(File file, int size) throws IOException { String md5 = DigestUtils.md5Hex(file.getPath()); File cachedImage = new File(getImageCacheDirectory(size), md5 + ".jpeg"); // Is cache missing or obsolete? if (!cachedImage.exists() || FileUtil.lastModified(file) > cachedImage.lastModified()) { InputStream in = null; OutputStream out = null; try { in = getImageInputStream(file); out = new FileOutputStream(cachedImage); BufferedImage image = ImageIO.read(in); if (image == null) { throw new Exception("Unable to decode image."); } image = scale(image, size, size); ImageIO.write(image, "jpeg", out); } catch (Throwable x) { // Delete corrupt (probably empty) thumbnail cache. LOG.warn("Failed to create thumbnail for " + file, x); IOUtils.closeQuietly(out); cachedImage.delete(); throw new IOException("Failed to create thumbnail for " + file + ". " + x.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } return cachedImage; }
/** * Servicio de obtencion de lenguajes. * * @param type tipo de documento que se desea consultar * @return String */ @RequestMapping(value = "/language/{lang}", method = RequestMethod.GET) public Object getIdiomas(@PathVariable("lang") String lang) { InputStream inputStream = null; OutputStream outputStream = null; try { System.out.println(); return "{\"testi\":\"{\"testiSe\":\"sec\"}\"}"; } catch (SessionTimeOutException e) { log.error(StackTraceUtil.getStackTrace(e)); throw new SessionTimeOutException("la Sesión ha expirado."); } catch (InvalidInputDataException e) { log.error(StackTraceUtil.getStackTrace(e)); throw new InvalidInputDataException(e.getMessage()); } catch (UnauthorizedException e) { log.error(StackTraceUtil.getStackTrace(e)); throw new UnauthorizedException(e.getMessage()); } catch (Exception e) { log.error(StackTraceUtil.getStackTrace(e)); throw new InternalServerErrorExcepcion("Se genero un error interno."); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
private static String readProcessOutput(String command, String arguments) { String result = ""; ProcessBuilder pb = new ProcessBuilder(command, arguments); pb.redirectErrorStream(true); try { Process process = pb.start(); InputStream stdout = process.getInputStream(); final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout)); String line = null; try { StringBuilder stringBuilder = new StringBuilder(); while ((line = brstdout.readLine()) != null) { stringBuilder.append(line); } result = stringBuilder.toString(); } catch (Exception e) { } finally { IOUtils.closeQuietly(brstdout); IOUtils.closeQuietly(stdout); } } catch (Throwable e) { e.printStackTrace(); } return result; }
@Test public void testUpdateWithTagWithSchemeAndLabel() throws Exception { DiagnosticReport dr = new DiagnosticReport(); dr.setId("001"); dr.addCodedDiagnosis().addCoding().setCode("AAA"); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001"); httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\""); httpPost.setEntity( new StringEntity( ourCtx.newXmlParser().encodeResourceToString(dr), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); assertEquals(1, ourReportProvider.getLastTags().size()); assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0)); IOUtils.closeQuietly(status.getEntity().getContent()); httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001"); httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"; "); httpPost.setEntity( new StringEntity( ourCtx.newXmlParser().encodeResourceToString(dr), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); status = ourClient.execute(httpPost); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(1, ourReportProvider.getLastTags().size()); assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0)); }
public static boolean CopyResourceToStorage(int resourceId, String path, boolean force) { File file = new File(path); // 파일이 존재하면 true return if (file.exists() && !force) { return true; } InputStream inputStream = null; OutputStream outputStream = null; try { // Stream 복사 inputStream = context.getResources().openRawResource(resourceId); outputStream = context.openFileOutput(path, Context.MODE_PRIVATE); IOUtils.copy(inputStream, outputStream); } catch (Exception e) { path = e.getMessage(); return false; } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } return true; }
private static void extractSkin(String fileName) { InputStream input = null; FileOutputStream output = null; File outputFile = new File(SkinIOUtils.getSkinLibraryDirectory(), fileName + ".armour"); if (outputFile.exists()) { if (getFileSize(outputFile) > 0) { return; } else { ModLogger.log("Deleting corrupted skin file " + fileName); outputFile.delete(); } } try { ModLogger.log("Extracting file " + fileName); input = SkinExtractor.class .getClassLoader() .getResourceAsStream(SKINS_ASSETS_LOCATION + fileName + ".armour"); if (input != null) { output = new FileOutputStream(outputFile); while (input.available() > 0) { output.write(input.read()); } output.flush(); } else { ModLogger.log(Level.ERROR, "Error extracting skin " + fileName); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException( "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
/** * Gets the stack trace of the Throwable that caused this crash report, or if that fails, the * cause .toString(). */ public String getCauseStackTraceOrString() { StringWriter stringwriter = null; PrintWriter printwriter = null; Throwable throwable = this.cause; if (throwable.getMessage() == null) { if (throwable instanceof NullPointerException) { throwable = new NullPointerException(this.description); } else if (throwable instanceof StackOverflowError) { throwable = new StackOverflowError(this.description); } else if (throwable instanceof OutOfMemoryError) { throwable = new OutOfMemoryError(this.description); } throwable.setStackTrace(this.cause.getStackTrace()); } String s = throwable.toString(); try { stringwriter = new StringWriter(); printwriter = new PrintWriter(stringwriter); throwable.printStackTrace(printwriter); s = stringwriter.toString(); } finally { IOUtils.closeQuietly((Writer) stringwriter); IOUtils.closeQuietly((Writer) printwriter); } return s; }
@Override public void replicate(ConfigManager manager, ConfigRequest request) throws IOException { if (!request.applies(CertificateManager.FEATURE)) { return; } boolean chainCertificate = false; boolean caCertificate = false; File dir = manager.getGlobalDataDirectory(); String sipCert = m_certificateManager.getCommunicationsCertificate(); FileUtils.writeStringToFile(new File(dir, "ssl.crt"), sipCert); String sipKey = m_certificateManager.getCommunicationsPrivateKey(); FileUtils.writeStringToFile(new File(dir, "ssl.key"), sipKey); String webCert = m_certificateManager.getWebCertificate(); FileUtils.writeStringToFile(new File(dir, "ssl-web.crt"), webCert); String webKey = m_certificateManager.getWebPrivateKey(); FileUtils.writeStringToFile(new File(dir, "ssl-web.key"), webKey); String chainCert = m_certificateManager.getChainCertificate(); if (chainCert != null) { FileUtils.writeStringToFile(new File(dir, "server-chain.crt"), chainCert); chainCertificate = true; } String caCert = m_certificateManager.getCACertificate(); if (caCert != null) { FileUtils.writeStringToFile(new File(dir, "ca-bundle.crt"), caCert); caCertificate = true; } Writer writer = new FileWriter(new File(dir, "ssl.conf")); try { write(writer, chainCertificate, caCertificate); } finally { IOUtils.closeQuietly(writer); } String domain = Domain.getDomain().getName(); JavaKeyStore sslSip = new JavaKeyStore(); sslSip.addKey(domain, sipCert, sipKey); sslSip.storeIfDifferent(new File(dir, "ssl.keystore")); JavaKeyStore sslWeb = new JavaKeyStore(); sslWeb.addKey(domain, webCert, webKey); sslWeb.storeIfDifferent(new File(dir, "ssl-web.keystore")); File authDir = new File(dir, "authorities"); authDir.mkdir(); JavaKeyStore store = new JavaKeyStore(); for (String authority : m_certificateManager.getAuthorities()) { String authCert = m_certificateManager.getAuthorityCertificate(authority); FileUtils.writeStringToFile(new File(authDir, authority + ".crt"), authCert); store.addAuthority(authority, authCert); } OutputStream authoritiesStore = null; try { store.storeIfDifferent(new File(dir, "authorities.jks")); } finally { IOUtils.closeQuietly(authoritiesStore); } }
/** 申請ファイルアップロード準備 */ private String prepareUploadDate(Shinsei shinsei, File toDir) { File receivedFile = null; byte[] receivedData = shinsei.getShinseiData(); String outDirPath = toDir.getAbsolutePath(); InputStream in = null; OutputStream out = null; try { receivedFile = File.createTempFile("dataset", ".zip"); in = new ByteArrayInputStream(receivedData); out = new FileOutputStream(receivedFile); IOUtils.copy(in, out); if (receivedFile.length() > MAX_ZIP_FILE_SIZE) { log.debug("ZIPファイルサイズの制限超過しています。[" + receivedFile.length() + "]"); return "TOO_LARGE_FILE"; } new ZipFile(receivedFile.getAbsolutePath(), "UTF-8").extract(outDirPath); log.debug("申請データの展開先:" + outDirPath); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); if (!receivedFile.delete()) { log.info("申請ファイルが削除できませんでした。:" + receivedFile.getAbsolutePath()); } } return "SUCCESS"; }
public static MD5InputStreamResult generateMD5Result(InputStream toEncode) { MD5Digest eTag = new MD5Digest(); byte[] resBuf = new byte[eTag.getDigestSize()]; byte[] buffer = new byte[1024]; ByteArrayOutputStream out = new ByteArrayOutputStream(); long length = 0; int numRead = -1; try { do { numRead = toEncode.read(buffer); if (numRead > 0) { length += numRead; eTag.update(buffer, 0, numRead); out.write(buffer, 0, numRead); } } while (numRead != -1); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(toEncode); } eTag.doFinal(resBuf, 0); return new MD5InputStreamResult(out.toByteArray(), resBuf, length); }
/** * 文件解压 * * @param file 压缩文件 * @param destDir 解压目录 */ public static void decompress(File file, File destDir, String encoding) { if (!file.exists()) { return; } InputStream is = null; ZipArchiveInputStream zis = null; try { is = new FileInputStream(file); zis = new ZipArchiveInputStream(new FileInputStream(file), encoding); ArchiveEntry archiveEntry = null; while ((archiveEntry = zis.getNextEntry()) != null) { CompressUtilsHelper.decompress(zis, archiveEntry, destDir); } } catch (Exception e) { throw new CommonsException( "Decompress " + file.getPath() + " to " + destDir.getPath() + " failed!", e); } finally { IOUtils.closeQuietly(zis); IOUtils.closeQuietly(is); } }
/** * Copy a file into another. The directory structure of target file will be created if needed. * * @param source the source file * @param destination the target file * @return true if the copy happened without error, false otherwise */ public static boolean copy(final File source, final File destination) { FileUtils.mkdirs(destination.getParentFile()); InputStream input = null; OutputStream output = null; boolean copyDone = false; try { input = new BufferedInputStream(new FileInputStream(source)); output = new BufferedOutputStream(new FileOutputStream(destination)); copyDone = copy(input, output); // close here already to catch any issue with closing input.close(); output.close(); } catch (final FileNotFoundException e) { Log.e("LocalStorage.copy: could not copy file", e); return false; } catch (final IOException e) { Log.e("LocalStorage.copy: could not copy file", e); return false; } finally { // close here quietly to clean up in all situations IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return copyDone; }
protected String getResourceText(final Resource r) { if (r instanceof ByteArrayResource) { return new String(((ByteArrayResource) r).getByteArray()); } else { InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { is = r.getInputStream(); if (is != null) { final StringBuilder sb = new StringBuilder(); String line = null; isr = new InputStreamReader(is, Charset.defaultCharset()); br = new BufferedReader(isr); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } sb.deleteCharAt(sb.length()); return sb.toString(); } } catch (final IOException e) { LOG.warn("Unable to get inputstream for resource '{}'", r, e); return null; } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } } return null; }