private void level2level3catalog( RadarType radarType, String pathInfo, PrintWriter pw, HttpServletRequest req, HttpServletResponse res) throws IOException { try { String type; if (pathInfo.contains("level2")) type = radarType.toString() + "/level2"; else type = radarType.toString() + "/level3"; ByteArrayOutputStream os = new ByteArrayOutputStream(10000); InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); factory.writeXML(cat, os, true); InvCatalogImpl tCat = factory.readXML(new ByteArrayInputStream(os.toByteArray()), catURI); Iterator parents = tCat.getDatasets().iterator(); while (parents.hasNext()) { ArrayList<InvDatasetImpl> delete = new ArrayList<InvDatasetImpl>(); InvDatasetImpl top = (InvDatasetImpl) parents.next(); Iterator tDatasets = top.getDatasets().iterator(); while (tDatasets.hasNext()) { InvDatasetImpl ds = (InvDatasetImpl) tDatasets.next(); if (ds instanceof InvDatasetScan) { InvDatasetScan ids = (InvDatasetScan) ds; if (ids.getPath() == null) continue; if (ids.getPath().contains(type)) { ids.setXlinkHref(ids.getPath() + "/dataset.xml"); } else { delete.add(ds); } } } // remove datasets for (InvDatasetImpl idi : delete) { top.removeDataset(idi); } } if (pathInfo.endsWith("xml")) { String catAsString = factory.writeXML(tCat); pw.println(catAsString); pw.flush(); } else { HtmlWriter.getInstance().writeCatalog(req, res, tCat, true); // show catalog as HTML } } catch (Throwable e) { log.error("RadarServer.level2level3catalog failed", e); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return; }
/** * ************************************************************************ Sends an error to the * client. * * @param t The exception that caused the problem. * @param res The <code>HttpServletResponse</code> for the client. */ public static void handleException(Throwable t, HttpServletResponse res) { try { String message = t.getMessage(); if (message == null) message = "NULL message " + t.getClass().getName(); if (Debug.isSet("trustedMode")) { // security issue: only show stack if trusted ByteArrayOutputStream bs = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bs); t.printStackTrace(ps); message = new String(bs.toByteArray()); } log.info( UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_BAD_REQUEST, message.length())); log.error("handleException", t); t.printStackTrace(); // debugging - log.error not showing stack trace !! if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_BAD_REQUEST, message); } catch (Throwable e) { log.error("handleException() had problem reporting Exception", e); t.printStackTrace(); } }
/** * Write a file to the response stream. Handles Range requests. * * @param req request * @param res response * @param file must exists and not be a directory * @param contentType must not be null * @throws IOException or error */ public static void returnFile( HttpServletRequest req, HttpServletResponse res, File file, String contentType) throws IOException { res.setContentType(contentType); // see if its a Range Request boolean isRangeRequest = false; long startPos = 0, endPos = Long.MAX_VALUE; String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // bytes=12-34 or bytes=12- int pos = rangeRequest.indexOf("="); if (pos > 0) { int pos2 = rangeRequest.indexOf("-"); if (pos2 > 0) { String startString = rangeRequest.substring(pos + 1, pos2); String endString = rangeRequest.substring(pos2 + 1); startPos = Long.parseLong(startString); if (endString.length() > 0) endPos = Long.parseLong(endString) + 1; isRangeRequest = true; } } } // set content length long fileSize = file.length(); long contentLength = fileSize; if (isRangeRequest) { endPos = Math.min(endPos, fileSize); contentLength = endPos - startPos; } if (contentLength > Integer.MAX_VALUE) res.addHeader( "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT else res.setContentLength((int) contentLength); // note HEAD only allows this String filename = file.getPath(); boolean debugRequest = Debug.isSet("returnFile"); if (debugRequest) log.debug( "returnFile(): filename = " + filename + " contentType = " + contentType + " contentLength = " + contentLength); // indicate we allow Range Requests res.addHeader("Accept-Ranges", "bytes"); if (req.getMethod().equals("HEAD")) { log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0)); return; } try { if (isRangeRequest) { // set before content is sent res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize); res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); FileCacheRaf.Raf craf = null; try { craf = fileCacheRaf.acquire(filename); IO.copyRafB( craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_PARTIAL_CONTENT, contentLength)); return; } finally { if (craf != null) fileCacheRaf.release(craf); } } // Return the file ServletOutputStream out = res.getOutputStream(); IO.copyFileB(file, out, 60000); res.flushBuffer(); out.close(); if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength)); } // @todo Split up this exception handling: those from file access vs those from dealing with // response // File access: catch and res.sendError() // response: don't catch (let bubble up out of doGet() etc) catch (FileNotFoundException e) { log.error("returnFile(): FileNotFoundException= " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (java.net.SocketException e) { log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage()); log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); } catch (IOException e) { String eName = e.getClass().getName(); // dont want compile time dependency on ClientAbortException if (eName.equals("org.apache.catalina.connector.ClientAbortException")) { log.info( "returnFile(): ClientAbortException while sending file: " + filename + " " + e.getMessage()); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); return; } log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e); log.error( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage()); } }
/** * Send a permanent redirect (HTTP status 301 "Moved Permanently") response with the given target * path. * * <p>The given target path may be relative or absolute. If it is relative, it will be resolved * against the request URL. * * @param targetPath the path to which the client is redirected. * @param req the HttpServletRequest * @param res the HttpServletResponse * @throws IOException if can't write the response. */ public static void sendPermanentRedirect( String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException { // Absolute URL needed so resolve the target path against the request URL. URI uri; try { uri = new URI(req.getRequestURL().toString()); } catch (URISyntaxException e) { log.error( "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e); log.info( "sendPermanentRedirect(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String absolutePath = uri.resolve(targetPath).toString(); absolutePath = res.encodeRedirectURL(absolutePath); res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); res.addHeader("Location", absolutePath); String title = "Permanently Moved - 301"; String body = new StringBuilder() .append("<p>") .append("The requested URL <") .append(req.getRequestURL()) .append("> has been permanently moved (HTTP status code 301).") .append(" Instead, please use the following URL: <a href=\"") .append(absolutePath) .append("\">") .append(absolutePath) .append("</a>.") .append("</p>") .toString(); String htmlResp = new StringBuilder() .append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag()) .append("<head><title>") .append(title) .append("</title></head><body>") .append("<h1>") .append(title) .append("</h1>") .append(body) .append("</body></html>") .toString(); log.info("sendPermanentRedirect(): redirect to " + absolutePath); log.info( "sendPermanentRedirect(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length())); // Write the catalog out. PrintWriter out = res.getWriter(); res.setContentType("text/html"); out.print(htmlResp); out.flush(); }
// The tck uses only get & post requests protected void processTCKReq(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.entering(LOG_CLASS, "servlet entry"); PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request"); PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response"); PortletConfig portletConfig = (PortletConfig) request.getAttribute("javax.portlet.config"); long svtTid = Thread.currentThread().getId(); long reqTid = (Long) portletReq.getAttribute(THREADID_ATTR); PrintWriter writer = ((MimeResponse) portletResp).getWriter(); JSR286DispatcherReqRespTestCaseDetails tcd = new JSR286DispatcherReqRespTestCaseDetails(); // Create result objects for the tests /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_containsHeader */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.containsHeader must return false" */ TestResult tr0 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_CONTAINSHEADER); try { boolean ok = response.containsHeader("Accept"); tr0.setTcSuccess(ok == false); } catch (Exception e) { tr0.appendTcDetail(e.toString()); } tr0.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectURL1 */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeRedirectURL must return null" */ TestResult tr1 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL1); try { String isval = response.encodeRedirectURL("http://www.cnn.com/"); CompareUtils.stringsEqual(isval, null, tr1); } catch (Exception e) { tr1.appendTcDetail(e.toString()); } tr1.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectUrl */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeRedirectUrl must return null" */ TestResult tr2 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL); try { String isval = response.encodeRedirectUrl("http://www.cnn.com/"); CompareUtils.stringsEqual(isval, null, tr2); } catch (Exception e) { tr2.appendTcDetail(e.toString()); } tr2.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeURL1 */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeURL must provide the same */ /* functionality as ResourceResponse.encodeURL" */ TestResult tr3 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL1); try { String turl = "http://www.apache.org/"; String hval = (String) response.encodeURL(turl); String pval = (String) portletResp.encodeURL(turl); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr3); } catch (Exception e) { tr3.appendTcDetail(e.toString()); } tr3.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeUrl */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.encodeUrl must provide the same */ /* functionality as ResourceResponse.encodeURL" */ TestResult tr4 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL); try { String turl = "http://www.apache.org/"; String hval = (String) response.encodeUrl(turl); String pval = (String) portletResp.encodeURL(turl); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr4); } catch (Exception e) { tr4.appendTcDetail(e.toString()); } tr4.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getBufferSize */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getBufferSize must provide the same */ /* functionality as ResourceResponse.getBufferSize" */ TestResult tr5 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETBUFFERSIZE); try { int hval = response.getBufferSize(); int pval = ((ResourceResponse) portletResp).getBufferSize(); String str = "Value " + hval + " from " + "HttpServletResponse" + " does not equal value " + pval + " + ResourceResponse"; if (hval != pval) { tr5.appendTcDetail(str); } tr5.setTcSuccess(hval == pval); } catch (Exception e) { tr5.appendTcDetail(e.toString()); } tr5.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getCharacterEncoding */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getCharacterEncoding must provide */ /* the same functionality as ResourceResponse.getCharacterEncoding" */ TestResult tr6 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCHARACTERENCODING); try { String hval = response.getCharacterEncoding(); String pval = ((ResourceResponse) portletResp).getCharacterEncoding(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr6); } catch (Exception e) { tr6.appendTcDetail(e.toString()); } tr6.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getContentType */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getContentType must provide the */ /* same functionality as ResourceResponse.getContentType" */ TestResult tr7 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCONTENTTYPE); try { String hval = response.getContentType(); String pval = ((ResourceResponse) portletResp).getContentType(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr7); } catch (Exception e) { tr7.appendTcDetail(e.toString()); } tr7.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getLocale */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.getLocale must provide the same */ /* functionality as ResourceResponse.getLocale" */ TestResult tr8 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETLOCALE); try { Locale hl = response.getLocale(); Locale pl = ((MimeResponse) portletResp).getLocale(); String hval = hl.getDisplayName(); String pval = pl.getDisplayName(); CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr8); } catch (Exception e) { tr8.appendTcDetail(e.toString()); } tr8.writeTo(writer); /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_isCommitted */ /* Details: "In a target servlet of a include in the Resource phase, */ /* the method HttpServletResponse.isCommitted must provide the same */ /* functionality as ResourceResponse.isCommitted" */ TestResult tr9 = tcd.getTestResultFailed( V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ISCOMMITTED); try { boolean hval = response.isCommitted(); boolean pval = ((ResourceResponse) portletResp).isCommitted(); String str = "Value " + hval + " from " + "HttpServletResponse" + " does not equal value " + pval + " + ResourceResponse"; if (hval != pval) { tr9.appendTcDetail(str); } tr9.setTcSuccess(hval == pval); } catch (Exception e) { tr9.appendTcDetail(e.toString()); } tr9.writeTo(writer); }
// get pathInfo and parmameters from servlet call public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter pw = null; try { long startms = System.currentTimeMillis(); if (cat == null || rm.nexradList == null) { // something major wrong res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "radarServer Radar Station/Catalog initialization problem"); return; } // setup String pathInfo = req.getPathInfo(); if (pathInfo == null) pathInfo = ""; RadarType radarType = RadarType.nexrad; // default if (pathInfo.indexOf('/', 1) > 1) { String rt = pathInfo.substring(1, pathInfo.indexOf('/', 1)); radarType = RadarType.valueOf(rt); } // default is xml, assume errors will be recorded by logger from this point if (!pathInfo.endsWith("html")) { pw = res.getWriter(); res.setContentType("text/xml; charset=iso-8859-1"); // default } // radar query if (req.getQueryString() != null) { // log.debug("RadarServer query ="+ req.getQueryString() ); if (log.isDebugEnabled()) log.debug("<documentation>\n" + req.getQueryString() + "</documentation>\n"); rm.radarQuery(radarType, req, res, pw); if (log.isDebugEnabled()) log.debug("after doGet " + (System.currentTimeMillis() - startms)); pw.flush(); return; } // return radarCollections catalog xml or html if (pathInfo.startsWith("/catalog.xml") || pathInfo.startsWith("/dataset.xml")) { InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation String catAsString = factory.writeXML(cat); pw.println(catAsString); res.setStatus(HttpServletResponse.SC_OK); pw.flush(); return; } else if (pathInfo.startsWith("/catalog.html") || pathInfo.startsWith("/dataset.html")) { try { int i = HtmlWriter.getInstance().writeCatalog(req, res, cat, true); // show catalog as HTML } catch (Exception e) { log.error("Radar HtmlWriter failed ", e); res.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "radarServer HtmlWriter error " + pathInfo); return; } return; } // level2 and level3 catalog/dataset if (pathInfo.contains("level2/catalog.") || pathInfo.contains("level3/catalog.") || pathInfo.contains("level2/dataset.") || pathInfo.contains("level3/dataset.")) { level2level3catalog(radarType, pathInfo, pw, req, res); return; } // return stations of dataset if (pathInfo.endsWith("stations.xml")) { pathInfo = pathInfo.replace("/stations.xml", ""); Element rootElem = new Element("stationsList"); Document doc = new Document(rootElem); doc = rm.stationsXML(radarType, doc, rootElem, pathInfo.substring(1)); XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat()); pw.println(fmt.outputString(doc)); pw.flush(); return; } // return specific dataset information, ie IDD if (pathInfo.endsWith("dataset.xml") || pathInfo.endsWith("catalog.xml")) { datasetInfoXml(radarType, pathInfo, pw); return; } // needs work nobody using it now // return Dataset information in html form format if (pathInfo.endsWith("dataset.html") || pathInfo.endsWith("catalog.html")) { datasetInfoHtml(radarType, pathInfo, pw, res); return; } // mal formed request with no exceptions res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (FileNotFoundException e) { if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (Throwable e) { log.error("RadarServer.doGet failed", e); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } // end doGet