public void run() { byte[] tmp = new byte[10000]; int read; try { FileInputStream fis = new FileInputStream(fileToSend.getFile()); read = fis.read(tmp); while (read != -1) { baos.write(tmp, 0, read); read = fis.read(tmp); System.out.println(read); } fis.close(); baos.writeTo(sWriter); sWriter.flush(); baos.flush(); baos.close(); System.out.println("fileSent"); } catch (IOException e) { e.printStackTrace(); } finally { this.closeSocket(); } }
private void flushRaw() throws IOException { if (currentRaw != null && currentRaw.size() > 0) { if (mode == Mode.Block) { output.writeInt(-1); } System.err.println("Writing raw chunk : " + currentRaw.size()); rawChunks += currentRaw.size(); output.writeInt(currentRaw.size()); currentRaw.writeTo(output); mode = Mode.Raw; } currentRaw = null; }
private void sendPacket(String outMessage) throws SeedSorterException, ChipperNotRunningException { System.out.println("Mock Chipper - sending packet to client: " + outMessage); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); byteOut.write(outMessage.getBytes(), 0, outMessage.length()); try { byteOut.writeTo(clientSocket.getOutputStream()); byteOut.flush(); } catch (IOException e) { e.printStackTrace(); throw new SeedSorterException("-- sendPacket() - I/O error", e); } }
/** * 设置编码方式,保存文件内容 * * @param fileName 文件名 * @param fileContent 文件内容 * @param charset 字符集 */ public static void saveFileContent(String fileName, Object fileContent, String charset) { BufferedOutputStream bosFile = null; try { // 创建失败 createFilePath(fileName); // 创建成功 bosFile = new BufferedOutputStream(new FileOutputStream(fileName)); // 判断传入的对象类型 如果是String 则直接保存 其他的则认为是JAXB对象 if (fileContent instanceof String) { bosFile.write( null == charset ? fileContent.toString().getBytes() : fileContent.toString().getBytes(charset)); } // 如果是流文件 else if (fileContent instanceof ByteArrayOutputStream) { ((ByteArrayOutputStream) fileContent).writeTo(bosFile); // } // JAXB对象 // else // if(fileContent.getClass().isAnnotationPresent(XmlRootElement.class)){ // ByteArrayOutputStream xmlbyteos = // marshall(fileContent.getClass(), fileContent); // xmlbyteos.writeTo(bosFile); } else { } bosFile.close(); if (RemexConstants.logger.isDebugEnabled()) { StringBuilder msg = new StringBuilder("文件保存成功,路径:【").append(fileName).append("】"); RemexConstants.logger.debug(msg); } } catch (Exception e) { String msg = new StringBuilder("保存报文失败!报文路径是:").append(fileName).toString(); RemexConstants.logger.error(msg, e); throw new RIOException(msg, e); } finally { if (bosFile != null) { try { bosFile.close(); } catch (IOException e) { RemexConstants.logger.error(e); } } } }
/** * Writes the data from this output stream to the specified output stream, after it has been * closed. * * @param out output stream to write to. * @exception IOException if this stream is not yet closed or an error occurs. */ public void writeTo(OutputStream out) throws IOException { // we may only need to check if this is closed if we are working with a file // but we should force the habit of closing wether we are working with // a file or memory. if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
private void writeAdditionalUninstallData(UninstallData udata, JarOutputStream outJar) throws IOException { Map<String, Object> additionalData = udata.getAdditionalData(); if (additionalData != null && !additionalData.isEmpty()) { Set<String> exist = new HashSet<String>(); for (String key : additionalData.keySet()) { Object contents = additionalData.get(key); if ("__uninstallLibs__".equals(key)) { for (Object o : ((List) contents)) { String nativeLibName = (String) ((List) o).get(0); byte[] buffer = new byte[5120]; long bytesCopied = 0; int bytesInBuffer; outJar.putNextEntry(new JarEntry("/com/izforge/izpack/bin/native/" + nativeLibName)); InputStream in = getClass().getResourceAsStream("/com/izforge/izpack/bin/native/" + nativeLibName); while ((bytesInBuffer = in.read(buffer)) != -1) { outJar.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } outJar.closeEntry(); } } else if ("uninstallerListeners".equals(key) || "uninstallerJars".equals(key)) { // It is a ArrayList of ArrayLists which contains the full // package paths of all needed class files. // First we create a new ArrayList which contains only // the full paths for the uninstall listener self; thats // the first entry of each sub ArrayList. ArrayList<String> subContents = new ArrayList<String>(); // Secound put the class into uninstaller.jar for (Object o : ((List) contents)) { byte[] buffer = new byte[5120]; long bytesCopied = 0; int bytesInBuffer; CustomData customData = (CustomData) o; // First element of the list contains the listener // class path; // remind it for later. if (customData.listenerName != null) { subContents.add(customData.listenerName); } for (String content : customData.contents) { if (exist.contains(content)) { continue; } exist.add(content); try { outJar.putNextEntry(new JarEntry(content)); } catch (JarException je) { // Ignore, or ignore not ?? May be it is a // exception because // a doubled entry was tried, then we should // ignore ... Debug.trace("JarException in writing custom data: " + je.getMessage()); continue; } InputStream in = getClass().getResourceAsStream("/" + content); if (in != null) { while ((bytesInBuffer = in.read(buffer)) != -1) { outJar.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } } else { Debug.trace("custom data not found: " + content); } outJar.closeEntry(); } } // Third we write the list into the // uninstaller.jar outJar.putNextEntry(new JarEntry(key)); ObjectOutputStream objOut = new ObjectOutputStream(outJar); objOut.writeObject(subContents); objOut.flush(); outJar.closeEntry(); } else { outJar.putNextEntry(new JarEntry(key)); if (contents instanceof ByteArrayOutputStream) { ((ByteArrayOutputStream) contents).writeTo(outJar); } else { ObjectOutputStream objOut = new ObjectOutputStream(outJar); objOut.writeObject(contents); objOut.flush(); } outJar.closeEntry(); } } } }
/** * Process the specified HTTP request, and create the corresponding HTTP response (or forward to * another web component that will create it). Return an <code>ActionForward</code> instance * describing where and how control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @exception Exception if business logic throws an exception */ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Extract attributes we will need MessageResources messages = getResources(request); // save errors ActionMessages errors = new ActionMessages(); // START check for login (security) if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) { return (mapping.findForward("welcome")); } // END check for login (security) // START get id of current project from either request, attribute, or cookie // id of project from request String projectId = null; projectId = request.getParameter("projectViewId"); // check attribute in request if (projectId == null) { projectId = (String) request.getAttribute("projectViewId"); } // id of project from cookie if (projectId == null) { projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies()); } // default project to last if not in request or cookie if (projectId == null) { java.util.List results = ProjectService.getInstance().getProjectList(); ListIterator iterScroll = null; for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {} iterScroll.previous(); Project p = (Project) iterScroll.next(); projectId = String.valueOf(p.getProjectId()); } Integer id = Integer.valueOf(projectId); // END get id of current project from either request, attribute, or cookie // get project Project p = ProjectService.getInstance().getSingleProject(id); // get user (project manager) User u = UserService.getInstance() .getSingleUserRealName( StandardCode.getInstance().getFirstName(p.getPm()), StandardCode.getInstance().getLastName(p.getPm())); // START process pdf try { PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template // save the pdf in memory ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); // the filled-in pdf PdfStamper stamp = new PdfStamper(reader, pdfStream); // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting); AcroFields form1 = stamp.getAcroFields(); Date cDate = new Date(); Integer month = cDate.getMonth(); Integer day = cDate.getDate(); Integer year = cDate.getYear() + 1900; String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // set the field values in the pdf form // form1.setField("", projectId) form1.setField("currentdate", monthName[month] + " " + day + ", " + year); form1.setField( "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name())); form1.setField("pm", p.getPm()); form1.setField("emailpm", u.getWorkEmail1()); if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present form1.setField( "phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()) + " ext " + StandardCode.getInstance().noNull(u.getWorkPhoneEx())); } else { // no ext present form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone())); } form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number())); form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation())); // START add images // if(u.getPicture() != null && u.getPicture().length() > 0) { // PdfContentByte over; // Image img = Image.getInstance("C:/Program Files (x86)/Apache Software // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture()); // img.setAbsolutePosition(200, 200); // over = stamp.getOverContent(1); // over.addImage(img, 54, 0,0, 65, 47, 493); // } // END add images form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct())); form1.setField("project", p.getNumber() + p.getCompany().getCompany_code()); form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription())); form1.setField("additional", p.getProjectRequirements()); // get sources and targets StringBuffer sources = new StringBuffer(""); StringBuffer targets = new StringBuffer(""); if (p.getSourceDocs() != null) { for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) { SourceDoc sd = (SourceDoc) iterSource.next(); sources.append(sd.getLanguage() + " "); if (sd.getTargetDocs() != null) { for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) { TargetDoc td = (TargetDoc) iterTarget.next(); if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " "); } } } } form1.setField("source", sources.toString()); form1.setField("target", targets.toString()); form1.setField( "start", (p.getStartDate() != null) ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate()) : ""); form1.setField( "due", (p.getDueDate() != null) ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate()) : ""); if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) { form1.setField( "cost", (p.getProjectAmount() != null) ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount()) : ""); } else { form1.setField( "cost", (p.getProjectAmount() != null) ? "€ " + StandardCode.getInstance() .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate()) : ""); } // stamp.setFormFlattening(true); stamp.close(); // write to client (web browser) response.setHeader( "Content-disposition", "attachment; filename=" + p.getNumber() + p.getCompany().getCompany_code() + "-Order-Confirmation" + ".pdf"); OutputStream os = response.getOutputStream(); pdfStream.writeTo(os); os.flush(); } catch (Exception e) { System.err.println("PDF Exception:" + e.getMessage()); throw new RuntimeException(e); } // END process pdf // Forward control to the specified success URI return (mapping.findForward("Success")); }
/** * Switches the underlying output stream from a memory based stream to one that is backed by disk. * This is the point at which we realise that too much data is being written to keep in memory, so * we elect to switch to disk-based storage. * * @exception IOException if an error occurs. */ protected void thresholdReached() throws IOException { FileOutputStream fos = new FileOutputStream(outputFile); memoryOutputStream.writeTo(fos); currentOutputStream = fos; memoryOutputStream = null; }
private COSStream makeUniqObjectNames(Map objectNameMap, COSStream stream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[10240]; int read; InputStream is = stream.getUnfilteredStream(); while ((read = is.read(buf)) > -1) { baos.write(buf, 0, read); } buf = baos.toByteArray(); baos = new ByteArrayOutputStream(buf.length + 100); StringBuffer sbObjectName = new StringBuffer(10); boolean bInObjectIdent = false; boolean bInText = false; boolean bInEscape = false; for (int i = 0; i < buf.length; i++) { byte b = buf[i]; if (!bInEscape) { if (!bInText && b == '(') { bInText = true; } if (bInText && b == ')') { bInText = false; } if (b == '\\') { bInEscape = true; } if (!bInText && !bInEscape) { if (b == '/') { bInObjectIdent = true; } else if (bInObjectIdent && Character.isWhitespace((char) b)) { bInObjectIdent = false; // System.err.println(sbObjectName); // String object = sbObjectName.toString(); String objectName = sbObjectName.toString().substring(1); String newObjectName = objectName + "overlay"; baos.write('/'); baos.write(newObjectName.getBytes("ISO-8859-1")); objectNameMap.put(objectName, COSName.getPDFName(newObjectName)); sbObjectName.delete(0, sbObjectName.length()); } } if (bInObjectIdent) { sbObjectName.append((char) b); continue; } } else { bInEscape = false; } baos.write(b); } COSDictionary streamDict = new COSDictionary(); streamDict.setInt(COSName.LENGTH, baos.size()); COSStream output = new COSStream(streamDict, pdfDocument.getDocument().getScratchFile()); output.setFilters(stream.getFilters()); OutputStream os = output.createUnfilteredStream(); baos.writeTo(os); os.close(); return output; }
private void unpackSegment(InputStream in, JarOutputStream out) throws IOException { _props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS, "0"); // Process the output directory or jar output. new PackageReader(pkg, in).read(); if (_props.getBoolean("unpack.strip.debug")) pkg.stripAttributeKind("Debug"); if (_props.getBoolean("unpack.strip.compile")) pkg.stripAttributeKind("Compile"); _props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS, "50"); pkg.ensureAllClassFiles(); // Now write out the files. HashSet classesToWrite = new HashSet(pkg.getClasses()); for (Iterator i = pkg.getFiles().iterator(); i.hasNext(); ) { Package.File file = (Package.File) i.next(); String name = file.nameString; JarEntry je = new JarEntry(Utils.getJarEntryName(name)); boolean deflate; deflate = (keepDeflateHint) ? (((file.options & Constants.FO_DEFLATE_HINT) != 0) || ((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0)) : deflateHint; boolean needCRC = !deflate; // STORE mode requires CRC if (needCRC) crc.reset(); bufOut.reset(); if (file.isClassStub()) { Package.Class cls = file.getStubClass(); assert (cls != null); new ClassWriter(cls, needCRC ? crcOut : bufOut).write(); classesToWrite.remove(cls); // for an error check } else { // collect data & maybe CRC file.writeTo(needCRC ? crcOut : bufOut); } je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED); if (needCRC) { if (verbose > 0) Utils.log.info("stored size=" + bufOut.size() + " and crc=" + crc.getValue()); je.setMethod(JarEntry.STORED); je.setSize(bufOut.size()); je.setCrc(crc.getValue()); } if (keepModtime) { je.setTime(file.modtime); // Convert back to milliseconds je.setTime((long) file.modtime * 1000); } else { je.setTime((long) modtime * 1000); } out.putNextEntry(je); bufOut.writeTo(out); out.closeEntry(); if (verbose > 0) Utils.log.info("Writing " + Utils.zeString((ZipEntry) je)); } assert (classesToWrite.isEmpty()); _props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS, "100"); pkg.reset(); // reset for the next segment, if any }
/** * Executes this instance. * * @return the autodiscover response * @throws ServiceLocalException the service local exception * @throws Exception the exception */ protected AutodiscoverResponse internalExecute() throws ServiceLocalException, Exception { this.validate(); HttpWebRequest request = null; try { request = this.service.prepareHttpWebRequestForUrl(this.url); this.service.traceHttpRequestHeaders(TraceFlags.AutodiscoverRequestHttpHeaders, request); boolean needSignature = this.getService().getCredentials() != null && this.getService().getCredentials().isNeedSignature(); boolean needTrace = this.getService().isTraceEnabledFor(TraceFlags.AutodiscoverRequest); OutputStream urlOutStream = request.getOutputStream(); // OutputStreamWriter out = new OutputStreamWriter(request // .getOutputStream()); ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(); EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.getService(), memoryStream); writer.setRequireWSSecurityUtilityNamespace(needSignature); this.writeSoapRequest(this.url, writer); if (needSignature) { this.service.getCredentials().sign(memoryStream); } if (needTrace) { memoryStream.flush(); this.service.traceXml(TraceFlags.AutodiscoverRequest, memoryStream); } memoryStream.writeTo(urlOutStream); urlOutStream.flush(); urlOutStream.close(); memoryStream.close(); // out.write(memoryStream.toString()); // out.close(); request.executeRequest(); request.getResponseCode(); if (AutodiscoverRequest.isRedirectionResponse(request)) { AutodiscoverResponse response = this.createRedirectionResponse(request); if (response != null) { return response; } else { throw new ServiceRemoteException("The service returned an invalid redirection response."); } } /* * BufferedReader in = new BufferedReader(new * InputStreamReader(request.getInputStream())); * * String decodedString; * * while ((decodedString = in.readLine()) != null) { * System.out.println(decodedString); } in.close(); */ memoryStream = new ByteArrayOutputStream(); InputStream serviceResponseStream = request.getInputStream(); while (true) { int data = serviceResponseStream.read(); if (-1 == data) { break; } else { memoryStream.write(data); } } memoryStream.flush(); serviceResponseStream.close(); if (this.service.isTraceEnabled()) { this.service.traceResponse(request, memoryStream); } ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray()); EwsXmlReader ewsXmlReader = new EwsXmlReader(memoryStreamIn); // WCF may not generate an XML declaration. ewsXmlReader.read(); if (ewsXmlReader.getNodeType().getNodeType() == XmlNodeType.START_DOCUMENT) { ewsXmlReader.readStartElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); } else if ((ewsXmlReader.getNodeType().getNodeType() != XmlNodeType.START_ELEMENT) || (!ewsXmlReader.getLocalName().equals(XmlElementNames.SOAPEnvelopeElementName)) || (!ewsXmlReader .getNamespaceUri() .equals(EwsUtilities.getNamespaceUri(XmlNamespace.Soap)))) { throw new ServiceXmlDeserializationException( "The Autodiscover service response was invalid."); } this.readSoapHeaders(ewsXmlReader); AutodiscoverResponse response = this.readSoapBody(ewsXmlReader); ewsXmlReader.readEndElement(XmlNamespace.Soap, XmlElementNames.SOAPEnvelopeElementName); if (response.getErrorCode() == AutodiscoverErrorCode.NoError) { return response; } else { throw new AutodiscoverResponseException( response.getErrorCode(), response.getErrorMessage()); } } catch (XMLStreamException ex) { this.service.traceMessage( TraceFlags.AutodiscoverConfiguration, String.format("XML parsing error: %s", ex.getMessage())); // Wrap exception throw new ServiceRequestException( String.format("The request failed. %s", ex.getMessage()), ex); } catch (IOException ex) { this.service.traceMessage( TraceFlags.AutodiscoverConfiguration, String.format("I/O error: %s", ex.getMessage())); // Wrap exception throw new ServiceRequestException( String.format("The request failed. %s", ex.getMessage()), ex); } catch (Exception ex) { // HttpWebRequest httpWebResponse = (HttpWebRequest)ex; if (null != request && request.getResponseCode() == 7) { if (AutodiscoverRequest.isRedirectionResponse(request)) { this.service.processHttpResponseHeaders( TraceFlags.AutodiscoverResponseHttpHeaders, request); AutodiscoverResponse response = this.createRedirectionResponse(request); if (response != null) { return response; } } else { this.processWebException(ex, request); } } // Wrap exception if the above code block didn't throw throw new ServiceRequestException( String.format("The request failed. %s", ex.getMessage()), ex); } finally { try { if (request != null) { request.close(); } } catch (Exception e) { // do nothing } } }