// postToRestfulApi - // Note: params in the addr field need to be URLEncoded private String postToRestfulApi( String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try { URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { // System.out.println("Exception: " + e.getMessage()); } return result; } // TESTED
public static boolean saveFile( HttpServlet servlet, String contentPath, String path, HttpServletRequest req, HttpServletResponse res) { // @todo Need to use logServerAccess() below here. boolean debugRequest = Debug.isSet("SaveFile"); if (debugRequest) log.debug(" saveFile(): path= " + path); String filename = contentPath + path; // absolute path File want = new File(filename); // backup current version if it exists int version = getBackupVersion(want.getParent(), want.getName()); String fileSave = filename + "~" + version; File file = new File(filename); if (file.exists()) { try { IO.copyFile(filename, fileSave); } catch (IOException e) { log.error( "saveFile(): Unable to save copy of file " + filename + " to " + fileSave + "\n" + e.getMessage()); return false; } } // save new file try { OutputStream out = new BufferedOutputStream(new FileOutputStream(filename)); IO.copy(req.getInputStream(), out); out.close(); if (debugRequest) log.debug("saveFile(): ok= " + filename); res.setStatus(HttpServletResponse.SC_CREATED); log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1)); return true; } catch (IOException e) { log.error( "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage()); return false; } }
@Override public void write(byte[] b) throws IOException { synchronized (statusLock) { // Make sure HTTP status and header is specified. statusLock.notifyAll(); committed = true; } target.write(b); }
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(); } } }
@Override public void flush() throws IOException { synchronized (statusLock) { // Make sure HTTP status and header is specified. statusLock.notifyAll(); } byte[] b = Arrays.copyOf(buffer, offset); target.write(b); offset = 0; }
/** * This method must be invoked at the end of processing. The streams are closed and their content * is analyzed. Actual XSLT processing takes place here. */ @SuppressWarnings("unchecked") void finishResponse() throws IOException { if (writer != null) { writer.close(); } else { if (stream != null) stream.close(); } /* * If we're not in passthrough mode, then we need to finalize XSLT transformation. */ if (false == passthrough) { if (stream != null) { final byte[] bytes = ((DeferredOutputStream) stream).getBytes(); final boolean processingSuppressed = (origRequest.getAttribute(XSLTFilterConstants.NO_XSLT_PROCESSING) != null) | (origRequest.getParameter(XSLTFilterConstants.NO_XSLT_PROCESSING) != null); if (processingSuppressed) { // Just copy the buffered data to the output directly. final OutputStream os = origResponse.getOutputStream(); os.write(bytes); os.close(); } else { // Otherwise apply XSLT transformation to it. try { processWithXslt( bytes, (Map<String, Object>) origRequest.getAttribute(XSLTFilterConstants.XSLT_PARAMS_MAP), origResponse); } catch (TransformerException e) { final Throwable t = unwrapCause(e); if (t instanceof IOException) { throw (IOException) t; } filterError("Error applying stylesheet.", e); } } } } }
public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) { StringBuffer bodyContent = null; OutputStream out = null; PrintWriter writer = null; String serviceKey = null; try { BufferedReader in = req.getReader(); String line = null; while ((line = in.readLine()) != null) { if (bodyContent == null) bodyContent = new StringBuffer(); bodyContent.append(line); } } catch (Exception e) { } try { if (requireSession) { // check to see if there was a session created for this request // if not assume it was from another domain and blow up // Wrap this to prevent Portlet exeptions HttpSession session = req.getSession(false); if (session == null) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } serviceKey = req.getParameter("id"); // only to preven regressions - Remove before 1.0 if (serviceKey == null) serviceKey = req.getParameter("key"); // check if the services have been loaded or if they need to be reloaded if (services == null || configUpdated()) { getServices(res); } String urlString = null; String xslURLString = null; String userName = null; String password = null; String format = "json"; String callback = req.getParameter("callback"); String urlParams = req.getParameter("urlparams"); String countString = req.getParameter("count"); // encode the url to prevent spaces from being passed along if (urlParams != null) { urlParams = urlParams.replace(' ', '+'); } try { if (services.has(serviceKey)) { JSONObject service = services.getJSONObject(serviceKey); // default to the service default if no url parameters are specified if (urlParams == null && service.has("defaultURLParams")) { urlParams = service.getString("defaultURLParams"); } String serviceURL = service.getString("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } String apikey = ""; if (service.has("username")) userName = service.getString("username"); if (service.has("password")) password = service.getString("password"); if (service.has("apikey")) apikey = service.getString("apikey"); urlString = serviceURL + apikey; if (urlParams != null) urlString += "&" + urlParams; if (service.has("xslStyleSheet")) { xslURLString = service.getString("xslStyleSheet"); } } // code for passing the url directly through instead of using configuration file else if (req.getParameter("url") != null) { String serviceURL = req.getParameter("url"); // build the URL if (urlParams != null && serviceURL.indexOf("?") == -1) { serviceURL += "?"; } else if (urlParams != null) { serviceURL += "&"; } urlString = serviceURL; if (urlParams != null) urlString += urlParams; } else { writer = res.getWriter(); if (serviceKey == null) writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required."); else writer.write( "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not found."); writer.flush(); return; } } catch (Exception ex) { getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex); } Map paramsMap = new HashMap(); paramsMap.put("format", format); // do not allow for xdomain unless the context level setting is enabled. if (callback != null && allowXDomain) { paramsMap.put("callback", callback); } if (countString != null) { paramsMap.put("count", countString); } InputStream xslInputStream = null; if (urlString == null) { writer = res.getWriter(); writer.write( "XmlHttpProxyServlet parameters: id[Required] urlparams[Optional] format[Optional] callback[Optional]"); writer.flush(); return; } // default to JSON res.setContentType(responseContentType); out = res.getOutputStream(); // get the stream for the xsl stylesheet if (xslURLString != null) { // check the web root for the resource URL xslURL = null; xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString); // if not in the web root check the classpath if (xslURL == null) { xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString); } if (xslURL != null) { xslInputStream = xslURL.openStream(); } else { String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey + ". Please check the XMLHttpProxy configuration."; getLogger().severe(message); try { out.write(message.getBytes()); out.flush(); return; } catch (java.io.IOException iox) { } } } if (!isPost) { xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password); } else { if (bodyContent == null) getLogger() .info( "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content"); xhp.doPost( urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(), userName, password); } } catch (Exception iox) { iox.printStackTrace(); getLogger().severe("XmlHttpProxyServlet: caught " + iox); try { writer = res.getWriter(); writer.write(iox.toString()); writer.flush(); } catch (java.io.IOException ix) { ix.printStackTrace(); } return; } finally { try { if (out != null) out.close(); if (writer != null) writer.close(); } catch (java.io.IOException iox) { } } }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // create the workbook, its worksheet, and its title row Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("User table"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("The User table"); // create the header row row = sheet.createRow(2); row.createCell(0).setCellValue("UserID"); row.createCell(1).setCellValue("LastName"); row.createCell(2).setCellValue("FirstName"); row.createCell(3).setCellValue("Email"); try { // read database rows ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM User ORDER BY UserID"; ResultSet results = statement.executeQuery(query); // create spreadsheet rows int i = 3; while (results.next()) { row = sheet.createRow(i); row.createCell(0).setCellValue(results.getInt("UserID")); row.createCell(1).setCellValue(results.getString("LastName")); row.createCell(2).setCellValue(results.getString("FirstName")); row.createCell(3).setCellValue(results.getString("Email")); i++; } results.close(); statement.close(); connection.close(); } catch (SQLException e) { this.log(e.toString()); } // set response object headers response.setHeader("content-disposition", "attachment; filename=users.xls"); response.setHeader("cache-control", "no-cache"); // get the output stream String encodingString = request.getHeader("accept-encoding"); OutputStream out; if (encodingString != null && encodingString.contains("gzip")) { out = new GZIPOutputStream(response.getOutputStream()); response.setHeader("content-encoding", "gzip"); // System.out.println("User table encoded with gzip"); } else { out = response.getOutputStream(); // System.out.println("User table not encoded with gzip"); } // send the workbook to the browser workbook.write(out); out.close(); }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String retval = "<html> <H4>"; try { // Create a message factory. MessageFactory mf = MessageFactory.newInstance(); // Create a message from the message factory. SOAPMessage msg = mf.createMessage(); // Message creation takes care of creating the SOAPPart - a // required part of the message as per the SOAP 1.1 // specification. SOAPPart sp = msg.getSOAPPart(); // Retrieve the envelope from the soap part to start building // the soap message. SOAPEnvelope envelope = sp.getEnvelope(); // Create a soap header from the envelope. SOAPHeader hdr = envelope.getHeader(); // Create a soap body from the envelope. SOAPBody bdy = envelope.getBody(); // Add a soap body element to the soap body SOAPBodyElement gltp = bdy.addBodyElement( envelope.createName("GetLastTradePrice", "ztrade", "http://wombat.ztrade.com")); gltp.addChildElement(envelope.createName("symbol", "ztrade", "http://wombat.ztrade.com")) .addTextNode("SUNW"); StringBuffer urlSB = new StringBuffer(); urlSB.append(req.getScheme()).append("://").append(req.getServerName()); urlSB.append(":").append(req.getServerPort()).append(req.getContextPath()); String reqBase = urlSB.toString(); if (data == null) { data = reqBase + "/index.html"; } // Want to set an attachment from the following url. // Get context URL url = new URL(data); AttachmentPart ap = msg.createAttachmentPart(new DataHandler(url)); ap.setContentType("text/html"); // Add the attachment part to the message. msg.addAttachmentPart(ap); // Create an endpoint for the recipient of the message. if (to == null) { to = reqBase + "/receiver"; } URL urlEndpoint = new URL(to); System.err.println("Sending message to URL: " + urlEndpoint); System.err.println("Sent message is logged in \"sent.msg\""); retval += " Sent message (check \"sent.msg\") and "; FileOutputStream sentFile = new FileOutputStream("sent.msg"); msg.writeTo(sentFile); sentFile.close(); // Send the message to the provider using the connection. SOAPMessage reply = con.call(msg, urlEndpoint); if (reply != null) { FileOutputStream replyFile = new FileOutputStream("reply.msg"); reply.writeTo(replyFile); replyFile.close(); System.err.println("Reply logged in \"reply.msg\""); retval += " received reply (check \"reply.msg\").</H4> </html>"; } else { System.err.println("No reply"); retval += " no reply was received. </H4> </html>"; } } catch (Throwable e) { e.printStackTrace(); logger.severe("Error in constructing or sending message " + e.getMessage()); retval += " There was an error " + "in constructing or sending message. </H4> </html>"; } try { OutputStream os = resp.getOutputStream(); os.write(retval.getBytes()); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); logger.severe("Error in outputting servlet response " + e.getMessage()); } }
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(); } }
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 File generateJarDiff( ResourceCatalog catalog, DownloadRequest dreq, JnlpResource res, boolean doJarDiffWorkAround) { boolean del_old = false; boolean del_new = false; // Lookup up file for request version DownloadRequest fromDreq = dreq.getFromDownloadRequest(); try { JnlpResource fromRes = catalog.lookupResource(fromDreq); /* Get file locations */ String newFilePath = _servletContext.getRealPath(res.getPath()); String oldFilePath = _servletContext.getRealPath(fromRes.getPath()); // fix for 4720897 if (newFilePath == null) { newFilePath = getRealPath(res.getPath()); if (newFilePath != null) del_new = true; } if (oldFilePath == null) { oldFilePath = getRealPath(fromRes.getPath()); if (oldFilePath != null) del_old = true; } if (newFilePath == null || oldFilePath == null) { return null; } // Create temp. file to store JarDiff file in File tempDir = (File) _servletContext.getAttribute("javax.servlet.context.tempdir"); // fix for 4653036: JarDiffHandler() should use javax.servlet.context.tempdir to store the // jardiff File outputFile = File.createTempFile("jnlp", ".jardiff", tempDir); _log.addDebug( "Generating Jardiff between " + oldFilePath + " and " + newFilePath + " Store in " + outputFile); // Generate JarDiff OutputStream os = new FileOutputStream(outputFile); JarDiff.createPatch(oldFilePath, newFilePath, os, !doJarDiffWorkAround); os.close(); try { // Check that Jardiff is smaller, or return null if (outputFile.length() >= (new File(newFilePath).length())) { _log.addDebug("JarDiff discarded - since it is bigger"); return null; } // Check that Jardiff is smaller than the packed version of // the new file, if the file exists at all File newFilePacked = new File(newFilePath + ".pack.gz"); if (newFilePacked.exists()) { _log.addDebug("generated jardiff size: " + outputFile.length()); _log.addDebug("packed requesting file size: " + newFilePacked.length()); if (outputFile.length() >= newFilePacked.length()) { _log.addDebug("JarDiff discarded - packed version of requesting file is smaller"); return null; } } _log.addDebug("JarDiff generation succeeded"); return outputFile; } finally { // delete the temporarily downloaded file if (del_new) { new File(newFilePath).delete(); } if (del_old) { new File(oldFilePath).delete(); } } } catch (IOException ioe) { _log.addDebug("Failed to genereate jardiff", ioe); return null; } catch (ErrorResponseException ere) { _log.addDebug("Failed to genereate jardiff", ere); return null; } }
@Override public void close() throws IOException { offset = 0; target.close(); super.close(); }
private static void sendBinaryResponse(HttpServletResponse res, byte[] bytes) throws IOException { res.setContentType("application/binary-encoded"); OutputStream out = res.getOutputStream(); // care to handle errors later? out.write(bytes); out.flush(); }