List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:eu.fusepool.p3.proxy.ProxyHandler.java
@Override public void handle(String target, Request baseRequest, final HttpServletRequest inRequest, final HttpServletResponse outResponse) throws IOException, ServletException { final String targetUriString = targetBaseUri + inRequest.getRequestURI(); final String requestUri = getFullRequestUrl(inRequest); //System.out.println(targetUriString); final URI targetUri; try {// w w w . j av a2 s . co m targetUri = new URI(targetUriString); } catch (URISyntaxException ex) { throw new IOException(ex); } final String method = inRequest.getMethod(); final HttpEntityEnclosingRequestBase outRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return method; } }; outRequest.setURI(targetUri); String transformerUri = null; if (method.equals("POST")) { if (!"no-transform".equals(inRequest.getHeader("X-Fusepool-Proxy"))) { transformerUri = getTransformerUrl(requestUri); } } final Enumeration<String> headerNames = baseRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (headerName.equalsIgnoreCase("Content-Length") || headerName.equalsIgnoreCase("X-Fusepool-Proxy") || headerName.equalsIgnoreCase("Transfer-Encoding")) { continue; } final Enumeration<String> headerValues = baseRequest.getHeaders(headerName); if (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); outRequest.setHeader(headerName, headerValue); } while (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); outRequest.addHeader(headerName, headerValue); } } final Header[] outRequestHeaders = outRequest.getAllHeaders(); //slow: outRequest.setEntity(new InputStreamEntity(inRequest.getInputStream())); final byte[] inEntityBytes = IOUtils.toByteArray(inRequest.getInputStream()); if (inEntityBytes.length > 0) { outRequest.setEntity(new ByteArrayEntity(inEntityBytes)); } final CloseableHttpResponse inResponse = httpclient.execute(outRequest); try { outResponse.setStatus(inResponse.getStatusLine().getStatusCode()); final Header[] inResponseHeaders = inResponse.getAllHeaders(); final Set<String> setHeaderNames = new HashSet(); for (Header header : inResponseHeaders) { if (setHeaderNames.add(header.getName())) { outResponse.setHeader(header.getName(), header.getValue()); } else { outResponse.addHeader(header.getName(), header.getValue()); } } final HttpEntity entity = inResponse.getEntity(); final ServletOutputStream os = outResponse.getOutputStream(); if (entity != null) { //outResponse.setContentType(target); final InputStream instream = entity.getContent(); try { IOUtils.copy(instream, os); } finally { instream.close(); } } //without flushing this and no or too little byte jetty return 404 os.flush(); } finally { inResponse.close(); } if (transformerUri != null) { Header locationHeader = inResponse.getFirstHeader("Location"); if (locationHeader == null) { log.warn("Response to POST request to LDPC contains no Location header. URI: " + targetUriString); } else { startTransformation(locationHeader.getValue(), requestUri, transformerUri, inEntityBytes, outRequestHeaders); } } }
From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java
/** * Returns an output stream to the client containing a text file of all * entries and comments. This will include draft entries as well. * * Currently the only file format supported is mtimport. *///w w w. j a v a 2s .co m public void exportEntries() throws WebloggerException { if (!WebloggerConfig.getBooleanProperty("weblog.export.enabled")) { throw new WebloggerException("ERROR: export is disabled"); } try { WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager(); URLStrategy urlStrategy; urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy(); List rawEntries; rawEntries = wmgr.getWeblogEntries(getActionWeblog(), null, null, null, null, null, null, null, null, null, null, 0, -1); List<WeblogEntryWrapper> entries; entries = new ArrayList<WeblogEntryWrapper>(); for (Object entry : rawEntries) { entries.add(WeblogEntryWrapper.wrap((WeblogEntry) entry, urlStrategy)); } // Compile the resource URL pattern using the weblog handle baseUrlPattern = Pattern .compile("(<[\\s\\S]+?=[\"'])(http[s]*?://[\\S]+/" + getActionWeblog().getHandle() + "/resource/|/" + getActionWeblog().getHandle() + "/resource/)"); // Produce the selected output format String output; output = formatAsMoveableType(entries); /* if (format.equals(ATOM_FORMAT)) { output = formatAsAtom(entries); } else { output = formatAsMoveableType(entries); } */ if (!response.isCommitted()) { response.reset(); SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("MMddyyyy'T'HHmmss"); StringBuilder fileName; fileName = new StringBuilder(); fileName.append(getActionWeblog().getHandle()); fileName.append("-entries-"); fileName.append(dateFormat.format(System.currentTimeMillis())); if (format.equals(ATOM_FORMAT)) { fileName.append(".xml"); } else { fileName.append(".txt"); } // Force the browser to download the export file response.setContentType("application/octet-stream; charset=utf-8"); response.setContentLength(output.getBytes("UTF-8").length); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\""); ServletOutputStream outputStream; outputStream = response.getOutputStream(); outputStream.print(output); outputStream.flush(); outputStream.close(); } } catch (WebloggerException e) { log.error("Error looking up entries: ", e); } catch (IOException e) { log.error("Error getting output stream: ", e); } }
From source file:au.org.ala.biocache.web.MapController.java
@Deprecated @RequestMapping(value = "/occurrences/wms", method = RequestMethod.GET) public void pointsWmsImage(SpatialSearchRequestParams requestParams, @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby, @RequestParam(value = "width", required = false, defaultValue = "256") Integer widthObj, @RequestParam(value = "height", required = false, defaultValue = "256") Integer heightObj, @RequestParam(value = "zoom", required = false, defaultValue = "0") Integer zoomLevel, @RequestParam(value = "symsize", required = false, defaultValue = "4") Integer symsize, @RequestParam(value = "symbol", required = false, defaultValue = "circle") String symbol, @RequestParam(value = "bbox", required = false, defaultValue = "110,-45,157,-9") String bboxString, @RequestParam(value = "type", required = false, defaultValue = "normal") String type, @RequestParam(value = "outline", required = true, defaultValue = "false") boolean outlinePoints, @RequestParam(value = "outlineColour", required = true, defaultValue = "0x000000") String outlineColour, HttpServletResponse response) throws Exception { // size of the circles int size = symsize.intValue(); int width = widthObj.intValue(); int height = heightObj.intValue(); requestParams.setStart(0);/*w w w.j av a2 s . c om*/ requestParams.setPageSize(Integer.MAX_VALUE); String query = requestParams.getQ(); String[] filterQuery = requestParams.getFq(); if (StringUtils.isBlank(query) && StringUtils.isBlank(requestParams.getFormattedQuery())) { displayBlankImage(width, height, false, response); return; } // let's force it to PNG's for now response.setContentType("image/png"); // Convert array to list so we append more values onto it ArrayList<String> fqList = null; if (filterQuery != null) { fqList = new ArrayList<String>(Arrays.asList(filterQuery)); } else { fqList = new ArrayList<String>(); } // the bounding box double[] bbox = new double[4]; int i; i = 0; for (String s : bboxString.split(",")) { try { bbox[i] = Double.parseDouble(s); i++; } catch (Exception e) { logger.error(e.getMessage(), e); } } double pixelWidth = (bbox[2] - bbox[0]) / width; double pixelHeight = (bbox[3] - bbox[1]) / height; bbox[0] += pixelWidth / 2; bbox[2] -= pixelWidth / 2; bbox[1] += pixelHeight / 2; bbox[3] -= pixelHeight / 2; //offset for points bounding box by size double xoffset = (bbox[2] - bbox[0]) / (double) width * (size * 2); double yoffset = (bbox[3] - bbox[1]) / (double) height * (size * 2); //adjust offset for pixel height/width xoffset += pixelWidth; yoffset += pixelHeight; double[] bbox2 = new double[4]; bbox2[0] = convertMetersToLng(bbox[0] - xoffset); bbox2[1] = convertMetersToLat(bbox[1] - yoffset); bbox2[2] = convertMetersToLng(bbox[2] + xoffset); bbox2[3] = convertMetersToLat(bbox[3] + yoffset); bbox[0] = convertMetersToLng(bbox[0]); bbox[1] = convertMetersToLat(bbox[1]); bbox[2] = convertMetersToLng(bbox[2]); bbox[3] = convertMetersToLat(bbox[3]); double[] pbbox = new double[4]; //pixel bounding box pbbox[0] = convertLngToPixel(bbox[0]); pbbox[1] = convertLatToPixel(bbox[1]); pbbox[2] = convertLngToPixel(bbox[2]); pbbox[3] = convertLatToPixel(bbox[3]); String bboxString2 = bbox2[0] + "," + bbox2[1] + "," + bbox2[2] + "," + bbox2[3]; bboxToQuery(bboxString2, fqList); PointType pointType = getPointTypeForZoomLevel(zoomLevel); String[] newFilterQuery = (String[]) fqList.toArray(new String[fqList.size()]); // convert back to array requestParams.setFq(newFilterQuery); List<OccurrencePoint> points = searchDAO.getFacetPoints(requestParams, pointType); logger.debug("Points search for " + pointType.getLabel() + " - found: " + points.size()); if (points.size() == 0) { displayBlankImage(width, height, false, response); return; } BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(Color.RED); int x, y; int pointWidth = size * 2; double width_mult = (width / (pbbox[2] - pbbox[0])); double height_mult = (height / (pbbox[1] - pbbox[3])); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color oColour = Color.decode(outlineColour); for (i = 0; i < points.size(); i++) { OccurrencePoint pt = points.get(i); float lng = pt.getCoordinates().get(0).floatValue(); float lat = pt.getCoordinates().get(1).floatValue(); x = (int) ((convertLngToPixel(lng) - pbbox[0]) * width_mult); y = (int) ((convertLatToPixel(lat) - pbbox[3]) * height_mult); if (colourby != null) { int colour = 0xFF000000 | colourby.intValue(); Color c = new Color(colour); g.setPaint(c); } else { g.setPaint(Color.blue); } // g.fillOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth); Shape shp = getShape(symbol, x - (size / 2), y - (size / 2), pointWidth, pointWidth); g.draw(shp); g.fill(shp); if (outlinePoints) { g.setPaint(oColour); g.drawOval(x - (size / 2), y - (size / 2), pointWidth, pointWidth); } } g.dispose(); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image", e); } }
From source file:com.iana.dver.controller.DverAdminController.java
private void write(HttpServletResponse response, HSSFSheet worksheet) throws IOException { logger.info("Writing excel report to the response stream..."); // Retrieve the output stream ServletOutputStream outputStream = response.getOutputStream(); // Write to the output stream worksheet.getWorkbook().write(outputStream); // Flush the stream outputStream.flush(); }
From source file:org.kuali.ole.module.purap.document.web.struts.ElectronicInvoiceTestAction.java
/** * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only. *///from ww w. j ava 2 s . com public ActionForward generate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { checkAuthorization(form, ""); ElectronicInvoiceTestForm testForm = (ElectronicInvoiceTestForm) form; String poDocNumber = testForm.getPoDocNumber(); LOG.info("Generating Electronic Invoice XML file for Purchase Order Document " + poDocNumber); PurchaseOrderService poService = SpringContext.getBean(PurchaseOrderService.class); PurchaseOrderDocument po = null; if (StringUtils.isBlank(poDocNumber)) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER, PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_NUMBER_EMPTY, new String[] { poDocNumber }); return mapping.findForward(RiceConstants.MAPPING_BASIC); } if (!getDocumentService().documentExists(poDocNumber)) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER, PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_DOES_NOT_EXIST, poDocNumber); return mapping.findForward(RiceConstants.MAPPING_BASIC); } try { po = poService.getPurchaseOrderByDocumentNumber(poDocNumber); } catch (Exception e) { throw e; } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/xml"); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PO_"); sbFilename.append(poDocNumber); sbFilename.append(".xml"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); // lookup the PO and fill in the XML with valid data if (po != null) { String duns = ""; if (po.getVendorDetail() != null) { duns = StringUtils.defaultString(po.getVendorDetail().getVendorDunsNumber()); } DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class); String currDate = ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()); // getting date in ole format String vendorNumber = po.getVendorDetail().getVendorNumber(); String eInvoiceFile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n<!-- ******Testing tool generated XML****** Version 1.2." + "\n\n Generated On " + currDate + " for PO " + po.getPurapDocumentIdentifier() + " (Doc# " + poDocNumber + ") -->\n\n" + "<!-- All the cXML attributes are junk values -->\n" + "<cXML payloadID=\"200807260401062080.964@eai002\"\n" + " timestamp=\"2008-07-26T04:01:06-08:00\"\n" + " version=\"1.2.014\" xml:lang=\"en\" \n" + " xmlns=\"http://www.kuali.org/ole/purap/electronicInvoice\" \n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + " <Header>\n" + " <From>\n" + " <Credential domain=\"DUNS\">\n" + " <Identity>" + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n" + " </Credential>\n" + " </From>\n" + " <To>\n" + " <Credential domain=\"NetworkId\">\n" + " <Identity>" + "IU" + "</Identity> <!-- Hardcoded --> \n" + " </Credential>\n" + " </To>\n" + " <Sender>\n" + " <Credential domain=\"DUNS\">\n" + " <Identity>" + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n" + " </Credential>\n" + " <UserAgent/>\n" + " </Sender>\n" + " </Header>\n" + " <Request deploymentMode=\"production\">\n" + " <InvoiceDetailRequest>\n" + " <InvoiceDetailRequestHeader\n" + " invoiceDate=\"" + currDate + "\" invoiceID=\"" + RandomUtils.nextInt() + "\" operation=\"new\" purpose=\"standard\"> <!-- invoiceID=Random unique Id, invoiceDate=Curr date -->\n" + " <InvoiceDetailHeaderIndicator/>\n" + " <InvoiceDetailLineIndicator/>\n" + " <InvoicePartner>\n" + getContactXMLChunk("billTo", po) + " </InvoicePartner>\n" + " <InvoicePartner>\n" + " <Contact addressID=\"" + RandomUtils.nextInt() + "\" role=\"remitTo\"> <!-- Vendor address -->\n" + " <Name xml:lang=\"en\">\n" + " " + po.getVendorName() + "\n" + " </Name>\n" + " <PostalAddress>\n" + " <Street>" + StringUtils.defaultString(po.getVendorLine1Address()) + "</Street>\n" + " <Street>" + StringUtils.defaultString(po.getVendorLine2Address()) + "</Street>\n" + " <City>" + StringUtils.defaultString(po.getVendorCityName()) + "</City>\n" + " <State>" + StringUtils.defaultString(po.getVendorStateCode()) + "</State>\n" + " <PostalCode>" + StringUtils.defaultString(po.getVendorPostalCode()) + "</PostalCode>\n" + " <Country isoCountryCode=\"" + StringUtils.defaultString(po.getVendorCountryCode()) + "\">\n" + " " + StringUtils.defaultString(po.getVendorCountry().getName()) + "\n" + " </Country>\n" + " </PostalAddress>\n" + " </Contact>\n" + " </InvoicePartner>\n" + getDeliveryAddressXMLChunk("shipTo", po) + getPaymentTermXML(po) + " </InvoiceDetailRequestHeader>\n" + " <InvoiceDetailOrder>\n" + " <InvoiceDetailOrderInfo>\n" + " <OrderReference\n" + " orderDate=\"" + ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()) + "\" orderID=\"" + po.getPurapDocumentIdentifier() + "\"> <!--orderDate=Curr date,orderID=PO#-->\n" + " <DocumentReference payloadID=\"NA\" /> <!--HardCoded-->\n" + " </OrderReference>\n" + " </InvoiceDetailOrderInfo>\n" + " <!-- No junk values in Items-->\n"; for (int i = 0; i < po.getItems().size(); i++) { List items = po.getItems(); PurchaseOrderItem item = (PurchaseOrderItem) items.get(i); if (!item.getItemType().isAdditionalChargeIndicator()) { eInvoiceFile = eInvoiceFile + getPOItemXMLChunk(item); } } KualiDecimal totalDollarAmt = po.getTotalDollarAmount() == null ? KualiDecimal.ZERO : po.getTotalDollarAmount(); eInvoiceFile = eInvoiceFile + " </InvoiceDetailOrder>\n" + " <InvoiceDetailSummary>\n" + " <SubtotalAmount>\n" + " <Money currency=\"USD\">" + po.getTotalPreTaxDollarAmount() + "</Money>\n" + " </SubtotalAmount>\n" + " <Tax>\n" + " <Money currency=\"USD\">" + po.getTotalTaxAmount() + "</Money>\n" + " <Description xml:lang=\"en\">Total Tax</Description>\n" + " </Tax>\n" + " <SpecialHandlingAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </SpecialHandlingAmount>\n" + " <ShippingAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </ShippingAmount>\n" + " <GrossAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </GrossAmount>\n" + " <InvoiceDetailDiscount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </InvoiceDetailDiscount>\n" + " <NetAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </NetAmount>\n" + " <DepositAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </DepositAmount>\n" + " <DueAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </DueAmount>\n" + " </InvoiceDetailSummary>\n" + " </InvoiceDetailRequest>\n" + " </Request>\n" + "</cXML>"; ServletOutputStream sos; sos = response.getOutputStream(); ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); StringBufferInputStream inStream = new StringBufferInputStream(eInvoiceFile); convert(baOutStream, inStream); response.setContentLength(baOutStream.size()); baOutStream.writeTo(sos); sos.flush(); } return mapping.findForward(OLEConstants.MAPPING_BASIC); }
From source file:fr.insalyon.creatis.vip.core.server.rpc.GetFileServiceImpl.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w ww. ja v a 2 s . c o m User user = CoreDAOFactory.getDAOFactory().getUserDAO() .getUserBySession(req.getParameter(CoreConstants.COOKIES_SESSION)); String filepath = req.getParameter("filepath"); if (filepath != null && !filepath.isEmpty()) { File file = new File(Server.getInstance().getWorkflowsPath() + filepath); boolean isDir = false; if (file.isDirectory()) { String zipName = file.getAbsolutePath() + ".zip"; FolderZipper.zipFolder(file.getAbsolutePath(), zipName); filepath = zipName; file = new File(zipName); isDir = true; } logger.info("(" + user.getEmail() + ") Downloading file '" + filepath + "'."); int length = 0; ServletOutputStream op = resp.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(file.getName()); resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); resp.setContentLength((int) file.length()); resp.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[4096]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } in.close(); op.flush(); op.close(); if (isDir) { FileUtils.deleteQuietly(file); } } } catch (DAOException ex) { throw new ServletException(ex); } }
From source file:org.kuali.kfs.module.purap.document.web.struts.ElectronicInvoiceTestAction.java
/** * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only. *///from ww w . j ava2s . c om public ActionForward generate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { checkAuthorization(form, ""); ElectronicInvoiceTestForm testForm = (ElectronicInvoiceTestForm) form; String poDocNumber = testForm.getPoDocNumber(); LOG.info("Generating Electronic Invoice XML file for Purchase Order Document " + poDocNumber); PurchaseOrderService poService = SpringContext.getBean(PurchaseOrderService.class); PurchaseOrderDocument po = null; if (StringUtils.isBlank(poDocNumber)) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER, PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_NUMBER_EMPTY, new String[] { poDocNumber }); return mapping.findForward(RiceConstants.MAPPING_BASIC); } if (!getDocumentService().documentExists(poDocNumber)) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER, PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_DOES_NOT_EXIST, poDocNumber); return mapping.findForward(RiceConstants.MAPPING_BASIC); } try { po = poService.getPurchaseOrderByDocumentNumber(poDocNumber); } catch (Exception e) { throw e; } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/xml"); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PO_"); sbFilename.append(poDocNumber); sbFilename.append(".xml"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); // lookup the PO and fill in the XML with valid data if (po != null) { String duns = ""; if (po.getVendorDetail() != null) { duns = StringUtils.defaultString(po.getVendorDetail().getVendorDunsNumber()); } DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class); String currDate = ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()); // getting date in kfs format String vendorNumber = po.getVendorDetail().getVendorNumber(); String eInvoiceFile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "\n<!-- ******Testing tool generated XML****** Version 1.2." + "\n\n Generated On " + currDate + " for PO " + po.getPurapDocumentIdentifier() + " (Doc# " + poDocNumber + ") -->\n\n" + "<!-- All the cXML attributes are junk values -->\n" + "<cXML payloadID=\"200807260401062080.964@eai002\"\n" + " timestamp=\"2008-07-26T04:01:06-08:00\"\n" + " version=\"1.2.014\" xml:lang=\"en\" \n" + " xmlns=\"http://www.kuali.org/kfs/purap/electronicInvoice\" \n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + " <Header>\n" + " <From>\n" + " <Credential domain=\"DUNS\">\n" + " <Identity>" + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n" + " </Credential>\n" + " </From>\n" + " <To>\n" + " <Credential domain=\"NetworkId\">\n" + " <Identity>" + "IU" + "</Identity> <!-- Hardcoded --> \n" + " </Credential>\n" + " </To>\n" + " <Sender>\n" + " <Credential domain=\"DUNS\">\n" + " <Identity>" + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n" + " </Credential>\n" + " <UserAgent/>\n" + " </Sender>\n" + " </Header>\n" + " <Request deploymentMode=\"production\">\n" + " <InvoiceDetailRequest>\n" + " <InvoiceDetailRequestHeader\n" + " invoiceDate=\"" + currDate + "\" invoiceID=\"" + RandomUtils.nextInt() + "\" operation=\"new\" purpose=\"standard\"> <!-- invoiceID=Random unique Id, invoiceDate=Curr date -->\n" + " <InvoiceDetailHeaderIndicator/>\n" + " <InvoiceDetailLineIndicator/>\n" + " <InvoicePartner>\n" + getContactXMLChunk("billTo", po) + " </InvoicePartner>\n" + " <InvoicePartner>\n" + " <Contact addressID=\"" + RandomUtils.nextInt() + "\" role=\"remitTo\"> <!-- Vendor address -->\n" + " <Name xml:lang=\"en\">\n" + " " + po.getVendorName() + "\n" + " </Name>\n" + " <PostalAddress>\n" + " <Street>" + StringUtils.defaultString(po.getVendorLine1Address()) + "</Street>\n" + " <Street>" + StringUtils.defaultString(po.getVendorLine2Address()) + "</Street>\n" + " <City>" + StringUtils.defaultString(po.getVendorCityName()) + "</City>\n" + " <State>" + StringUtils.defaultString(po.getVendorStateCode()) + "</State>\n" + " <PostalCode>" + StringUtils.defaultString(po.getVendorPostalCode()) + "</PostalCode>\n" + " <Country isoCountryCode=\"" + StringUtils.defaultString(po.getVendorCountryCode()) + "\">\n" + " " + StringUtils.defaultString(po.getVendorCountry().getName()) + "\n" + " </Country>\n" + " </PostalAddress>\n" + " </Contact>\n" + " </InvoicePartner>\n" + getDeliveryAddressXMLChunk("shipTo", po) + getPaymentTermXML(po) + " </InvoiceDetailRequestHeader>\n" + " <InvoiceDetailOrder>\n" + " <InvoiceDetailOrderInfo>\n" + " <OrderReference\n" + " orderDate=\"" + ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()) + "\" orderID=\"" + po.getPurapDocumentIdentifier() + "\"> <!--orderDate=Curr date,orderID=PO#-->\n" + " <DocumentReference payloadID=\"NA\" /> <!--HardCoded-->\n" + " </OrderReference>\n" + " </InvoiceDetailOrderInfo>\n" + " <!-- No junk values in Items-->\n"; for (int i = 0; i < po.getItems().size(); i++) { List items = po.getItems(); PurchaseOrderItem item = (PurchaseOrderItem) items.get(i); if (!item.getItemType().isAdditionalChargeIndicator()) { eInvoiceFile = eInvoiceFile + getPOItemXMLChunk(item); } } KualiDecimal totalDollarAmt = po.getTotalDollarAmount() == null ? KualiDecimal.ZERO : po.getTotalDollarAmount(); eInvoiceFile = eInvoiceFile + " </InvoiceDetailOrder>\n" + " <InvoiceDetailSummary>\n" + " <SubtotalAmount>\n" + " <Money currency=\"USD\">" + po.getTotalPreTaxDollarAmount() + "</Money>\n" + " </SubtotalAmount>\n" + " <Tax>\n" + " <Money currency=\"USD\">" + po.getTotalTaxAmount() + "</Money>\n" + " <Description xml:lang=\"en\">Total Tax</Description>\n" + " </Tax>\n" + " <SpecialHandlingAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </SpecialHandlingAmount>\n" + " <ShippingAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </ShippingAmount>\n" + " <GrossAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </GrossAmount>\n" + " <InvoiceDetailDiscount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </InvoiceDetailDiscount>\n" + " <NetAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </NetAmount>\n" + " <DepositAmount>\n" + " <Money currency=\"USD\">0.00</Money>\n" + " </DepositAmount>\n" + " <DueAmount>\n" + " <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n" + " </DueAmount>\n" + " </InvoiceDetailSummary>\n" + " </InvoiceDetailRequest>\n" + " </Request>\n" + "</cXML>"; ServletOutputStream sos; sos = response.getOutputStream(); ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); StringBufferInputStream inStream = new StringBufferInputStream(eInvoiceFile); convert(baOutStream, inStream); response.setContentLength(baOutStream.size()); baOutStream.writeTo(sos); sos.flush(); } return mapping.findForward(KFSConstants.MAPPING_BASIC); }
From source file:com.seer.datacruncher.spring.EventTriggerValidator.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); String name = request.getParameter("name"); String addReq = request.getParameter("addReq"); String result = null;//from w w w. ja va 2 s . c o m ObjectMapper mapper = new ObjectMapper(); ServletOutputStream out = null; response.setContentType("application/json"); out = response.getOutputStream(); if (StringUtils.isEmpty(code) || StringUtils.isEmpty(name)) { result = I18n.getMessage("error.trigger.invaliddata");//"Failed. Reason:Invalid Data"; } else { name = name.trim(); if (addReq.equalsIgnoreCase("true")) { ReadList list = eventTriggerDao.findTriggersByName(name); if (list != null && CollectionUtils.isNotEmpty(list.getResults())) { result = I18n.getMessage("error.trigger.name.alreadyexist");//"Failed. Reason:Name alredy exist"; out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; } } try { File sourceDir = new File(System.getProperty("java.io.tmpdir"), "DataCruncher/src"); sourceDir.mkdirs(); String classNamePack = name.replace('.', File.separatorChar); String srcFilePath = sourceDir + "" + File.separatorChar + classNamePack + ".java"; File sourceFile = new File(srcFilePath); if (sourceFile.exists()) { sourceFile.delete(); } FileUtils.writeStringToFile(new File(srcFilePath), code); DynamicClassLoader dynacode = DynamicClassLoader.getInstance(); dynacode.addSourceDir(sourceDir); EventTrigger eventTrigger = (EventTrigger) dynacode.newProxyInstance(EventTrigger.class, name); boolean isValid = false; if (eventTrigger != null) { Class clazz = dynacode.getLoadedClass(name); if (clazz != null) { Class[] interfaces = clazz.getInterfaces(); if (ArrayUtils.isNotEmpty(interfaces)) { for (Class clz : interfaces) { if (clz.getName() .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTrigger")) { isValid = true; } } } else if (clazz.getSuperclass() != null && clazz.getSuperclass().getName() .equalsIgnoreCase("com.seer.datacruncher.eventtrigger.EventTriggerImpl")) { isValid = true; } } } if (isValid) { result = "Success"; } else { result = I18n.getMessage("error.trigger.wrongimpl");//"Failed. Reason: Custom code should implement com.seer.datacruncher.eventtrigger.EventTrigger Interface"; } } catch (Exception e) { result = "Failed. Reason:" + e.getMessage(); } } out.write(mapper.writeValueAsBytes(result)); out.flush(); out.close(); return null; }
From source file:com.seer.datacruncher.spring.SchemaFieldsPopupUpdateController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idSchema = request.getParameter("idSchema"); String idSchemaField = request.getParameter("idSchemaField"); String idFieldType = request.getParameter("idFieldType"); String name = request.getParameter("name"); String description = request.getParameter("description"); String minLenght = request.getParameter("minLenght"); String maxLenght = request.getParameter("maxLenght"); String nillableAlphanumeric = request.getParameter("nillableAlphanumeric"); String idCheckType = request.getParameter("extraCheck"); String minInclusive = request.getParameter("minInclusive"); String maxInclusive = request.getParameter("maxInclusive"); String fractionDigits = request.getParameter("fractionDigits"); String nillableNumeric = request.getParameter("nillableNumeric"); String numericType = request.getParameter("numericType"); String idDateTimeType = request.getParameter("idDateTimeType"); String idDateType = request.getParameter("idDateType"); String idTimeType = request.getParameter("idTimeType"); String isForecastable = request.getParameter("isForecastable"); String forecastAccuracy = request.getParameter("forecastAccuracy"); String forecastSpeed = request.getParameter("forecastSpeed"); String nillableDate = request.getParameter("nillableDate"); String size = request.getParameter("size"); String idCustomError = request.getParameter("idCustomError"); String maxOccurs = request.getParameter("maxOccurs"); String linkToDb = request.getParameter("linkToDb"); String isAttribute = request.getParameter("isAttribute"); String errorType = request.getParameter("errorType"); String selectedExtraCheckVals = request.getParameter("selectedExtraCheck"); int errorToleranceValue = Integer.parseInt(request.getParameter("errorToleranceValue") == null ? "-1" : request.getParameter("errorToleranceValue")); boolean indexIncremental = Boolean.parseBoolean(request.getParameter("indexIncrementalValue")); SchemaEntity schemaEntity = schemasDao.find(Long.parseLong(idSchema)); SchemaFieldEntity schemaFieldEntity = schemaFieldsDao.find(Long.parseLong(idSchemaField)); schemasXSDDao.destroy(schemaFieldEntity.getIdSchema()); String oldLinkToDb = schemaFieldEntity.getLinkToDb(); schemaFieldEntity.setIdFieldType(Integer.parseInt(idFieldType)); schemaFieldEntity.setName(name);/*w w w . ja va 2 s . com*/ schemaFieldEntity.setDescription(description.replace('\u200b', ' ')); schemaFieldEntity.setErrorToleranceValue(errorToleranceValue); schemaFieldEntity.setIndexIncremental(indexIncremental); if (errorType != null) schemaFieldEntity.setErrorType(Integer.parseInt(request.getParameter("errorType"))); if ("1".equals(isAttribute) || "true".equals(isAttribute)) { schemaFieldEntity.setIs_Attribute(true); } else { schemaFieldEntity.setIs_Attribute(false); } if (maxOccurs != null && !maxOccurs.equals("")) { schemaFieldEntity.setMaxOccurs(Integer.parseInt(maxOccurs)); } else { schemaFieldEntity.setMaxOccurs(1); } boolean isLinkedToDbChanged = false; if (linkToDb != null && !linkToDb.isEmpty()) { schemaFieldEntity.setLinkToDb(linkToDb); isLinkedToDbChanged = true; } if (idCustomError != null && !idCustomError.isEmpty() && Long.parseLong(idCustomError) != -7) { schemaFieldEntity.setIdCustomError(Long.parseLong(idCustomError)); } if (schemaFieldEntity.getIdFieldType() == FieldType.alphanumeric) { if (minLenght != null && !minLenght.equals("")) { schemaFieldEntity.setMinLength(Integer.parseInt(minLenght)); } else { schemaFieldEntity.setMinLength(null); } if (maxLenght != null && !maxLenght.equals("")) { schemaFieldEntity.setMaxLength(Integer.parseInt(maxLenght)); } else { schemaFieldEntity.setMaxLength(null); } if (idCheckType != null && !idCheckType.equals("")) { schemaFieldEntity.setIdCheckType(Integer.parseInt(idCheckType)); } else { schemaFieldEntity.setIdCheckType(0); } if (StringUtils.isNotEmpty(selectedExtraCheckVals)) { // Delete existing entries from database schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField)); String[] extraCheckIds = selectedExtraCheckVals.split(","); Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>( extraCheckIds.length); SchemaFieldCheckTypesEntity schemaFieldCheckTypesEntity; for (String extraCheck : extraCheckIds) { schemaFieldCheckTypesEntity = new SchemaFieldCheckTypesEntity(); schemaFieldCheckTypesEntity.setIdCheckType(Long.parseLong(extraCheck)); schemaFieldCheckTypesEntity.setSchemaFieldEntity(schemaFieldEntity); schemaFieldCheckTypeSet.add(schemaFieldCheckTypesEntity); schemaFieldCheckTypesEntity = null; } schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet); } else { List<String> list = schemaFieldsDao.findSchemaFieldCheckTypes(Long.parseLong(idSchemaField)); if (list.size() > 0) { // Delete existing entries from database schemaFieldsDao.destroySchemFieldCheckTypes(Long.parseLong(idSchemaField)); Set<SchemaFieldCheckTypesEntity> schemaFieldCheckTypeSet = new HashSet<SchemaFieldCheckTypesEntity>(); schemaFieldEntity.setSchemaFieldCheckTypeSet(schemaFieldCheckTypeSet); } } if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignAlphanumeric = request.getParameter("idAlignAlphanumeric"); String fillCharAlphanumeric = request.getParameter("fillCharAlphanumeric"); schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(size); if (idAlignAlphanumeric != null && !idAlignAlphanumeric.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignAlphanumeric)); } else { schemaFieldEntity.setIdAlign(null); } if (fillCharAlphanumeric != null && !fillCharAlphanumeric.equals("")) { schemaFieldEntity.setFillChar(fillCharAlphanumeric); } else { schemaFieldEntity.setFillChar(null); } } else { if (nillableAlphanumeric != null && (nillableAlphanumeric.equals("1") || nillableAlphanumeric.equals("true"))) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } } if (schemaFieldEntity.getIdFieldType() == FieldType.numeric) { if (!minInclusive.equals("")) { schemaFieldEntity.setMinInclusive(Double.parseDouble(minInclusive)); } else { schemaFieldEntity.setMinInclusive(null); } if (!maxInclusive.equals("")) { schemaFieldEntity.setMaxInclusive(Double.parseDouble(maxInclusive)); } else { schemaFieldEntity.setMaxInclusive(null); } if (!fractionDigits.equals("")) { schemaFieldEntity.setFractionDigits(Integer.parseInt(fractionDigits)); } else { schemaFieldEntity.setFractionDigits(null); } if (numericType.equals("1")) { schemaFieldEntity.setIdNumericType(1); } else { schemaFieldEntity.setIdNumericType(2); } schemaFieldEntity.setIsForecastable(Boolean.parseBoolean(isForecastable)); schemaFieldEntity.setForecastSpeed(Integer.parseInt(forecastSpeed)); schemaFieldEntity.setForecastAccuracy(Integer.parseInt(forecastAccuracy)); if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignNumeric = request.getParameter("idAlignNumeric"); String fillCharNumeric = request.getParameter("fillCharNumeric"); schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(size); if (!idAlignNumeric.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignNumeric)); } else { schemaFieldEntity.setIdAlign(null); } if (!fillCharNumeric.equals("")) { schemaFieldEntity.setFillChar(fillCharNumeric); } else { schemaFieldEntity.setFillChar(null); } } else { if (nillableNumeric.equals("1") || nillableNumeric.equals("true")) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } } if (schemaFieldEntity.getIdFieldType() == FieldType.date) { int maxLength = 0; schemaFieldEntity.setIdDateFmtType(Integer.parseInt(idDateTimeType)); if (!idDateType.equals("")) { schemaFieldEntity.setIdDateType(Integer.parseInt(idDateType)); switch (Integer.parseInt(idDateType)) { case DateTimeType.DDMMYY: maxLength = 6; break; case DateTimeType.slashDDMMYY: case DateTimeType.signDDMMYY: case DateTimeType.dotDDMMYY: case DateTimeType.DDMMYYYY: case DateTimeType.YYYYMMDD: maxLength = 8; break; case DateTimeType.slashDDMMYYYY: case DateTimeType.signDDMMYYYY: case DateTimeType.dotDDMMYYYY: case DateTimeType.slashYYYYMMDD: case DateTimeType.signYYYYMMDD: case DateTimeType.dotYYYYMMDD: maxLength = 10; break; } } else { schemaFieldEntity.setIdDateType(null); } if (!idTimeType.equals("")) { schemaFieldEntity.setIdTimeType(Integer.parseInt(idTimeType)); if (maxLength > 0) { maxLength = maxLength + 1; } switch (Integer.parseInt(idTimeType)) { case DateTimeType.dblpnthhmm: case DateTimeType.dothhmm: maxLength = maxLength + 5; break; case DateTimeType.dblpnthhmmss: case DateTimeType.dothhmmss: maxLength = maxLength + 8; break; case DateTimeType.dblpntZhhmmss: case DateTimeType.dotZhhmmss: maxLength = maxLength + 11; break; case DateTimeType.dblpnthmmss: case DateTimeType.dothmmss: maxLength = maxLength + 7; break; } } else { schemaFieldEntity.setIdTimeType(null); } schemaFieldEntity.setMaxLength(maxLength); if (schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { schemaFieldEntity.setNillable(false); schemaFieldEntity.setSize(maxLength + ""); } else { if (nillableDate.equals("1") || nillableDate.equals("true")) { schemaFieldEntity.setNillable(true); } else { schemaFieldEntity.setNillable(false); } } int dateTimeType = schemaFieldEntity.getIdDateTimeType(); if ((dateTimeType == DateTimeType.xsdDateTime || dateTimeType == DateTimeType.xsdDate || dateTimeType == DateTimeType.xsdTime || dateTimeType == DateTimeType.unixTimestamp) && schemaEntity.getIdStreamType() == StreamType.flatFileFixedPosition) { String idAlignDateTime = request.getParameter("idAlignDateTime"); String fillCharDateTime = request.getParameter("fillCharDateTime"); schemaFieldEntity.setSize(size); if (!idAlignDateTime.equals("")) { schemaFieldEntity.setIdAlign(Integer.parseInt(idAlignDateTime)); } else { schemaFieldEntity.setIdAlign(null); } if (!fillCharDateTime.equals("")) { schemaFieldEntity.setFillChar(fillCharDateTime); } else { schemaFieldEntity.setFillChar(null); } } else { schemaFieldEntity.setIdAlign(null); schemaFieldEntity.setFillChar(null); } } Update update = schemaFieldsDao.update(schemaFieldEntity); if (update.isSuccess()) { schemaEntity.setIsActive(0); schemasDao.update(schemaEntity); } if (linkToDb != null && linkToDb.trim().length() > 0 && linkToDb.indexOf(".") == -1) { if (oldLinkToDb == null || oldLinkToDb.trim().length() == 0) { addLinkedTableFields(schemaFieldEntity, linkToDb); } else if (!linkToDb.equals(oldLinkToDb)) { deleteLinkedTableFields(schemaFieldEntity, oldLinkToDb); addLinkedTableFields(schemaFieldEntity, linkToDb); } } if (isLinkedToDbChanged) { update.setExtraMessage("isLinkedToDbChanged"); } ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json"); ServletOutputStream out = response.getOutputStream(); out.write(mapper.writeValueAsBytes(update)); out.flush(); out.close(); return null; }