/** * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the * exception message to the output stream. * * @param message Message to be printed to the logger and to the output stream. * @param t Exception that caused the error. */ protected void filterError(String message, Throwable t) { log.error("XSLT filter error: " + message, t); if (false == origResponse.isCommitted()) { // Reset the buffer and previous status code. origResponse.reset(); origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); origResponse.setContentType("text/html; charset=UTF-8"); } // Response committed. Just push the error to the output stream. try { final OutputStream os = origResponse.getOutputStream(); final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1")); osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->"); osw.write("<h1 style=\"color: red; margin-top: 1em;\">"); osw.write("Internal server exception"); osw.write("</h1>"); osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>"); serializeException(osw, t); if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) { osw.write("<br/><br/><h2>ServletException root cause:</h2>"); serializeException(osw, ((ServletException) t).getRootCause()); } osw.write("</body></html>"); osw.flush(); } catch (IOException e) { // Not much to do in such case (connection broken most likely). log.debug("Filter error could not be returned to client."); } }
/** * Sets a status and sends an info message. * * @param code status code * @param message info message * @throws IOException I/O exception */ public void status(final int code, final String message) throws IOException { log(true, code, message); if (session != null) session.close(); res.resetBuffer(); res.setStatus(code); if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC); if (message != null) res.getOutputStream().write(token(message)); }
private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt) throws IOException { setContentType(pResp, pContentType); pResp.setStatus(200); setNoCacheHeaders(pResp); PrintWriter writer = pResp.getWriter(); writer.write(pJsonTxt); }
/** {@inheritDoc} */ @Override public void handle(String target, Request req, HttpServletRequest srvReq, HttpServletResponse res) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("Handling request [target=" + target + ", req=" + req + ", srvReq=" + srvReq + ']'); if (target.startsWith("/gridgain")) { processRequest(target, srvReq, res); req.setHandled(true); } else if (target.startsWith("/favicon.ico")) { if (favicon == null) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); req.setHandled(true); return; } res.setStatus(HttpServletResponse.SC_OK); res.setContentType("image/x-icon"); res.getOutputStream().write(favicon); res.getOutputStream().flush(); req.setHandled(true); } else { if (dfltPage == null) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); req.setHandled(true); return; } res.setStatus(HttpServletResponse.SC_OK); res.setContentType("text/html"); res.getWriter().write(dfltPage); res.getWriter().flush(); req.setHandled(true); } }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request); if (exception != null) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("\r\n"); out.write("<title>Error Page</title>\r\n"); out.write("</head>\r\n"); out.write("\r\n"); out.write("<body bgcolor=\"blue\">\r\n"); out.write("\t<font size=\"16\" color=\"white\">Your page generated an error:\"<br />\r\n"); out.write("\t\tException:<br /></font>\r\n"); out.write("\t"); out.print(exception.toString()); out.write("\r\n"); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) { } if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else log(t.getMessage(), t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
protected void handleDocument( HttpServletRequest request, HttpServletResponse response, Document doc) throws IOException { if (request.getPathInfo().equalsIgnoreCase("/load")) getXmlScoreBoard().loadDocument(doc); else if (request.getPathInfo().equalsIgnoreCase("/merge")) getXmlScoreBoard().mergeDocument(doc); else response.sendError( HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document"); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); }
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; } }
/** * Sets a status and sends an info message. * * @param code status code * @param message info message * @param error treat as error (use web server standard output) * @throws IOException I/O exception */ public void status(final int code, final String message, final boolean error) throws IOException { try { log(message, code); res.resetBuffer(); if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC); if (error && code >= SC_BAD_REQUEST) { res.sendError(code, message); } else { res.setStatus(code); if (message != null) res.getOutputStream().write(token(message)); } } catch (final IllegalStateException ex) { log(Util.message(ex), SC_INTERNAL_SERVER_ERROR); } }
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String sid = req.getParameter("sid"); String gameId = req.getParameter("game"); String action = req.getParameter("action"); HanabiUser user = s.getUserBySession(sid); HanabiGame game = s.getGame(gameId); try { String message; if (action.equals("play_card")) { int slot = Integer.parseInt(req.getParameter("handSlot")); HanabiGame.PlayCardResult rv = game.playCard(slot); message = "It was a " + rv.card + "; " + (rv.success ? "Success!" : "Oops!"); } else if (action.equals("discard_card")) { int slot = Integer.parseInt(req.getParameter("handSlot")); HanabiGame.Card c = game.discardCard(slot); message = "It was a " + c; } else if (action.equals("give_hint")) { doGiveHint(game, req, resp); return; } else { message = "don't know how to " + action; } JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream()); out.writeStartObject(); out.writeStringField("message", message); out.writeEndObject(); out.close(); } catch (HanabiException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream()); out.writeStartObject(); out.writeStringField("status", "error"); out.writeStringField("message", e.toString()); out.writeEndObject(); out.close(); } }
protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { try { if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest)); // getRequestURL is the exact string used by the caller in the request. // Internally, it's the "request URI" that names the service // String requestURL = httpRequest.getRequestURL().toString() ; String uri = httpRequest.getRequestURI(); if (uri.length() > urlLimit) { httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG); return; } String serviceURI = chooseServiceURI(uri, httpRequest); serviceURI = Service.canonical(serviceURI); String sender = httpRequest.getRemoteAddr(); log.info("[" + sender + "] Service URI = <" + serviceURI + ">"); // MIME-Type String contentType = httpRequest.getContentType(); // if ( Joseki.contentSPARQLUpdate.equals(contentType) || // Joseki.contentSPARQLUpdate_X.equals(contentType) ) // {} Request request = setupRequest(serviceURI, httpRequest); request.setParam(Joseki.VERB, httpRequest.getMethod()); Response response = new ResponseHttp(request, httpRequest, httpResponse); Dispatcher.dispatch(serviceURI, request, response); } catch (Exception ex) { try { log.warn("Internal server error", ex); // httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ; // httpResponse.flushBuffer() ; // httpResponse.getWriter().close() ; httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getPathInfo(); boolean htmlOutput = true; String language = null; String contentType = "text/html; charset='utf-8'"; if (path != null) { if (path.endsWith(".rdf")) { contentType = "application/rdf+xml; charset='utf-8'"; htmlOutput = false; language = "RDF/XML"; } else if (path.endsWith(".xml")) { contentType = "application/xml; charset='utf-8'"; htmlOutput = false; language = "RDF/XML"; } else if (path.endsWith(".n3")) { contentType = "text/n3; charset='utf-8'"; htmlOutput = false; language = "N3"; } } response.setContentType(contentType); response.setStatus(HttpServletResponse.SC_OK); Writer writer = response.getWriter(); synchronized (board) { if (htmlOutput) { writer.write( "<!DOCTYPE html>\n" + "<html lang='en'>" + "<head><meta charset='utf-8'/><title>MATe model</title></head>" + "<body><ul>"); StmtIterator it = model.listStatements(); /* TODO: well, this could be prettier */ while (it.hasNext()) writer.write("<li>" + it.nextStatement() + "</li>"); writer.write("<ul></body></html>"); } else model.write(writer, language); } }
/** * Process HTTP request. * * @param act Action. * @param req Http request. * @param res Http response. */ private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) { res.setContentType("application/json"); res.setCharacterEncoding("UTF-8"); GridRestCommand cmd = command(req); if (cmd == null) { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (!authChecker.apply(req.getHeader("X-Signature"))) { res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } GridRestResponse cmdRes; Map<String, Object> params = parameters(req); try { GridRestRequest cmdReq = createRequest(cmd, params, req); if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq); cmdRes = hnd.handle(cmdReq); if (cmdRes == null) throw new IllegalStateException("Received null result from handler: " + hnd); byte[] sesTok = cmdRes.sessionTokenBytes(); if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok)); res.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { res.setStatus(HttpServletResponse.SC_OK); U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e); cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage()); } catch (Throwable e) { U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e); throw e; } JsonConfig cfg = new GridJettyJsonConfig(); // Workaround for not needed transformation of string into JSON object. if (cmdRes.getResponse() instanceof String) cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC); if (cmdRes.getResponse() instanceof GridClientTaskResultBean && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String) cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC); JSON json; try { json = JSONSerializer.toJSON(cmdRes, cfg); } catch (JSONException e) { U.error(log, "Failed to convert response to JSON: " + cmdRes, e); json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg); } try { if (log.isDebugEnabled()) log.debug("Parsed command response into JSON object: " + json.toString(2)); res.getWriter().write(json.toString()); if (log.isDebugEnabled()) log.debug( "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']'); } catch (IOException e) { U.error(log, "Failed to send HTTP response: " + json.toString(2), e); } }
private static void sendNoResponse(HttpServletResponse res) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); }
/** * This method handles PUT requests from the client. PUT requests will come from the applet * portion of this application and are the way that images and other files can be posted to the * server. * * @param request the HTTP request object * @param response the HTTP response object * @exception ServletException * @exception IOException */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); /* * The Scan applet will zip all the files together to create a * faster upload and to use just one server connection. */ ZipInputStream in = new ZipInputStream(request.getInputStream()); /* * This will write all the files to a directory on the server. */ try { try { File file = new File("scan"); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); String fileSize = null; while (true) { ZipEntry entry = in.getNextEntry(); if (entry == null) { break; } File f = File.createTempFile("translate", entry.getName()); FileOutputStream out = new FileOutputStream(f); FileInputStream inStream = null; try { int read; byte[] buf = new byte[2024]; while ((read = in.read(buf)) > 0) { out.write(buf, 0, read); } out.close(); inStream = new FileInputStream(f); System.out.println(entry.getSize()); byte[] b = new byte[inStream.available()]; inStream.read(b); System.out.println(b.length); com.itextpdf.text.Image image1 = com.itextpdf.text.Image.getInstance(b); image1.scalePercent(30); image1.setCompressionLevel(9); document.add(image1); } finally { } } document.close(); // fileSize = CommonUtils.getFileSize(file); // DocumentStoreLogDAO documentStoreLogDAO = new DocumentStoreLogDAO(); // DocumentStoreLog documentStoreLog = null; // DocumentStoreLog documentStore = // (DocumentStoreLog)session.getAttribute(CommonConstants.DOCUMENT_STORE_LOG); // if(null != documentStore) { // documentStore.setFileSize(fileSize); // } // Transaction tx = documentStoreLogDAO.getSession().getTransaction(); // tx.begin(); // documentStoreLogDAO.save(documentStore); // tx.commit(); } catch (ZipException ze) { /* * We want to catch each sip exception separately because * there is a possibility that we can read more files from * the archive even if one of them is corrupted. */ ze.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { in.close(); } /* * Now that we have finished uploading the files * we will send a reponse to the server indicating * our success. */ response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html><head><title>ImageSrv</title></head></html>"); out.flush(); out.close(); response.setStatus(HttpServletResponse.SC_OK); }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // All request in GET method must be certificated Object obj = session.getAttribute("device_id"); if (!(obj instanceof Long)) { // Client must be login first, then use Mobile service response.setStatus(404); return; } response.setContentType("text/plain"); PrintWriter out = response.getWriter(); // Here is tracked's id Long device_id = (Long) obj; // Determine operation type String op = request.getParameter("op"); if (op == null) op = ""; // Get current track Long track_id = null; obj = session.getAttribute("track_id"); if (obj instanceof Long) { track_id = (Long) obj; } if (op.equals("logout")) { // Client request a logout operation session.removeAttribute("device_id"); session.removeAttribute("track_id"); out.print("OK," + device_id); } else if (op.equals("latlng")) { // Client insert update it's location in latitude/longitude // If it's a first waypoint, create a new track if (track_id == null) { track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); } // Parse latitude, longitude from request double lat = Double.parseDouble(request.getParameter("lat")); double lng = Double.parseDouble(request.getParameter("lng")); long speed = -1L; try { // Try to get speed from request speed = Long.parseLong(request.getParameter("spd")); } catch (Exception ex) { } if (speed < 0) { // Client don't send speed to server try { // Calculate speed manually double lastLat = (Double) session.getAttribute("latitude"); double lastLng = (Double) session.getAttribute("longitude"); long time = (Long) session.getAttribute("time"); long distance = Utils.getDistance(lastLat, lastLng, lat, lng); speed = distance * 1000 / Math.abs(time - System.currentTimeMillis()); } catch (Exception ex) { speed = 0L; } } // Insert new point into server ServiceResult<CWaypoint> result = db.insertWaypoint(track_id, lat, lng, speed); CWaypoint cwaypoint = result.getResult(); if (result.isOK()) { // OK,latitude,longitude,speed(m/s),time,trackid session.setAttribute("latitude", lat); session.setAttribute("longitude", lng); session.setAttribute("time", cwaypoint.getTime().getTime()); out.print( "OK," + cwaypoint.getLat() + "," + cwaypoint.getLng() + "," + cwaypoint.getSpeed() + "," + cwaypoint.getTime().getTime() + "," + cwaypoint.getTrackID()); } } else if (op.equals("cellid")) { // Client send it's location by cellular technique if (track_id == null) { track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); } try { int cell = Integer.parseInt(request.getParameter("cell")); int lac = Integer.parseInt(request.getParameter("lac")); Geocode geocode = Utils.getLocation(cell, lac); out.println(geocode.getLatitude() + "," + geocode.getLongitude()); } catch (Exception ex) { } // TODO Implements cellular method to calculate location of a mobile out.println("Not implement"); } else if (op.equals("newtrack")) { // Client request to create a new track track_id = db.newTrack(device_id).getResult().getTrackID(); session.setAttribute("track_id", track_id); out.print("OK," + track_id); } else if (op.equals("changepass")) { String newpass = request.getParameter("newpass"); if (newpass != null) { CTracked ctracked = new CTracked(); ctracked.setUsername(device_id); ctracked.setPassword(newpass); if (db.updateTracked(ctracked).isOK()) { out.println("OK," + device_id); } } } else if (op.equals("config")) { CTracked ctracked = db.getTracked(device_id).getResult(); Integer interval = ctracked.getIntervalGps(); if (interval == null) interval = 10; out.print("OK," + interval + ","); byte[] b = ctracked.getSchedule(); if (b == null) { for (int i = 0; i < 23; i++) { out.print("1."); } out.println(1); } else { for (int i = 0; i < 23; i++) { out.print(b[i] + "."); } out.println(b[23]); } } else if (op.equals("amilogin")) { out.println("OK"); } }
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) { } } }
// authentication request public String authRequest( String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException, ServletException { if (OpenIDRealm.instance == null) { ServletOutputStream out = httpResp.getOutputStream(); httpResp.setContentType("text/html; charset=\"UTF-8\""); httpResp.addHeader("pragma", "no-cache"); httpResp.addHeader("Cache-Control", "no-cache"); httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.print("<html><head>"); out.print("<title>OpenIDServlet Error</title>"); out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>"); out.print("<body><div id=\"container\"><h1>Error found</h1>"); out.print("<h2>Message:"); out.print("OpenID realm wasn't initialized."); out.print("</h2>"); // out.print(HTTPUtils.printStackTraceHTML(t)); out.print("</div></body></html>"); return null; } try { String returnAfterAuthentication = httpReq.getParameter("return_to"); // configure the return_to URL where your application will receive // the authentication responses from the OpenID provider String returnToUrl = httpReq.getRequestURL().toString() + "?is_return=true&exist_return=" + returnAfterAuthentication; // perform discovery on the user-supplied identifier List<?> discoveries = manager.discover(userSuppliedString); // attempt to associate with the OpenID provider // and retrieve one service endpoint for authentication DiscoveryInformation discovered = manager.associate(discoveries); // store the discovery information in the user's session httpReq.getSession().setAttribute("openid-disc", discovered); // obtain a AuthRequest message to be sent to the OpenID provider AuthRequest authReq = manager.authenticate(discovered, returnToUrl); if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) { SRegRequest sregReq = SRegRequest.createFetchRequest(); sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true); sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true); sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true); sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true); authReq.addExtension(sregReq); } else { FetchRequest fetch = FetchRequest.createFetchRequest(); fetch.addAttribute( AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true); fetch.addAttribute( AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true); fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true); fetch.addAttribute( AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true); fetch.addAttribute( AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true); // wants up to three email addresses fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3); authReq.addExtension(fetch); } if (!discovered.isVersion2()) { // Option 1: GET HTTP-redirect to the OpenID Provider endpoint // The only method supported in OpenID 1.x // redirect-URL usually limited ~2048 bytes httpResp.sendRedirect(authReq.getDestinationUrl(true)); return null; } else { // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes) Object OPEndpoint = authReq.getDestinationUrl(false); ServletOutputStream out = httpResp.getOutputStream(); httpResp.setContentType("text/html; charset=UTF-8"); httpResp.addHeader("pragma", "no-cache"); httpResp.addHeader("Cache-Control", "no-cache"); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); out.println("<head>"); out.println(" <title>OpenID HTML FORM Redirection</title>"); out.println("</head>"); out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">"); out.println( " <form name=\"openid-form-redirection\" action=\"" + OPEndpoint + "\" method=\"post\" accept-charset=\"utf-8\">"); Map<String, String> parameterMap = authReq.getParameterMap(); for (Entry<String, String> entry : parameterMap.entrySet()) { out.println( " <input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\"" + entry.getValue() + "\"/>"); } out.println(" <button type=\"submit\">Continue...</button>"); out.println(" </form>"); out.println("</body>"); out.println("</html>"); out.flush(); } } catch (OpenIDException e) { // present error to the user LOG.debug("OpenIDException", e); ServletOutputStream out = httpResp.getOutputStream(); httpResp.setContentType("text/html; charset=\"UTF-8\""); httpResp.addHeader("pragma", "no-cache"); httpResp.addHeader("Cache-Control", "no-cache"); httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.print("<html><head>"); out.print("<title>OpenIDServlet Error</title>"); out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>"); out.print("<body><div id=\"container\"><h1>Error found</h1>"); out.print("<h2>Message:"); out.print(e.getMessage()); out.print("</h2>"); Throwable t = e.getCause(); if (t != null) { // t can be null out.print(HTTPUtils.printStackTraceHTML(t)); } out.print("</div></body></html>"); } return null; }
// 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
/** * 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(); }
/** * 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()); } }