protected Object exec(Object[] args, Context context) { int nargs = args.length; if (nargs != 1 && nargs != 2) { undefined(args, context); return null; } HttpServletRequest request = (HttpServletRequest) args[0]; String enc; if (nargs == 1) { enc = ServletEncoding.getDefaultInputEncoding(context); } else { enc = (String) args[1]; } String contentType = request.getContentType(); if (contentType != null && contentType.startsWith("multipart/form-data")) { throw new RuntimeException("not yet implemented"); } else { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[512]; int n; InputStream in = request.getInputStream(); while ((n = in.read(buf, 0, buf.length)) != -1) { bout.write(buf, 0, n); } in.close(); String qs = new String(bout.toByteArray()); Map map = URLEncoding.parseQueryString(qs, enc); return new ServletParameter(map); } catch (IOException e) { throw new PnutsException(e, context); } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doPost(request, response); try { if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } ServletFileUpload sfU = new ServletFileUpload(); FileItemIterator items = sfU.getItemIterator(request); while (items.hasNext()) { FileItemStream item = items.next(); if (!item.isFormField()) { InputStream stream = item.openStream(); Document doc = editor.toDocument(stream); stream.close(); handleDocument(request, response, doc); return; } } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded"); } catch (FileUploadException fuE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage()); } catch (JDOMException jE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage()); } }
private static synchronized String getJavascript() { if (jstext == null) { InputStream istr = null; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE); jstext = StringUtil.fromInputStream(istr); istr.close(); } catch (Exception e) { log.error("Can't load javascript", e); } finally { IOUtil.safeClose(istr); } } return jstext; }
public static void main(String args[]) throws IOException { // Function References String path = "http://motherlode.ucar.edu:8081/thredds/radarServer/nexrad/level3/IDD/dataset.xml"; try { catURI = new URI(StringUtil2.escape(path, "/:-_.")); } catch (URISyntaxException e) { System.out.println("radarServer main: URISyntaxException=" + e.getMessage()); return; } // read the catalog System.out.println("radarServer main: full path=" + path); InputStream ios = null; try { URL url = new URL(path); ios = url.openStream(); // ios = new FileInputStream(path); // acat = factory.readXML(ios, catURI ); BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios)); while (true) { String line = dataIS.readLine(); if (line == null) break; System.out.println(line); } } catch (Throwable t) { System.out.println("radarServer main: Exception on catalog=" + path + " " + t.getMessage()); return; } finally { if (ios != null) { try { ios.close(); } catch (IOException e) { System.out.println("radarServer main: error closing" + path); } } } return; }
/** * return OutputStream of JasperReport object, this page could only be viewed from localhost for * security concern. parameter can be (id), or (table and type) * * @param id - report id, or * @param table - table name * @param type - reporttype "s","l","o", case insensitive * @param client(*) - client domain * @param version - version number, default to -1 */ public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String clientName = request.getParameter("client"); int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1); if (objectId == -1) { // try using table and type objectId = getReportId(clientName, request.getParameter("table"), request.getParameter("type")); } if (objectId == -1) { logger.error("report not found, request is:" + Tools.toString(request)); throw new NDSException("report not found"); } int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1); File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName)); if (reportXMLFile.exists()) { // generate jasperreport if file not exists or not newer String reportName = reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf(".")); File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper"); if (!reportJasperFile.exists() || reportJasperFile.lastModified() < reportXMLFile.lastModified()) { JasperCompileManager.compileReportToFile( reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath()); } InputStream is = new FileInputStream(reportJasperFile); response.setContentType("application/octetstream;"); response.setContentLength((int) reportJasperFile.length()); // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\""); ServletOutputStream os = response.getOutputStream(); byte[] b = new byte[8192]; int bInt; while ((bInt = is.read(b, 0, b.length)) != -1) { os.write(b, 0, bInt); } is.close(); os.flush(); os.close(); } else { throw new NDSException("Not found report template"); } }
public void download(HttpServletResponse response, String filename) throws IOException { StringTokenizer tokenTO = new StringTokenizer(filename, "\\"); int j = 0; String[] filepath1 = new String[10]; while (tokenTO.hasMoreTokens()) { filepath1[j] = tokenTO.nextToken(); j++; } String filepath = ""; for (int m = 0; m < j - 1; m++) { filepath = filepath + filepath1[m] + "\\"; } filepath = filepath + filepath1[j - 1]; File down_file = new java.io.File(filepath); long l = down_file.length(); // 文件长度 InputStream in = new FileInputStream(down_file); if (in != null) { try { String fs = down_file.getName(); response.reset(); response.setContentType(null); // String s = "attachment; filename=" + fs; // response.setHeader("Content-Disposition", s); // 以上输出文件元信息 OutputStream output = null; FileInputStream fis = null; output = response.getOutputStream(); fis = new FileInputStream(filepath); response.setContentLength((int) l); byte[] b = new byte[2048]; int i = 0; while ((i = fis.read(b)) > 0) { output.write(b, 0, i); } output.flush(); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Variable initializations. HttpSession session = request.getSession(); FileItem image_file = null; int record_id = 0; int image_id; // Check if a record ID has been entered. if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) { // If no ID has been entered, send message to jsp. response_message = "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("UploadImage.jsp"); } try { // Parse the HTTP request to get the image stream. DiskFileUpload fu = new DiskFileUpload(); // Will get multiple image files if that happens and can be accessed through FileItems. List<FileItem> FileItems = fu.parseRequest(request); // Connect to the database and create a statement. conn = getConnected(drivername, dbstring, username, password); stmt = conn.createStatement(); // Process the uploaded items, assuming only 1 image file uploaded. Iterator<FileItem> i = FileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); // Test if item is a form field and matches recordID. if (item.isFormField()) { if (item.getFieldName().equals("recordID")) { // Covert record id from string to integer. record_id = Integer.parseInt(item.getString()); String sql = "select count(*) from radiology_record where record_id = " + record_id; int count = 0; try { rset = stmt.executeQuery(sql); while (rset != null && rset.next()) { count = (rset.getInt(1)); } } catch (SQLException e) { response_message = e.getMessage(); } // Check if recordID is in the database. if (count == 0) { // Invalid recordID, send message to jsp. response_message = "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } else { image_file = item; if (image_file.getName().equals("")) { // No file, send message to jsp. response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } // Get the image stream. InputStream instream = image_file.getInputStream(); BufferedImage full_image = ImageIO.read(instream); BufferedImage thumbnail = shrink(full_image, 10); BufferedImage regular_image = shrink(full_image, 5); // First, to generate a unique img_id using an SQL sequence. rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual"); rset1.next(); image_id = rset1.getInt(1); // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty blob. stmt.execute( "INSERT INTO pacs_images VALUES(" + record_id + "," + image_id + ", empty_blob(), empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE"; rset = stmt.executeQuery(cmd); rset.next(); BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5); BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3); BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4); // Write the full size image to the blob object. OutputStream fullOutstream = myblobFull.getBinaryOutputStream(); ImageIO.write(full_image, "jpg", fullOutstream); // Write the thumbnail size image to the blob object. OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream(); ImageIO.write(thumbnail, "jpg", thumbOutstream); // Write the regular size image to the blob object. OutputStream regularOutstream = myblobRegular.getBinaryOutputStream(); ImageIO.write(regular_image, "jpg", regularOutstream); // Commit the changes to database. stmt.executeUpdate("commit"); response_message = "<p><font color=00CC00>Upload Successful.</font></p>"; session.setAttribute("msg", response_message); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); } catch (Exception ex) { response_message = ex.getMessage(); } }
package com.jspsmart.upload;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set the response Shepherd myShepherd = new Shepherd(); Vector rEncounters = new Vector(); // setup data dir String rootWebappPath = getServletContext().getRealPath("/"); File webappsDir = new File(rootWebappPath).getParentFile(); File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName()); // if(!shepherdDataDir.exists()){shepherdDataDir.mkdir();} File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters"); // if(!encountersDir.exists()){encountersDir.mkdir();} // set up the files String gisFilename = "geneGIS_export_" + request.getRemoteUser() + ".csv"; File gisFile = new File(encountersDir.getAbsolutePath() + "/" + gisFilename); myShepherd.beginDBTransaction(); try { // set up the output stream FileOutputStream fos = new FileOutputStream(gisFile); OutputStreamWriter outp = new OutputStreamWriter(fos); try { EncounterQueryResult queryResult = EncounterQueryProcessor.processQuery( myShepherd, request, "year descending, month descending, day descending"); rEncounters = queryResult.getResult(); int numMatchingEncounters = rEncounters.size(); // build the CSV file header StringBuffer locusString = new StringBuffer(""); int numLoci = 2; // most covered species will be loci try { numLoci = (new Integer(CommonConfiguration.getProperty("numLoci"))).intValue(); } catch (Exception e) { System.out.println("numPloids configuration value did not resolve to an integer."); e.printStackTrace(); } for (int j = 0; j < numLoci; j++) { locusString.append(",Locus" + (j + 1) + " A1,Locus" + (j + 1) + " A2"); } // out.println("<html><body>"); // out.println("Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub // Area,Sex,Haplotype"+locusString.toString()); outp.write( "Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub Area,Sex,Haplotype" + locusString.toString() + "\n"); for (int i = 0; i < numMatchingEncounters; i++) { Encounter enc = (Encounter) rEncounters.get(i); String assembledString = ""; if (enc.getIndividualID() != null) { assembledString += enc.getIndividualID(); } if (enc.getAlternateID() != null) { assembledString += "," + enc.getAlternateID(); } else { assembledString += ","; } String dateString = ","; if (enc.getYear() > 0) { dateString += enc.getYear(); if (enc.getMonth() > 0) { dateString += ("-" + enc.getMonth()); if (enc.getDay() > 0) { dateString += ("-" + enc.getDay()); } } } assembledString += dateString; String timeString = ","; if (enc.getHour() > -1) { timeString += enc.getHour() + ":" + enc.getMinutes(); } assembledString += timeString; if ((enc.getDecimalLatitude() != null) && (enc.getDecimalLongitude() != null)) { assembledString += "," + enc.getDecimalLatitude(); assembledString += "," + enc.getDecimalLongitude(); } else { assembledString += ",,"; } assembledString += "," + enc.getVerbatimLocality(); assembledString += "," + enc.getLocationID(); assembledString += "," + enc.getSex(); // find and print the haplotype String haplotypeString = ","; if (enc.getHaplotype() != null) { haplotypeString += enc.getHaplotype(); } // find and print the ms markers String msMarkerString = ""; List<TissueSample> samples = enc.getTissueSamples(); int numSamples = samples.size(); boolean foundMsMarkers = false; for (int k = 0; k < numSamples; k++) { if (!foundMsMarkers) { TissueSample t = samples.get(k); List<GeneticAnalysis> analyses = t.getGeneticAnalyses(); int aSize = analyses.size(); for (int l = 0; l < aSize; l++) { GeneticAnalysis ga = analyses.get(l); if (ga.getAnalysisType().equals("MicrosatelliteMarkers")) { foundMsMarkers = true; MicrosatelliteMarkersAnalysis ga2 = (MicrosatelliteMarkersAnalysis) ga; List<Locus> loci = ga2.getLoci(); int localLoci = loci.size(); for (int m = 0; m < localLoci; m++) { Locus locus = loci.get(m); if (locus.getAllele0() != null) { msMarkerString += "," + locus.getAllele0(); } else { msMarkerString += ","; } if (locus.getAllele1() != null) { msMarkerString += "," + locus.getAllele1(); } else { msMarkerString += ","; } } } } } } // out.println("<p>"+assembledString+haplotypeString+msMarkerString+"</p>"); outp.write(assembledString + haplotypeString + msMarkerString + "\n"); } outp.close(); outp = null; // now write out the file response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment;filename=" + gisFilename); ServletContext ctx = getServletContext(); // InputStream is = ctx.getResourceAsStream("/encounters/"+gisFilename); InputStream is = new FileInputStream(gisFile); int read = 0; byte[] bytes = new byte[BYTES_DOWNLOAD]; OutputStream os = response.getOutputStream(); while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } os.flush(); os.close(); } catch (Exception ioe) { ioe.printStackTrace(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(ServletUtilities.getHeader(request)); out.println( "<html><body><p><strong>Error encountered</strong> with file writing. Check the relevant log.</p>"); out.println( "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>"); out.println(ServletUtilities.getFooter()); out.close(); outp.close(); outp = null; } } catch (Exception e) { e.printStackTrace(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(ServletUtilities.getHeader(request)); out.println("<html><body><p><strong>Error encountered</strong></p>"); out.println( "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>"); out.println(ServletUtilities.getFooter()); out.close(); } myShepherd.rollbackDBTransaction(); myShepherd.closeDBTransaction(); }
private void datasetInfoHtml( RadarType radarType, String pathInfo, PrintWriter pw, HttpServletResponse res) throws IOException { pathInfo = pathInfo.replace("/dataset.html", ""); pathInfo = pathInfo.replace("/catalog.html", ""); Element root = new Element("RadarNexrad"); Document doc = new Document(root); if (pathInfo.startsWith("/")) pathInfo = pathInfo.substring(1); for (int i = 0; i < datasets.size(); i++) { InvDatasetScan ds = (InvDatasetScan) datasets.get(i); if (!(pathInfo.equals(ds.getPath()))) { continue; } // at this point a valid dataset // fix the location root.setAttribute("location", "/thredds/radarServer/" + ds.getPath()); // spatial range ThreddsMetadata.GeospatialCoverage gc = ds.getGeospatialCoverage(); LatLonRect bb = new LatLonRect(); gc.setBoundingBox(bb); String north = Double.toString(gc.getLatNorth()); String south = Double.toString(gc.getLatSouth()); String east = Double.toString(gc.getLonEast()); String west = Double.toString(gc.getLonWest()); Element LatLonBox = new Element("LatLonBox"); LatLonBox.addContent(new Element("north").addContent(north)); LatLonBox.addContent(new Element("south").addContent(south)); LatLonBox.addContent(new Element("east").addContent(east)); LatLonBox.addContent(new Element("west").addContent(west)); root.addContent(LatLonBox); // get the time range Element timeSpan = new Element("TimeSpan"); CalendarDateRange dr = ds.getCalendarDateCoverage(); timeSpan.addContent(new Element("begin").addContent(dr.getStart().toString())); timeSpan.addContent(new Element("end").addContent(dr.getEnd().toString())); root.addContent(timeSpan); ThreddsMetadata.Variables cvs = (ThreddsMetadata.Variables) ds.getVariables().get(0); List vl = cvs.getVariableList(); for (int j = 0; j < vl.size(); j++) { ThreddsMetadata.Variable v = (ThreddsMetadata.Variable) vl.get(j); Element variable = new Element("variable"); variable.setAttribute("name", v.getName()); root.addContent(variable); } // add pointer to the station list XML /* Element stnList = new Element("stationList"); stnList.setAttribute("title", "Available Stations", XMLEntityResolver.xlinkNS); stnList.setAttribute("href", "/thredds/radarServer/"+ pathInfo +"/stations.xml", XMLEntityResolver.xlinkNS); root.addContent(stnList); */ // String[] stations = rns.stationsDS( dataLocation.get( ds.getPath() )); // rns.printStations( stations ); // add accept list Element a = new Element("AcceptList"); a.addContent(new Element("accept").addContent("xml")); a.addContent(new Element("accept").addContent("html")); root.addContent(a); } ServerMethods sm = new ServerMethods(log); InputStream xslt = sm.getInputStream(contentPath + getPath() + "radar.xsl", RadarServer.class); try { // what's wrong here xslt = getXSLT( "radar.xsl" ); XSLTransformer transformer = new XSLTransformer(xslt); Document html = transformer.transform(doc); XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); String infoString = fmt.outputString(html); res.setContentType("text/html; charset=iso-8859-1"); pw = res.getWriter(); pw.println(infoString); pw.flush(); } catch (Exception e) { log.error("radarServer reading " + contentPath + getPath() + "radar.xsl"); log.error("radarServer XSLTransformer problem for web form ", e); } finally { if (xslt != null) { try { xslt.close(); } catch (IOException e) { log.error("radarServer radar.xsl: error closing" + contentPath + getPath() + "radar.xsl"); } } } return; }