List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:com.clt.sub.controller.DriverAction.java
/** * ?//from w w w . j a v a 2s .c o m * * @param request * @param files * @throws FileNotFoundException * @throws IOException */ private void uploadTruckImg(HttpServletRequest request, CommonsMultipartFile[] files, TDriver driver) throws FileNotFoundException, IOException { if (files == null) { return; } for (int i = 0; i < files.length; i++) { System.out.println("fileName---------->" + files[i].getOriginalFilename()); if (!files[i].isEmpty()) { int pre = (int) System.currentTimeMillis(); // String source = request.getSession().getServletContext() // .getRealPath( "/" ); String source = pictureService.getPathById(22);// ? if (!source.endsWith("/")) { source += "/"; } if (StringUtils.isBlank(source)) { System.out.println("source??"); return; } String path = source; File pathFile = new File(path); if (!pathFile.exists()) { pathFile.mkdirs(); } String jpgPath = new Date().getTime() + files[i].getOriginalFilename(); // path += new Date().getTime() + // files[i].getOriginalFilename(); path += jpgPath; // ????? FileOutputStream os = new FileOutputStream(path); // ? ByteArrayInputStream in = (ByteArrayInputStream) files[i].getInputStream(); // ? int b = 0; while ((b = in.read()) != -1) { os.write(b); } os.flush(); os.close(); in.close(); int finaltime = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); String imgPath = driver.getVcTruckImgPath(); if (StringUtils.isBlank(imgPath)) { driver.setVcTruckImgPath(jpgPath); } else { // share.setVcImgpath( imgPath + "," + path ); imgPath = imgPath.substring(imgPath.lastIndexOf("/") + 1);// ? String existImgPath = source + imgPath; File imgFile = new File(existImgPath); if (imgFile.exists()) { boolean isDel = imgFile.delete(); if (isDel) { System.out.println("'" + imgPath + "'"); } } driver.setVcTruckImgPath(jpgPath); } } } }
From source file:com.clt.sub.controller.DriverAction.java
/** * ??/* w w w .j av a 2s. c om*/ * * @param request * @param files * @throws FileNotFoundException * @throws IOException */ private void uploadImg(HttpServletRequest request, CommonsMultipartFile[] files, TDriver driver) throws FileNotFoundException, IOException { if (files == null) { return; } for (int i = 0; i < files.length; i++) { System.out.println("fileName---------->" + files[i].getOriginalFilename()); if (!files[i].isEmpty()) { int pre = (int) System.currentTimeMillis(); // String source = request.getSession().getServletContext() // .getRealPath( "/" ); String source = pictureService.getPathById(22);// ? if (!source.endsWith("/")) { source += "/"; } if (StringUtils.isBlank(source)) { System.out.println("source??"); return; } String path = source; File pathFile = new File(path); if (!pathFile.exists()) { pathFile.mkdirs(); } String jpgPath = new Date().getTime() + files[i].getOriginalFilename(); // path += new Date().getTime() + // files[i].getOriginalFilename(); path += jpgPath; // ????? FileOutputStream os = new FileOutputStream(path); // ? ByteArrayInputStream in = (ByteArrayInputStream) files[i].getInputStream(); // ? int b = 0; while ((b = in.read()) != -1) { os.write(b); } os.flush(); os.close(); in.close(); int finaltime = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); String imgPath = driver.getVcImgPath(); if (StringUtils.isBlank(imgPath)) { driver.setVcImgPath(jpgPath); } else { // share.setVcImgpath( imgPath + "," + path ); imgPath = imgPath.substring(imgPath.lastIndexOf("/") + 1);// ? String existImgPath = source + imgPath; File imgFile = new File(existImgPath); if (imgFile.exists()) { boolean isDel = imgFile.delete(); if (isDel) { System.out.println("'" + imgPath + "'"); } } driver.setVcImgPath(jpgPath); } } } }
From source file:com.sun.faces.renderkit.ResponseStateManagerImpl.java
public Object getTreeStructureToRestore(FacesContext context, String treeId) { StateManager stateManager = Util.getStateManager(context); Object structure = null;/*from ww w . j a va 2s. c o m*/ Object state = null; ByteArrayInputStream bis = null; GZIPInputStream gis = null; ObjectInputStream ois = null; boolean compress = isCompressStateSet(context); Map requestParamMap = context.getExternalContext().getRequestParameterMap(); String viewString = (String) requestParamMap.get(RIConstants.FACES_VIEW); if (viewString == null) { return null; } if (stateManager.isSavingStateInClient(context)) { byte[] bytes = Base64.decode(viewString.getBytes()); try { bis = new ByteArrayInputStream(bytes); if (isCompressStateSet(context)) { if (log.isDebugEnabled()) { log.debug("Deflating state before restoring.."); } gis = new GZIPInputStream(bis); ois = new ApplicationObjectInputStream(gis); } else { ois = new ApplicationObjectInputStream(bis); } structure = ois.readObject(); state = ois.readObject(); Map requestMap = context.getExternalContext().getRequestMap(); // store the state object temporarily in request scope until it is // processed by getComponentStateToRestore which resets it. requestMap.put(FACES_VIEW_STATE, state); bis.close(); if (compress) { gis.close(); } ois.close(); } catch (java.io.OptionalDataException ode) { log.error(ode.getMessage(), ode); throw new FacesException(ode); } catch (java.lang.ClassNotFoundException cnfe) { log.error(cnfe.getMessage(), cnfe); throw new FacesException(cnfe); } catch (java.io.IOException iox) { log.error(iox.getMessage(), iox); throw new FacesException(iox); } } else { structure = viewString; } return structure; }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
private byte[] zipDocument(String fileZipName, byte[] content) { logger.debug("IN"); ByteArrayOutputStream bos = null; ZipOutputStream zos = null;//from w ww.j a va2 s .c o m ByteArrayInputStream in = null; try { bos = new ByteArrayOutputStream(); zos = new ZipOutputStream(bos); ZipEntry ze = new ZipEntry(fileZipName); zos.putNextEntry(ze); in = new ByteArrayInputStream(content); for (int c = in.read(); c != -1; c = in.read()) { zos.write(c); } return bos.toByteArray(); } catch (IOException ex) { logger.error("Error zipping the document", ex); return null; } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } if (zos != null) { try { zos.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { logger.error("Error closing output stream", e); } } } }
From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java
/** * Execute the split of a pdf document when split type is S_BLEVEL * //from w ww. ja va2s .com * @param inputCommand * @throws Exception */ private void executeBookmarksSplit(SplitParsedCommand inputCommand) throws Exception { pdfReader = PdfUtility.readerFor(inputCommand.getInputFile()); int bLevel = inputCommand.getBookmarksLevel().intValue(); Hashtable bookmarksTable = new Hashtable(); if (bLevel > 0) { pdfReader.removeUnusedObjects(); pdfReader.consolidateNamedDestinations(); List bookmarks = SimpleBookmark.getBookmark(pdfReader); ByteArrayOutputStream out = new ByteArrayOutputStream(); SimpleBookmark.exportToXML(bookmarks, out, "UTF-8", false); ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray()); int maxDepth = PdfUtility.getMaxBookmarksDepth(input); input.reset(); if (bLevel <= maxDepth) { SAXReader reader = new SAXReader(); org.dom4j.Document document = reader.read(input); // head node String headBookmarkXQuery = "/Bookmark/Title[@Action=\"GoTo\"]"; Node headNode = document.selectSingleNode(headBookmarkXQuery); if (headNode != null && headNode.getText() != null && headNode.getText().trim().length() > 0) { bookmarksTable.put(new Integer(1), headNode.getText().trim()); } // bLevel nodes StringBuffer buffer = new StringBuffer("/Bookmark"); for (int i = 0; i < bLevel; i++) { buffer.append("/Title[@Action=\"GoTo\"]"); } String xQuery = buffer.toString(); List nodes = document.selectNodes(xQuery); input.close(); input = null; if (nodes != null && nodes.size() > 0) { LinkedHashSet pageSet = new LinkedHashSet(nodes.size()); for (Iterator nodeIter = nodes.iterator(); nodeIter.hasNext();) { Node currentNode = (Node) nodeIter.next(); Node pageAttribute = currentNode.selectSingleNode("@Page"); if (pageAttribute != null && pageAttribute.getText().length() > 0) { String attribute = pageAttribute.getText(); int blankIndex = attribute.indexOf(' '); if (blankIndex > 0) { Integer currentNumber = new Integer(attribute.substring(0, blankIndex)); String bookmarkText = currentNode.getText().trim(); // fix #2789963 if (currentNumber.intValue() > 0) { // bookmarks regexp matching if any if (StringUtils.isBlank(inputCommand.getBookmarkRegexp()) || bookmarkText.matches(inputCommand.getBookmarkRegexp())) { // to split just before the given page if ((currentNumber.intValue()) > 1) { pageSet.add(new Integer(currentNumber.intValue() - 1)); } if (StringUtils.isNotBlank(bookmarkText)) { bookmarksTable.put(currentNumber, bookmarkText.trim()); } } } } } } if (pageSet.size() > 0) { if (StringUtils.isBlank(inputCommand.getBookmarkRegexp())) { LOG.debug("Found " + pageSet.size() + " destination pages at level " + bLevel); } else { LOG.debug("Found " + pageSet.size() + " destination pages at level " + bLevel + " matching '" + inputCommand.getBookmarkRegexp() + "'"); } inputCommand.setSplitPageNumbers((Integer[]) pageSet.toArray(new Integer[pageSet.size()])); } else { throw new SplitException(SplitException.ERR_BLEVEL_NO_DEST, new String[] { "" + bLevel }); } } else { throw new SplitException(SplitException.ERR_BLEVEL, new String[] { "" + bLevel }); } } else { input.close(); pdfReader.close(); throw new SplitException(SplitException.ERR_BLEVEL_OUTOFBOUNDS, new String[] { "" + bLevel, "" + maxDepth }); } } else { pdfReader.close(); throw new SplitException(SplitException.ERR_NOT_VALID_BLEVEL, new String[] { "" + bLevel }); } pdfReader.close(); executeSplit(inputCommand, bookmarksTable); }
From source file:org.miloss.fgsms.presentation.Helper.java
public static ServicePolicy ImportServicePolicy(String pol, PolicyType pt) { try {// www .ja v a2 s. c om JAXBContext jc = Utility.getSerializationContext(); Unmarshaller u = jc.createUnmarshaller(); ByteArrayInputStream bss = new ByteArrayInputStream(pol.getBytes(Constants.CHARSET)); //1 = reader //2 = writer XMLInputFactory xf = XMLInputFactory.newInstance(); XMLStreamReader r = xf.createXMLStreamReader(bss); // com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl r = new com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl(bss, new com.sun.org.apache.xerces.internal.impl.PropertyManager(1)); switch (pt) { case MACHINE: JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) u.unmarshal(r, MachinePolicy.class); bss.close(); if (foo != null && foo.getValue() != null) { return foo.getValue(); } break; case PROCESS: JAXBElement<ProcessPolicy> foo2 = (JAXBElement<ProcessPolicy>) u.unmarshal(r, ProcessPolicy.class); bss.close(); if (foo2 != null && foo2.getValue() != null) { return foo2.getValue(); } break; case STATISTICAL: JAXBElement<StatisticalServicePolicy> foo3 = (JAXBElement<StatisticalServicePolicy>) u.unmarshal(r, StatisticalServicePolicy.class); bss.close(); if (foo3 != null && foo3.getValue() != null) { return foo3.getValue(); } break; case STATUS: JAXBElement<StatusServicePolicy> foo4 = (JAXBElement<StatusServicePolicy>) u.unmarshal(r, StatusServicePolicy.class); bss.close(); if (foo4 != null && foo4.getValue() != null) { return foo4.getValue(); } break; case TRANSACTIONAL: JAXBElement<TransactionalWebServicePolicy> foo5 = (JAXBElement<TransactionalWebServicePolicy>) u .unmarshal(r, TransactionalWebServicePolicy.class); bss.close(); if (foo5 != null && foo5.getValue() != null) { return foo5.getValue(); } break; } bss.close(); Logger.getLogger(Helper.class).log(Level.WARN, "ServicePolicy is unexpectedly null or empty"); return null; } catch (Exception ex) { Logger.getLogger(Helper.class).log(Level.ERROR, null, ex); } return null; }
From source file:com.eviware.soapui.impl.wsdl.monitor.JProxyServletWsdlMonitorMessageExchange.java
private void parseResponseData(IncomingWss incomingResponseWss) { ByteArrayInputStream in = new ByteArrayInputStream(response == null ? new byte[0] : response); try {/*from w w w . j a v a2 s . c o m*/ responseContentType = responseHeaders.get("Content-Type", ""); if (responseContent == null) { if (responseContentType != null && responseContentType.toUpperCase().startsWith("MULTIPART")) { StringToStringMap values = StringToStringMap.fromHttpHeader(responseContentType); responseMmSupport = new MultipartMessageSupport( new MonitorMessageExchangeDataSource("monitor response", in, responseContentType), values.get("start"), null, true, false); responseContentType = responseMmSupport.getRootPart().getContentType(); } else { String charset = getCharset(responseHeaders); this.responseContent = charset == null ? Tools.readAll(in, 0).toString() : Tools.readAll(in, 0).toString(charset); } } processResponseWss(incomingResponseWss); } catch (Exception e) { SoapUI.logError(e); } finally { try { in.close(); } catch (IOException e1) { SoapUI.logError(e1); } } }
From source file:com.hp.application.automation.tools.results.RunResultRecorder.java
private Boolean collectAndPrepareHtmlReports(Run build, TaskListener listener, List<ReportMetaData> htmlReportsInfo, FilePath runWorkspace) throws IOException, InterruptedException { File reportDir = new File(new File(build.getRootDir(), "archive"), "UFTReport"); FilePath rootTarget = new FilePath(reportDir); try {/*from w ww .ja v a2s . com*/ for (ReportMetaData htmlReportInfo : htmlReportsInfo) { // make sure it's a html report if (!htmlReportInfo.getIsHtmlReport()) { continue; } String htmlReportDir = htmlReportInfo.getFolderPath(); // C:\UFTTest\GuiTest1\Report listener.getLogger().println("collectAndPrepareHtmlReports, collecting:" + htmlReportDir); listener.getLogger().println("workspace: " + runWorkspace); // copy to the subdirs of master FilePath source = new FilePath(runWorkspace, htmlReportDir); listener.getLogger().println("source: " + source); String testName = htmlReportInfo.getDisPlayName(); // like "GuiTest1" String dest = testName; FilePath targetPath = new FilePath(rootTarget, dest); // target path is something like "C:\Program Files // (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\GuiTest1" // zip copy and unzip ByteArrayOutputStream outstr = new ByteArrayOutputStream(); // don't use FileFilter for zip, or it will cause bug when files are on slave source.zip(outstr); ByteArrayInputStream instr = new ByteArrayInputStream(outstr.toByteArray()); String zipFileName = "UFT_Report_HTML_tmp.zip"; FilePath archivedFile = new FilePath(rootTarget, zipFileName); archivedFile.copyFrom(instr); listener.getLogger().println("copy from slave to master: " + archivedFile); outstr.close(); instr.close(); // unzip archivedFile.unzip(rootTarget); archivedFile.delete(); // now,all the files are in the C:\Program Files (x86) // \Jenkins\jobs\testAction\builds\35\archive\UFTReport\Report // we need to rename the above path to targetPath. // So at last we got files in C:\Program Files (x86) // \Jenkins\jobs\testAction\builds\35\archive\UFTReport\GuiTest String unzippedFileName = org.apache.commons.io.FilenameUtils.getName(htmlReportDir); FilePath unzippedFolderPath = new FilePath(rootTarget, unzippedFileName); // C:\Program Files // (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\Report // FilePath unzippedFolderPath = new FilePath(rootTarget, source.getName()); //C:\Program Files // (x86)\Jenkins\jobs\testAction\builds\35\archive\UFTReport\Report unzippedFolderPath.renameTo(targetPath); listener.getLogger() .println("UnzippedFolderPath is: " + unzippedFolderPath + " targetPath is: " + targetPath); // end zip copy and unzip // fill in the urlName of this report. we need a network path not a FS path String resourceUrl = htmlReportInfo.getResourceURL(); String urlName = resourceUrl + "/run_results.html"; // like artifact/UFTReport/GuiTest1/run_results.html listener.getLogger().println("set the report urlName to " + urlName); htmlReportInfo.setUrlName(urlName); } } catch (Exception ex) { listener.getLogger().println("catch exception in collectAndPrepareHtmlReports: " + ex); } return true; }
From source file:ch.rgw.tools.StringTool.java
/** * Ein mit flatten() erzeugtes Byte-Array wieder in eine HAshtable zurckverwandeln * /*from www . j a va2 s . c o m*/ * @param flat * Die komprimierte Hashtable * @param compressMode * Expnad-Modus * @param ExtInfo * @return die Hastbale */ @SuppressWarnings("unchecked") @Deprecated public static Hashtable fold(final byte[] flat, final int compressMode, final Object ExtInfo) { ObjectInputStream ois = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(flat); switch (compressMode) { case BZIP: ois = new ObjectInputStream(new CBZip2InputStream(bais)); break; case HUFF: ois = new ObjectInputStream(new HuffmanInputStream(bais)); break; case GLZ: ois = new ObjectInputStream(new GLZInputStream(bais)); break; case ZIP: ZipInputStream zis = new ZipInputStream(bais); zis.getNextEntry(); ois = new ObjectInputStream(zis); break; case GUESS: Hashtable<Object, Object> res = fold(flat, ZIP, null); if (res == null) { res = fold(flat, GLZ, null); if (res == null) { res = fold(flat, BZIP, null); if (res == null) { res = fold(flat, HUFF, ExtInfo); if (res == null) { return null; } } } } return res; default: ois = new ObjectInputStream(bais); break; } Hashtable<Object, Object> res = (Hashtable<Object, Object>) ois.readObject(); ois.close(); bais.close(); return res; } catch (Exception ex) { // ExHandler.handle(ex); deliberately don't mind return null; } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java
private void loadRMDelegationTokenState(RMState rmState) throws Exception { List<String> childNodes = getChildren(delegationTokensRootPath); for (String childNodeName : childNodes) { String childNodePath = getNodePath(delegationTokensRootPath, childNodeName); byte[] childData = getData(childNodePath); if (childData == null) { LOG.warn("Content of " + childNodePath + " is broken."); continue; }/*ww w .ja va 2 s .c om*/ ByteArrayInputStream is = new ByteArrayInputStream(childData); DataInputStream fsIn = new DataInputStream(is); try { if (childNodeName.startsWith(DELEGATION_TOKEN_PREFIX)) { RMDelegationTokenIdentifierData identifierData = new RMDelegationTokenIdentifierData(); identifierData.readFields(fsIn); RMDelegationTokenIdentifier identifier = identifierData.getTokenIdentifier(); long renewDate = identifierData.getRenewDate(); rmState.rmSecretManagerState.delegationTokenState.put(identifier, renewDate); if (LOG.isDebugEnabled()) { LOG.debug("Loaded RMDelegationTokenIdentifier: " + identifier + " renewDate=" + renewDate); } } } finally { is.close(); } } }