/** * Returns an array with all accepted content types. if the root directory was specified. * * @return database */ public String[] produces() { final String[] acc = req.getHeader("Accept").split("\\s*,\\s*"); for (int a = 0; a < acc.length; a++) { if (acc[a].indexOf(';') != -1) acc[a] = acc[a].replaceAll("\\w*;.*", ""); } return acc; }
private String getOriginOrReferer(HttpServletRequest pReq) { String origin = pReq.getHeader("Origin"); if (origin == null) { origin = pReq.getHeader("Referer"); } return origin != null ? origin.replaceAll("[\\n\\r]*", "") : null; }
/** * OPTION requests are treated as CORS preflight requests * * @param req the original request * @param resp the response the answer are written to */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, String> responseHeaders = requestHandler.handleCorsPreflightRequest( req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers")); for (Map.Entry<String, String> entry : responseHeaders.entrySet()) { resp.setHeader(entry.getKey(), entry.getValue()); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Showing Request Headers"; StringBuilder sb = new StringBuilder(); sb.append("<html>\n<head>\n"); sb.append("<title>" + title + "</title>\n"); sb.append("</head>\n"); sb.append("<body bgcolor='#FDF5E6'>\n"); sb.append("<h1 align='center'>" + title + "</h1>\n"); sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n"); sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n"); sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n"); sb.append("<table border=1 align='center'>\n"); sb.append("<tr bgcolor='#FFAD00'>\n"); sb.append("<th> Header Name </th><th> Header Value </th></tr>\n"); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); sb.append("<tr><td>" + headerName + "</td>"); sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n"); } sb.append("</table>\n"); sb.append("</body></html>"); out.println(sb.toString()); out.close(); }
@Override public final void service(final HttpServletRequest req, final HttpServletResponse res) throws IOException { final HTTPContext http = new HTTPContext(req, res, this); final boolean restxq = this instanceof RestXqServlet; try { http.authorize(); run(http); http.log(SC_OK, ""); } catch (final HTTPException ex) { http.status(ex.getStatus(), Util.message(ex), restxq); } catch (final LoginException ex) { http.status(SC_UNAUTHORIZED, Util.message(ex), restxq); } catch (final IOException | QueryException ex) { http.status(SC_BAD_REQUEST, Util.message(ex), restxq); } catch (final ProcException ex) { http.status(SC_BAD_REQUEST, Text.INTERRUPTED, restxq); } catch (final Exception ex) { final String msg = Util.bug(ex); Util.errln(msg); http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq); } finally { if (Prop.debug) { Util.outln("_ REQUEST _________________________________" + Prop.NL + req); final Enumeration<String> en = req.getHeaderNames(); while (en.hasMoreElements()) { final String key = en.nextElement(); Util.outln(Text.LI + key + Text.COLS + req.getHeader(key)); } Util.out("_ RESPONSE ________________________________" + Prop.NL + res); } } }
public DownloadRequest(ServletContext context, HttpServletRequest request) { _context = context; _httpRequest = request; _path = request.getRequestURI(); _encoding = request.getHeader(ACCEPT_ENCODING); String context_path = request.getContextPath(); if (context_path != null) _path = _path.substring(context_path.length()); if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations if (_path == null) _path = "/"; // No path given _path = _path.trim(); if (_context != null && !_path.endsWith("/")) { String realPath = _context.getRealPath(_path); // fix for 4474021 - getRealPath might returns NULL if (realPath != null) { File f = new File(realPath); if (f != null && f.exists() && f.isDirectory()) { _path += "/"; } } } // Append default file for a directory if (_path.endsWith("/")) _path += "launch.jnlp"; _version = getParameter(request, ARG_VERSION_ID); _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID); _os = getParameterList(request, ARG_OS); _arch = getParameterList(request, ARG_ARCH); _locale = getParameterList(request, ARG_LOCALE); _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS); String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID); _isPlatformRequest = (platformVersion != null); if (_isPlatformRequest) _version = platformVersion; _query = request.getQueryString(); _testJRE = getParameter(request, TEST_JRE); }
private static Properties createCGIEnvironment( HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException { URI full_request_uri = new URI( sreq.getScheme(), null, sreq.getServerName(), sreq.getServerPort(), sreq.getRequestURI(), sreq.getQueryString(), null); Properties p = createCGIEnvironment( sreq.getMethod(), sreq.getProtocol(), full_request_uri, new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()), new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()), sreq.getContextPath() + "/", root_uri, canonical_script_file); // Add request headers for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) { String h = (String) e.nextElement(); p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h)); } return p; }
/** * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE * request. * * <p>A TRACE returns the headers sent with the TRACE request to the client, so that they can be * used in debugging. There's no need to override this method. * * @param req the {@link HttpServletRequest} object that contains the request the client made of * the servlet * @param resp the {@link HttpServletResponse} object that contains the response the servlet * returns to the client * @exception IOException if an input or output error occurs while the servlet is handling the * TRACE request * @exception ServletException if the request for the TRACE cannot be handled */ protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int responseLength; String CRLF = "\r\n"; StringBuilder buffer = new StringBuilder("TRACE ") .append(req.getRequestURI()) .append(" ") .append(req.getProtocol()); Enumeration<String> reqHeaderEnum = req.getHeaderNames(); while (reqHeaderEnum.hasMoreElements()) { String headerName = reqHeaderEnum.nextElement(); buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName)); } buffer.append(CRLF); responseLength = buffer.length(); resp.setContentType("message/http"); resp.setContentLength(responseLength); ServletOutputStream out = resp.getOutputStream(); out.print(buffer.toString()); out.close(); return; }
/** * Constructor. * * @param rq request * @param rs response * @throws IOException I/O exception */ public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException { req = rq; res = rs; final String m = rq.getMethod(); method = HTTPMethod.get(m); final StringBuilder uri = new StringBuilder(req.getRequestURL()); final String qs = req.getQueryString(); if (qs != null) uri.append('?').append(qs); log(false, m, uri); // set UTF8 as default encoding (can be overwritten) res.setCharacterEncoding(UTF8); segments = toSegments(req.getPathInfo()); path = join(0); user = System.getProperty(DBUSER); pass = System.getProperty(DBPASS); // set session-specific credentials final String auth = req.getHeader(AUTHORIZATION); if (auth != null) { final String[] values = auth.split(" "); if (values[0].equals(BASIC)) { final String[] cred = Base64.decode(values[1]).split(":", 2); if (cred.length != 2) throw new LoginException(NOPASSWD); user = cred[0]; pass = cred[1]; } else { throw new LoginException(WHICHAUTH, values[0]); } } }
// Set an appropriate CORS header if requested and if allowed private void setCorsHeader(HttpServletRequest pReq, HttpServletResponse pResp) { String origin = requestHandler.extractCorsOrigin(pReq.getHeader("Origin")); if (origin != null) { pResp.setHeader("Access-Control-Allow-Origin", origin); pResp.setHeader("Access-Control-Allow-Credentials", "true"); } }
/** * Returns an array with all accepted content types. if the root directory was specified. * * @return database */ public String[] produces() { final String accept = req.getHeader("Accept"); if (accept == null) return new String[0]; final String[] acc = accept.split("\\s*,\\s*"); final int as = acc.length; for (int a = 0; a < as; a++) { if (acc[a].indexOf(';') != -1) acc[a] = acc[a].replaceAll("\\w*;.*", ""); } return acc; }
@Override public Map<String, String> getHeaders() { final Map<String, String> map = new HashMap<>(); final Enumeration<String> en = req.getHeaderNames(); while (en.hasMoreElements()) { final String name = en.nextElement(); final String val = req.getHeader(name); map.put(name, val); } return map; }
private static String getGZIPEncoding(HttpServletRequest request) { String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding == null) return null; acceptEncoding = acceptEncoding.toLowerCase(); if (acceptEncoding.indexOf("x-gzip") >= 0) { return "x-gzip"; } if (acceptEncoding.indexOf("gzip") >= 0) { return "gzip"; } return null; }
private void verifyAjaxToken(HttpServletRequest request) throws CsrfGuardException { HttpSession session = request.getSession(true); String tokenFromSession = (String) session.getAttribute(getSessionKey()); String tokenFromRequest = request.getHeader(getTokenName()); if (tokenFromRequest == null) { /** FAIL: token is missing from the request * */ throw new CsrfGuardException("required token is missing from the request"); } else if (tokenFromRequest.indexOf(tokenFromSession) == -1) { /** FAIL: the request token does not match the session token * */ throw new CsrfGuardException("request token does not match session token"); } }
public String getClientIPAddr() { HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest()); String remoteAddr = request.getRemoteAddr(); String x; if ((x = request.getHeader("X-FORWARDED-FOR")) != null) { remoteAddr = x; int idx = remoteAddr.indexOf(','); if (idx > -1) { remoteAddr = remoteAddr.substring(0, idx); } } return remoteAddr; }
/** @service the servlet service request. called once for each servlet request. */ public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException { String name; String value[]; String val; servRes.setHeader("AUTHORIZATION", "user fred:mypassword"); ServletOutputStream out = servRes.getOutputStream(); HttpSession session = servReq.getSession(true); session.setAttribute("timemilis", new Long(System.currentTimeMillis())); if (session.isNew()) { out.println("<p> Session is new "); } else { out.println("<p> Session is not new "); } Long l = (Long) session.getAttribute("timemilis"); out.println("<p> Session id = " + session.getId()); out.println("<p> TimeMillis = " + l); out.println("<H2>Servlet Params</H2>"); Enumeration e = servReq.getParameterNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); value = servReq.getParameterValues(name); out.println(name + " : "); for (int i = 0; i < value.length; ++i) { out.println(value[i]); } out.println("<p>"); } out.println("<H2> Request Headers : </H2>"); e = servReq.getHeaderNames(); while (e.hasMoreElements()) { name = (String) e.nextElement(); val = (String) servReq.getHeader(name); out.println("<p>" + name + " : " + val); } try { BufferedReader br = servReq.getReader(); String line = null; while (null != (line = br.readLine())) { out.println(line); } } catch (IOException ie) { ie.printStackTrace(); } session.invalidate(); }
@SuppressWarnings("unchecked") private void handleAction( RenderVelocityAction action, String cmd, Vector[] args, HttpServletRequest request) { if (action != null) { // add parameter from path for (int p = 0; p < args[0].size(); p++) { action.putParam((String) args[0].get(p), (String) args[1].get(p)); } VelocityContext c = new VelocityContext(); try { c.put("action", action); c.put("encoding", action.encoding); c.put("cmd", cmd); // c.put("au", action.user); c.put("reqaddress", request.getRemoteAddr()); c.put("scheme", request.getScheme()); c.put("querystring", request.getQueryString()); if (c.get("querystring") == null) { c.put("querystring", ""); } String requesturl = request.getRequestURL().toString(); // c.put("mid", ma.user.mandantid); c.put("request", request); c.put("requesturl", requesturl); c.put("server", request.getServerName()); c.put("port", request.getServerPort()); String ref = request.getHeader("Referer"); if (ref == null) { ref = "#"; } c.put("referer", ref); // process and render template action.process(c); } catch (Exception ex) { ex.printStackTrace(); // action.makeErrorOutput("Internal Error", null, c); } } }
public void doFilter(ServletRequest request0, ServletResponse response0, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) request0; HttpServletResponse response = (HttpServletResponse) response0; if (request.getRequestURI().endsWith(requesturl)) { boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With")); request.getSession().invalidate(); if (isAjax) { Response<String> kv = new Response<String>(); kv.setReturncode("00000000"); kv.setReturnmsg("登出成功"); outputJson(response, kv); } else { response.sendRedirect(request.getContextPath() + successurl); } return; } filterChain.doFilter(request, response); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); String title = rb.getString("requestheader.title"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=\"white\">"); // all links relative // XXX // making these absolute till we work out the // addition of a PathInfo issue out.println("<a href=\"../reqheaders.html\">"); out.println( "<img src=\"../images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>"); out.println("<a href=\"../index.html\">"); out.println( "<img src=\"../images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>"); out.println("<h3>" + title + "</h3>"); out.println("<table border=0>"); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String headerName = (String) e.nextElement(); String headerValue = request.getHeader(headerName); out.println("<tr><td bgcolor=\"#CCCCCC\">"); out.println(HTMLFilter.filter(headerName)); out.println("</td><td>"); out.println(HTMLFilter.filter(headerValue)); out.println("</td></tr>"); } out.println("</table>"); }
@Override protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { String login = successfulAuthentication.getName(); log.debug("Creating new persistent login for user {}", login); User user = userRepository.findOne(login); PersistentToken token = new PersistentToken(); token.setSeries(generateSeriesData()); token.setUser(user); token.setTokenValue(generateTokenData()); token.setTokenDate(new LocalDate()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to save persistent token ", e); } }
@Override @Transactional protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { PersistentToken token = getPersistentToken(cookieTokens); String login = token.getUser().getLogin(); // Token also matches, so login is valid. Update the token value, keeping the *same* series number. log.debug("Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries()); token.setTokenDate(new LocalDate()); token.setTokenValue(generateTokenData()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to update token: ", e); throw new RememberMeAuthenticationException("Autologin failed due to data access problem: " + e.getMessage()); } return getUserDetailsService().loadUserByUsername(login); }
/** * Constructor. * * @param rq request * @param rs response * @param servlet calling servlet instance * @throws IOException I/O exception */ public HTTPContext( final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet) throws IOException { req = rq; res = rs; params = new HTTPParams(this); method = rq.getMethod(); final StringBuilder uri = new StringBuilder(req.getRequestURL()); final String qs = req.getQueryString(); if (qs != null) uri.append('?').append(qs); log('[' + method + "] " + uri, null); // set UTF8 as default encoding (can be overwritten) res.setCharacterEncoding(UTF8); segments = decode(toSegments(req.getPathInfo())); // adopt servlet-specific credentials or use global ones final GlobalOptions mprop = context().globalopts; user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER); pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD); // overwrite credentials with session-specific data final String auth = req.getHeader(AUTHORIZATION); if (auth != null) { final String[] values = auth.split(" "); if (values[0].equals(BASIC)) { final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2); if (cred.length != 2) throw new LoginException(NOPASSWD); user = cred[0]; pass = cred[1]; } else { throw new LoginException(WHICHAUTH, values[0]); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form. response.setCharacterEncoding("UTF-8"); // Unicode++ request.setCharacterEncoding("UTF-8"); PrintWriter out = null; // The talkback buffer. // handle startrecord Integer startRecord = 0; if (!(request.getParameter("startRecord") == null)) { try { startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1; } catch (NumberFormatException e) { startRecord = 0; } } // maximumrecords Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords")); if (!(request.getParameter("maximumRecords") == null)) { maximumRecords = Integer.parseInt(request.getParameter("maximumRecords")); } // operation String operation = request.getParameter("operation"); // x_collection String x_collection = request.getParameter("x-collection"); if (x_collection == null) x_collection = this.config.getProperty("default_x_collection"); if (x_collection == null) operation = null; // sortkeys String sortKeys = request.getParameter("sortKeys"); // sortorder String sortOrder = request.getParameter("sortOrder"); // recordschema String recordSchema = request.getParameter("recordSchema"); if (recordSchema == null) recordSchema = "dc"; if (recordSchema.equalsIgnoreCase("dcx")) { recordSchema = "dcx"; } if (recordSchema.equalsIgnoreCase("solr")) { recordSchema = "solr"; } // query request String query = request.getParameter("query"); String q = request.getParameter("q"); // who is requestor ? String remote_ip = request.getHeader("X-FORWARDED-FOR"); if (remote_ip == null) { remote_ip = request.getRemoteAddr().trim(); } else { remote_ip = request.getHeader("X-FORWARDED-FOR"); } // handle debug Boolean debug = Boolean.parseBoolean(request.getParameter("debug")); if (!debug) { out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true); } // handle query if ((query == null) && (q != null)) { query = q; } else { if ((query != null) && (q == null)) { q = query; } else { operation = null; } } // handle operation if (operation == null) { if (query != null) { operation = "searchRetrieve"; } else { operation = "explain"; } } // searchRetrieve if (operation.equalsIgnoreCase("searchRetrieve")) { if (query == null) { operation = "explain"; log.debug(operation + ":" + query); } } // start talking back. String[] sq = {""}; String solrquery = ""; // facet String facet = null; List<FacetField> fct = null; if (request.getParameter("facet") != null) { facet = request.getParameter("facet"); log.debug("facet : " + facet); } if (operation == null) { operation = "searchretrieve"; } else { // explain response if (operation.equalsIgnoreCase("explain")) { log.debug("operation = explain"); out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">"); out.write("</srw:explainResponse>"); } else { // DEBUG routine operation = "searchretrieve"; String triplequery = null; if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax triplequery = symantic_query(query); query = query.split("\\[")[0] + " " + triplequery; log.fatal(triplequery); solrquery = CQLtoLucene.translate(query, log, config); } else { solrquery = CQLtoLucene.translate(query, log, config); } log.debug(solrquery); if (debug == true) { response.setContentType(HTML_RESPONSE_HEADER); out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true); out.write("<html><body>\n\n"); out.write("'" + remote_ip + "'<br>\n"); out.write("<form action='http://www.kbresearch.nl/kbSRU'>"); out.write("<input type=text name=q value='" + query + "' size=120>"); out.write("<input type=hidden name=debug value=True>"); out.write("<input type=submit>"); out.write("<table border=1><tr><td>"); out.write("q</td><td>" + query + "</td></tr><tr>"); out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>"); out.write( "<tr><td>SOLR_URL</td><td> <a href='" + this.config.getProperty( "collection." + x_collection.toLowerCase() + ".solr_baseurl") + "/?q=" + solrquery + "'>" + this.config.getProperty( "collection." + x_collection.toLowerCase() + ".solr_baseurl") + "/select/?q=" + solrquery + "</a><br>" + this.config.getProperty("solr_url") + solrquery + "</td></tr>"); out.write( "<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='" + this.config.getProperty( "collection." + x_collection.toLowerCase() + ".solr_baseurl") + "/../?q=" + solrquery + "'></iframe><BR>"); out.write( "<b>SRU_QUERY</b> : <BR> <a href=" + this.config.getProperty("baseurl") + "?q=" + query + "'>" + this.config.getProperty("baseurl") + "?q=" + query + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q=" + query + "'></iframe><BR>"); out.write( "<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query=" + query + "&x-collection=" + x_collection + "'>http://jsru.kb.nl/sru/?query=" + query + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query=" + query + "&x-collection=GGC'></iframe>"); } else { // XML SearchRetrieve response String url = this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl"); String buffer = ""; CommonsHttpSolrServer server = null; server = new CommonsHttpSolrServer(url); log.fatal("URSING " + url); server.setParser(new XMLResponseParser()); int numfound = 0; try { SolrQuery do_query = new SolrQuery(); do_query.setQuery(solrquery); do_query.setRows(maximumRecords); do_query.setStart(startRecord); if ((sortKeys != null) && (sortKeys.length() > 1)) { if (sortOrder != null) { if (sortOrder.equals("asc")) { do_query.setSortField(sortKeys, SolrQuery.ORDER.asc); } if (sortOrder.equals("desc")) { do_query.setSortField(sortKeys, SolrQuery.ORDER.desc); } } else { for (String str : sortKeys.trim().split(",")) { str = str.trim(); if (str.length() > 1) { if (str.equals("date")) { do_query.setSortField("date_date", SolrQuery.ORDER.desc); log.debug("SORTORDERDEBUG | DATE! " + str + " | "); break; } else { do_query.setSortField(str + "_str", SolrQuery.ORDER.asc); log.debug("SORTORDERDEBUG | " + str + " | "); break; } } } } } if (facet != null) { if (facet.indexOf(",") > 1) { for (String str : facet.split(",")) { if (str.indexOf("date") > 1) { do_query.addFacetField(str); } else { do_query.addFacetField(str); } // do_query.setParam("facet.method", "enum"); } // q.setFacetSort(false); } else { do_query.addFacetField(facet); } do_query.setFacet(true); do_query.setFacetMinCount(1); do_query.setFacetLimit(-1); } log.fatal(solrquery); QueryResponse rsp = null; boolean do_err = false; boolean do_sugg = false; SolrDocumentList sdl = null; String diag = ""; StringBuffer suggest = new StringBuffer(""); String content = "1"; SolrQuery spellq = do_query; try { rsp = server.query(do_query); } catch (SolrServerException e) { String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0"); out.write(header); diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage()); do_err = true; rsp = null; } log.fatal("query done.."); if (!(do_err)) { // XML dc response SolrDocumentList docs = rsp.getResults(); numfound = (int) docs.getNumFound(); int count = startRecord; String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", Integer.toString(numfound)); out.write(header); out.write("<srw:records>"); Iterator<SolrDocument> iter = rsp.getResults().iterator(); while (iter.hasNext()) { count += 1; if (recordSchema.equalsIgnoreCase("dc")) { SolrDocument resultDoc = iter.next(); content = (String) resultDoc.getFieldValue("id"); out.write("<srw:record>"); out.write("<srw:recordPacking>xml</srw:recordPacking>"); out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>"); out.write( "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >"); StringBuffer result = new StringBuffer(""); construct_lucene_dc(result, resultDoc); out.write(result.toString()); out.write("</srw:recordData>"); out.write( "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>"); out.write("</srw:record>"); } if (recordSchema.equalsIgnoreCase("solr")) { SolrDocument resultDoc = iter.next(); content = (String) resultDoc.getFieldValue("id"); out.write("<srw:record>"); out.write("<srw:recordPacking>xml</srw:recordPacking>"); out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>"); out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">"); StringBuffer result = new StringBuffer(""); construct_lucene_solr(result, resultDoc); out.write(result.toString()); out.write("</srw:recordData>"); out.write( "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>"); out.write("</srw:record>"); } if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response out.write("<srw:record>"); out.write("<srw:recordPacking>xml</srw:recordPacking>"); out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>"); out.write( "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >"); SolrDocument resultDoc = iter.next(); content = (String) resultDoc.getFieldValue("id"); String dcx_data = helpers.getOAIdcx( "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content, log); if (x_collection.equalsIgnoreCase("ggc-thes")) { dcx_data = helpers.getOAIdcx( "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content, log); } if (!(dcx_data.length() == 0)) { out.write(dcx_data); } else { // Should not do this!! out.write("<srw:record>"); out.write("<srw:recordPacking>xml</srw:recordPacking>"); out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>"); out.write( "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >"); StringBuffer result = new StringBuffer(""); construct_lucene_dc(result, resultDoc); out.write(result.toString()); out.write("</srw:recordData>"); out.write( "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>"); out.write("</srw:record>"); } out.write("</srw_dc:dc>"); StringBuffer expand_data; boolean expand = false; if (content.startsWith("GGC-THES:AC:")) { String tmp_content = ""; tmp_content = content.replaceFirst("GGC-THES:AC:", ""); log.fatal("calling get"); expand_data = new StringBuffer( helpers.getExpand( "http://www.kbresearch.nl/general/lod_new/get/" + tmp_content + "?format=rdf", log)); log.fatal("get finini"); if (expand_data.toString().length() > 4) { out.write( "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >"); out.write(expand_data.toString()); expand = true; } } else { expand_data = new StringBuffer( helpers.getExpand( "http://www.kbresearch.nl/ANP.cgi?q=" + content, log)); if (expand_data.toString().length() > 0) { if (!expand) { out.write( "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >"); expand = true; } out.write(expand_data.toString()); } } if (expand) { out.write("</srw_dc:expand>"); } out.write("</srw:recordData>"); out.write( "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>"); out.write("</srw:record>"); } } } if ((do_err) || (numfound == 0)) { log.fatal("I haz suggestions"); try { spellq.setParam("spellcheck", true); spellq.setQueryType("/spell"); server = new CommonsHttpSolrServer(url); rsp = server.query(spellq); sdl = rsp.getResults(); SpellCheckResponse spell; spell = rsp.getSpellCheckResponse(); List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions(); if (suggestions.isEmpty() == false) { suggest.append("<srw:extraResponseData>"); suggest.append("<suggestions>"); for (SpellCheckResponse.Suggestion sugg : suggestions) { suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>"); for (String item : sugg.getSuggestions()) { suggest.append("<suggestion>" + item + "</suggestion>"); } suggest.append("</suggestions>"); suggest.append("</srw:extraResponseData>"); } do_sugg = true; } } catch (Exception e) { rsp = null; // log.fatal(e.toString()); } ; } ; if (!do_err) { if (facet != null) { try { fct = rsp.getFacetFields(); out.write("<srw:facets>"); for (String str : facet.split(",")) { out.write("<srw:facet>"); out.write("<srw:facetType>"); out.write(str); out.write("</srw:facetType>"); for (FacetField f : fct) { log.debug(f.getName()); // if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) { List<FacetField.Count> facetEnties = f.getValues(); for (FacetField.Count fcount : facetEnties) { out.write("<srw:facetValue>"); out.write("<srw:valueString>"); out.write(helpers.xmlEncode(fcount.getName())); out.write("</srw:valueString>"); out.write("<srw:count>"); out.write(Double.toString(fcount.getCount())); out.write("</srw:count>"); out.write("</srw:facetValue>"); // } } } out.write("</srw:facet>"); } out.write("</srw:facets>"); startRecord += 1; } catch (Exception e) { } // log.fatal(e.toString()); } } } else { out.write(diag); } out.write("</srw:records>"); // SearchRetrieve response footer String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query)); footer = footer.replaceAll("\\$startRecord", (startRecord).toString()); footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString()); footer = footer.replaceAll("\\$recordSchema", recordSchema); if (do_sugg) { out.write(suggest.toString()); } out.write(footer); } catch (MalformedURLException e) { out.write(e.getMessage()); } catch (IOException e) { out.write("TO ERR is Human"); } } } } out.close(); }
@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 _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; 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; charset=UTF-8"); 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("\r\n"); String host = request.getScheme() + "://" + request.getHeader("host"); request.setAttribute("host", host); out.write('\r'); out.write('\n'); org.apache.jasper.runtime.JspRuntimeLibrary.include( request, response, "../include/core_header.jsp", out, false); out.write('\r'); out.write('\n'); out.write("\r\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); out.write("\r\n"); out.write("<link href=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/css/centerLeft.css\" rel=\"stylesheet\">\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/jquery.js\"></script>\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/centerLeft.js\"></script>\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/ajax-pushlet-client.js\"></script>\r\n"); out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n"); out.write("\r\n"); out.write("<title>会员个人中心</title>\r\n"); out.write("<style type=\"text/css\">\r\n"); out.write("body {\r\n"); out.write("\toverflow-x: hidden;\r\n"); out.write("}\r\n"); out.write("</style>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t<div class=\"content\">\r\n"); out.write("\t\t<div class=\"mainContent\">\r\n"); out.write("\t\t\t<div class=\"leftMain\">\r\n"); out.write("\t\t\t\t<div class=\"orange\"></div>\r\n"); out.write("\t\t\t\t<ul>\r\n"); out.write("\t\t\t\t\t<li class=\"focusColor\"><a id=\"wodeCen\" href=\"wodeCen\"\r\n"); out.write("\t\t\t\t\t\ttarget=\"rightFrame\">我的中心</a></li>\r\n"); out.write("\t\t\t\t\t<li id=\"sel1\">医疗服务</li>\r\n"); out.write("\t\t\t\t\t<div id=\"selD1\" class=\"vanish\">\r\n"); out.write( "\t\t\t\t\t\t<a id=\"wodeDoc\" href=\"wodeDoc\" target=\"rightFrame\">我的专家</a>\r\n"); out.write( "\t\t\t\t\t\t <a id=\"huanyouSoc\" href=\"javascript:void(0)\" onclick=\"alert('功能正在实现')\" target=\"rightFrame\">患友会</a>\r\n"); out.write( "\t\t\t\t\t\t <a id=\"jiuyiExp\" href=\"jiuyiExp\" target=\"rightFrame\">就医经验</a>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<li id=\"sel2\">我的可穿戴设备</li>\r\n"); out.write("\t\t\t\t\t<div id=\"selD2\" class=\"vanish\">\r\n"); out.write( "\t\t\t\t\t\t<a id=\"myBloodPressure\" href=\"myBloodPressure\" target=\"rightFrame\">我的血压</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"mySleepRecord\" href=\"mySleepRecord\" target=\"rightFrame\">我的睡眠</a>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<li id=\"sel3\">疾病管理</li>\r\n"); out.write("\t\t\t\t\t<div id=\"selD3\" class=\"vanish\">\r\n"); out.write( "\t\t\t\t\t\t<a id=\"jibingMan\" href=\"jibingMan\" target=\"rightFrame\">离线咨询</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"myAppointment\" href=\"myAppointment\" target=\"rightFrame\">我的预约</a>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t\t<li id=\"sel4\">我的家属</li>\r\n"); out.write("\t\t\t\t\t<div id=\"selD4\" class=\"vanish\">\r\n"); out.write( "\t\t\t\t\t\t<a id=\"myfamily\" href=\"myfamily\" target=\"rightFrame\">我的家属</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"membArchInfo\" href=\"membArchInfo\" target=\"rightFrame\">电子健康档案</a>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\r\n"); out.write("\t\t\t\t\t<li id=\"sel5\">我的账户</li>\r\n"); out.write("\t\t\t\t\t<div id=\"selD5\" class=\"vanish\">\r\n"); out.write( "\t\t\t\t\t\t<a id=\"caiwuMan\" href=\"caiwuMan\" target=\"rightFrame\">财务管理</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"jifenMan\" href=\"jifenMan\" target=\"rightFrame\">积分管理</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"gerenInfo\" href=\"gerenInfo\" target=\"rightFrame\">个人信息管理</a>\r\n"); out.write( "\t\t\t\t\t\t<a id=\"passChange\" href=\"passChange\" target=\"rightFrame\">修改密码</a>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\r\n"); out.write("\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\r\n"); out.write("\t\t\t<script>\r\n"); out.write("\t\t\t\t$(window).load(\r\n"); out.write("\t\t\t\t\t\tfunction() {\r\n"); out.write("\t\t\t\t\t\t\thobj = $.ajax({\r\n"); out.write("\t\t\t\t\t\t\t\turl : 'wodeCen',\r\n"); out.write("\t\t\t\t\t\t\t\tsuccess : function() {\r\n"); out.write("\t\t\t\t\t\t\t\t},\r\n"); out.write("\t\t\t\t\t\t\t\terror : function() {\r\n"); out.write("\t\t\t\t\t\t\t\t\talert(\"加载信息错误\");\r\n"); out.write("\t\t\t\t\t\t\t\t},\r\n"); out.write("\t\t\t\t\t\t\t\tasync : false\r\n"); out.write("\t\t\t\t\t\t\t});\r\n"); out.write("\t\t\t\t\t\t\t$(window.frames[\"rightFrame\"].document).html(\r\n"); out.write("\t\t\t\t\t\t\t\t\thobj.responseText);\r\n"); out.write("\t\t\t\t\t\t});\r\n"); out.write("\t\t\t</script>\r\n"); out.write("\t\t</div>\r\n"); out.write("\t</div>\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); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
private boolean isAjaxRequest(HttpServletRequest request) { return request.getHeader("X-Requested-With") != null; }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; 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; charset=UTF-8"); 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'); out.write('\n'); String templateUrl = request.getScheme() + "://" + request.getHeader("host") + request.getContextPath(); request.setAttribute("url", templateUrl); String MembFamily_Id = request.getParameter("MembFamily_Id"); out.write("\r\n"); out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/css0623/style.css\" />\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/jquery.js\"></script>\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/jquery.validate.js\"></script>\r\n"); out.write("<script type=\"text/javascript\" src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/js/register.js\"></script>\r\n"); out.write("\r\n"); out.write("<script>\r\n"); out.write(" function getMembFamilyById(){\r\n"); out.write(" \t$.ajax({\r\n"); out.write("\t url : '"); out.print(templateUrl); out.write("/user/MembFamilyForReadAction?MembFamily_Id="); out.print(MembFamily_Id); out.write("',\r\n"); out.write("\t\t\ttype : 'POST',\r\n"); out.write("\t\t\tcontentType: \"application/x-www-form-urlencoded; charset=utf-8\",\r\n"); out.write("\t\t\tdataType : 'json',\r\n"); out.write("\t\t\ttimeout : 8000,\r\n"); out.write("\t\t\tcache : true,\r\n"); out.write("\t\t\terror : erryFunction, //错误执行方法 \r\n"); out.write("\t\t\tsuccess : succFunction\r\n"); out.write("\t\t//成功执行方法 \r\n"); out.write("\t\t});\r\n"); out.write("\t\tfunction erryFunction(data) {\r\n"); out.write("\t\t\talert(\"等待3秒后请刷新页面\");\r\n"); out.write("\t\t}\r\n"); out.write("\t\tfunction succFunction(data) {\r\n"); out.write("\t\t\t$(\"#FamilyName\").val(data.FamilyName);\r\n"); out.write( "\t\t\t$(\"input:radio[name='sex']\").eq(parseInt(data.sex)).attr(\"checked\",true);\r\n"); out.write("\t\t\t$(\"#age\").val(data.age);\r\n"); out.write("\t\t\t$(\"#relation\").val(data.relation);\r\n"); out.write("\t\t\t$(\"#mobile\").val(data.mobile);\r\n"); out.write("\t\t\t$(\"#telephone\").val(data.telephone);\r\n"); out.write("\t\t\t$(\"#address\").val(data.address);\r\n"); out.write("\t\t}\r\n"); out.write("\t}\r\n"); out.write("\twindow.onload = function() {\r\n"); out.write("\t\tgetMembFamilyById();\r\n"); out.write("\t};\r\n"); out.write("</script>\r\n"); out.write("</head>\r\n"); out.write("<style>\r\n"); out.write("\r\n"); out.write("</style>\r\n"); out.write("<body>\r\n"); out.write("<div id=\"page\">\r\n"); out.write("\t\r\n"); out.write( "<form id=\"newFamilyMember\" name=\"newFamilyMember\" method=\"post\" action=\"UpdateMemberFamily\">\r\n"); out.write("\t<div>\r\n"); out.write("\t\t<img src=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/imgs/membercenter/left.png\" /> <font\r\n"); out.write("\t\t\t\tsize=\"6\"><b>更新家属信息</b>\r\n"); out.write("\t\t</font> <img\r\n"); out.write("\t\t\t\tsrc=\""); out.write( (java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate( "${url}", java.lang.String.class, (PageContext) _jspx_page_context, null, false)); out.write("/imgs/membercenter/right.png\" />\r\n"); out.write("\t</div>\r\n"); out.write("\t<br/>\r\n"); out.write("\t<table class=\"wwFormTable\" style=\"font-family: '宋体';font-size: 18px;\">\r\n"); out.write("\t\t\t<fieldset>\r\n"); out.write("\t\t\t\t<ul>\r\n"); out.write(" \t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"FamilyName\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"required\" style=\"font-family: '宋体';font-size: 18px;\"><b>[患者姓名]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<input id=\"FamilyName\" name=\"FamilyName\" type=\"text\">\r\n"); out.write("\t\t\t\t\t\t<label for=\"FamilyName\" class=\"error\">患者姓名不可为空</label>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"sex\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"required\" style=\"font-family: '宋体';font-size: 18px;\"><b>[性别]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write( "\t\t\t\t\t\t<input name=\"sex\" type=\"radio\" value=\"male\" checked=\"checked\" >男 \r\n"); out.write("\t\t\t\t\t\t<input name=\"sex\" type=\"radio\" value=\"female\" >女\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"age\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"required\" style=\"font-family: '宋体';font-size: 18px;\"><b>[年龄]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<input id=\"age\" name=\"age\" type=\"text\">\r\n"); out.write("\t\t\t\t\t\t<label for=\"age\" class=\"error\">请填写正确的年龄</label>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"relation\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"relation\" style=\"font-family: '宋体';font-size: 18px;\"><b>[与患者关系]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<select id=\"relation\" name=\"relation\">\r\n"); out.write("\t\t\t\t\t\t\t<option value=\"本人\" selected=\"selected\">本人</option>\r\n"); out.write("\t\t\t\t\t\t\t<option value=\"家庭成员\">家庭成员</option>\r\n"); out.write("\t\t\t\t\t\t\t<option value=\"亲戚\">亲戚</option>\r\n"); out.write("\t\t\t\t\t\t\t<option value=\"朋友\">朋友</option>\r\n"); out.write("\t\t\t\t\t\t\t<option value=\"其他\">其他</option>\r\n"); out.write("\t\t\t\t\t</select>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"mobile\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"mobile\" style=\"font-family: '宋体';font-size: 18px;\"><b>[手机号]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<input id=\"mobile\" name=\"mobile\" type=\"text\">\r\n"); out.write("\t\t\t\t\t\t<label for=\"mobile\" class=\"error\">请填写正确的手机号</label>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"telephone\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"telephone\" style=\"font-family: '宋体';font-size: 18px;\"><b>[固定电话]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<input id=\"telephone\" name=\"telephone\" type=\"text\">\r\n"); out.write("\t\t\t\t\t\t<label for=\"telephone\" class=\"error\">请填写正确的固定电话</label>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t\t<br/>\r\n"); out.write("\t\t\t\t\t<li>\r\n"); out.write("\t\t\t\t\t\t<label for=\"address\">\r\n"); out.write( "\t\t\t\t\t\t\t<span class=\"address\" style=\"font-family: '宋体';font-size: 18px;\"><b>[家庭地址]</b></span>\r\n"); out.write("\t\t\t\t\t\t</label>\r\n"); out.write("\t\t\t\t\t\t<input id=\"address\" name=\"address\" type=\"text\">\r\n"); out.write("\t\t\t\t\t\t<label for=\"address\" class=\"error\">家庭地址不可为空</label>\r\n"); out.write("\t\t\t\t\t</li>\r\n"); out.write("\t\t\t\t</ul>\r\n"); out.write("\t\t\t</fieldset>\r\n"); out.write("\t\t\t<fieldset class=\"submit\">\r\n"); out.write("\t\t\t<input type=\"hidden\" name=\"MembFamily_Id\" value=\""); out.print(MembFamily_Id); out.write("\" >\r\n"); out.write( "\t\t\t \r\n"); out.write( "\t\t\t \r\n"); out.write( "\t\t\t \r\n"); out.write( "\t\t\t \r\n"); out.write("\t\t\t\t<input type=\"submit\" class=\"submit\" value=\"确认\" />\r\n"); out.write("\t\t\t</fieldset>\r\n"); out.write("\t\t\t<div class=\"clear\"></div>\r\n"); out.write("\t\t</table>\r\n"); out.write("</form>\r\n"); out.write("</div>\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); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
/** * 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); } }
/* * Procesamiento de peticiones GET y POST * @param request * @param response * @throws ServletException * @throws IOException */ public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Comprobar si es un GET if (request.getMethod().equalsIgnoreCase("GET")) { return; } // Se trata de un POST // La respuesta es JSON response.setContentType("application/json; charset=UTF-8"); // Crear los filtros definidos para todos los servicios es.tid.frawa.service.servlet.Filter[] filters = new es.tid.frawa.service.servlet.Filter[0]; PrintWriter output = null; StringBuffer input = null; String action = ""; try { // Crea una sesión si no existe (esta opción está marcada en el modelo de servicios) request.getSession(true); // Invocar el método startService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].startService(request, response); } // Invocar el método frawaService() de la clase derivada (si está implementado) if (!frawaService(request, response)) { // Ha retornado false, por tanto abortamos el procesamiento del servicio return; } // Mensaje por defecto para los filtros que no necesitan el texto JSON StringBuffer soapStr = new StringBuffer(""); // Leer el mensaje JSON if (request.getParameter("JSONAction") != null && request.getParameter("JSONAction").length() > 0) { action = request.getParameter("JSONAction"); String tmp = request.getParameter("JSON"); if (tmp == null || tmp.length() == 0) { throw new Exception( getClass().getName() + ".service() JSONAction viene en la URL pero no viene el parámetro JSON con los datos"); } input = new StringBuffer(tmp); } else { action = request.getHeader("JSONAction"); if (action == null || action.length() == 0) { throw new Exception( getClass().getName() + ".service() La cabecera HTTP JSONAction no esta definida"); } // new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName()+".service() // Leyendo mensaje JSON"); BufferedReader input_r = new BufferedReader(request.getReader()); input = new StringBuffer(); String line = input_r.readLine(); while (line != null) { input.append(line); line = input_r.readLine(); } } // Invocar el método beforeParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeParse(request, response, input.toString()); } // // Invocar al servicio adecuado en función del header JSONAction // if (action.equals("http://www.qualipso.org/advdoc/ws/storage/CreateFolder")) { // SERVICIO: CreateFolder // Parámetro de entrada al servicio CreateFolder_req inbean = new CreateFolder_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio CreateFolder_resp outbean = new CreateFolder_resp(); // Crear un objeto que implementa la operación CreateFolderService serviceImplementation = new CreateFolderService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: CreateFolder]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetFiles")) { // SERVICIO: GetFiles // Parámetro de entrada al servicio GetFiles_req inbean = new GetFiles_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio GetFiles_resp outbean = new GetFiles_resp(); // Crear un objeto que implementa la operación GetFilesService serviceImplementation = new GetFilesService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: GetFiles]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetSubFolders")) { // SERVICIO: GetSubFolders // Parámetro de entrada al servicio GetSubFolders_req inbean = new GetSubFolders_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio GetSubFolders_resp outbean = new GetSubFolders_resp(); // Crear un objeto que implementa la operación GetSubFoldersService serviceImplementation = new GetSubFoldersService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: GetSubFolders]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadBinaryFile")) { // SERVICIO: LoadBinaryFile // Parámetro de entrada al servicio LoadBinaryFile_req inbean = new LoadBinaryFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio LoadBinaryFile_resp outbean = new LoadBinaryFile_resp(); // Crear un objeto que implementa la operación LoadBinaryFileService serviceImplementation = new LoadBinaryFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: LoadBinaryFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadFile")) { // SERVICIO: LoadFile // Parámetro de entrada al servicio LoadFile_req inbean = new LoadFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio LoadFile_resp outbean = new LoadFile_resp(); // Crear un objeto que implementa la operación LoadFileService serviceImplementation = new LoadFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: LoadFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFile")) { // SERVICIO: RemoveFile // Parámetro de entrada al servicio RemoveFile_req inbean = new RemoveFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio RemoveFile_resp outbean = new RemoveFile_resp(); // Crear un objeto que implementa la operación RemoveFileService serviceImplementation = new RemoveFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: RemoveFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFolder")) { // SERVICIO: RemoveFolder // Parámetro de entrada al servicio RemoveFolder_req inbean = new RemoveFolder_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio RemoveFolder_resp outbean = new RemoveFolder_resp(); // Crear un objeto que implementa la operación RemoveFolderService serviceImplementation = new RemoveFolderService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: RemoveFolder]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreBinaryFile")) { // SERVICIO: StoreBinaryFile // Parámetro de entrada al servicio StoreBinaryFile_req inbean = new StoreBinaryFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio StoreBinaryFile_resp outbean = new StoreBinaryFile_resp(); // Crear un objeto que implementa la operación StoreBinaryFileService serviceImplementation = new StoreBinaryFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: StoreBinaryFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreFile")) { // SERVICIO: StoreFile // Parámetro de entrada al servicio StoreFile_req inbean = new StoreFile_req(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio StoreFile_resp outbean = new StoreFile_resp(); // Crear un objeto que implementa la operación StoreFileService serviceImplementation = new StoreFileService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: StoreFile]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestLoopback")) { // SERVICIO: TestLoopback // Parámetro de entrada al servicio org.qualipso.advdoc.ws.client.storage.beans.TestLoopback inbean = new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio org.qualipso.advdoc.ws.client.storage.beans.TestLoopback outbean = new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback(); // Crear un objeto que implementa la operación TestLoopbackService serviceImplementation = new TestLoopbackService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: TestLoopback]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestParser")) { // SERVICIO: TestParser // Parámetro de entrada al servicio org.qualipso.advdoc.ws.client.storage.beans.TestParser inbean = new org.qualipso.advdoc.ws.client.storage.beans.TestParser(); inbean.fromJSON(input.toString()); // Invocar el método beforeService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action); } // Parámetro de salida del servicio org.qualipso.advdoc.ws.client.storage.beans.TestParser outbean = new org.qualipso.advdoc.ws.client.storage.beans.TestParser(); // Crear un objeto que implementa la operación TestParserService serviceImplementation = new TestParserService(); // Invocar la implementación de la operación Throwable applicationException = serviceImplementation.executeImpl(this, request, response, inbean, outbean); // Si ha ocurrido una excepción, enviarla al cliente if (applicationException != null) { // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException); output = response.getWriter(); if (applicationException instanceof TdiServiceException) { sendError(output, (TdiServiceException) applicationException); } else { String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false); String rc = "\n"; sendError( output, new TdiServiceException( 1, "." + rc + "[Operation: TestParser]" + rc + inputBean + rc + ".", applicationException.getClass().getName() + ":" + applicationException.getMessage())); } return; } // Invocar el método afterService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterService(request, response, outbean, "QualiPSoStorage", action); } // Respuesta output = response.getWriter(); // Bean de salida String output_str = outbean.toJSON(false); // Invocar el método afterParse() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].afterParse(request, response, output_str.toString()); } // Enviar la respuesta output.println(output_str); // Invocar el método endService() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].endService(request, response); } } else { throw new Exception(getClass().getName() + ".service() Operación " + action + " no válida"); } } catch (ServletException e) { // Ha ocurrido un error en los filtros // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(e); new es.tid.frawa.common.TdiFrawaTraceListener().trace(e); // Enviar <Fault> al cliente if (output == null) { output = response.getWriter(); } TdiServiceException se = new TdiServiceException(-1, "Filter exception", e.getMessage()); sendError(output, se); } catch (Throwable t) { // Invocar el método onException() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].onException(request, response, t, "QualiPSoStorage", action); } // Traza // new es.tid.frawa.common.TdiFrawaTraceListener().trace(t); new es.tid.frawa.common.TdiFrawaTraceListener().trace(t); // Elevar una ServletException throw new ServletException( getClass().getName() + ".service() Server Exception: " + t.getClass().getName() + " -> " + t.getMessage()); // if (output == null) { // output = response.getWriter(); // } // TdiServiceException se = new TdiServiceException(-2,t.getClass().getName(),t.getMessage()); // sendError(output,se); } finally { // Invocar el método onFinally() de los filtros for (int i = 0; i < filters.length; i++) { filters[i].onFinally(request, response, "QualiPSoStorage", action); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InetAddress serverIp = null; Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); String hostname = "", clientIp = "", userAgent = ""; try { serverIp = InetAddress.getLocalHost(); hostname = serverIp.getHostName(); clientIp = request.getHeader("X-FORWARDED-FOR"); if (clientIp == null) { clientIp = request.getRemoteAddr(); } userAgent = request.getHeader("user-agent"); } catch (UnknownHostException e) { e.printStackTrace(); } response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Sample Application Page</title>"); writer.println("</head>"); writer.println("<body bgcolor=white>"); writer.println("<table border=\"0\">"); writer.println("<tr>"); writer.println("<td>"); writer.println("<h1>Sample Application</h1>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); // writer.println("Server IP address: <strong>" + serverIp.getHostAddress() + // "</strong>"); writer.println("Server IP addresses: <strong>"); while (interfaces.hasMoreElements()) { NetworkInterface n = (NetworkInterface) interfaces.nextElement(); Enumeration inetAddresses = n.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = (InetAddress) inetAddresses.nextElement(); if (address.getHostAddress().substring(0, 6).compareTo("10.42.") == 0) writer.println(address.getHostAddress() + " "); } } writer.println("</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Server Hostname: <strong>" + hostname + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Your current IP address: <strong>" + clientIp + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Your current User-Agent: <strong>" + userAgent + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("</table>"); writer.println("</body>"); writer.println("</html>"); }