/** * @param req The request. * @return The query string of the request in its raw (not URI-encoded) form. This is suitable for * passing as the 'query' parameter to one of the multi-argument {@link URI} constructors. */ private static String getQueryString(HttpServletRequest req) throws UnsupportedEncodingException { StringBuilder buf = new StringBuilder(); Map<String, String[]> params = req.getParameterMap(); if (params.size() == 0) return null; for (Entry<String, String[]> entry : params.entrySet()) { String name = entry.getKey(); String[] values = entry.getValue(); if (values.length == 0) { buf.append("&").append(name); } else { for (String value : values) { buf.append("&").append(name).append("=").append(value); } } } return buf.substring(1); }
static { CONTENT_TYPES.put(ContentType.HTTP, Response.HTTP); CONTENT_TYPES.put(ContentType.MULTIPART, Response.MULTIPART); CONTENT_TYPES.put(ContentType.XML, Response.XML); for (final Entry<ContentType, String> entry : CONTENT_TYPES.entrySet()) TYPE_CONTENTS.put(entry.getValue(), entry.getKey()); }
/** * 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()); } }
/** * Parses HTTP parameters in an appropriate format and return back map of values to predefined * list of names. * * @param req Request. * @return Map of parsed parameters. */ @SuppressWarnings({"unchecked"}) private Map<String, Object> parameters(ServletRequest req) { Map<String, String[]> params = req.getParameterMap(); if (F.isEmpty(params)) return Collections.emptyMap(); Map<String, Object> map = U.newHashMap(params.size()); for (Map.Entry<String, String[]> entry : params.entrySet()) map.put(entry.getKey(), parameter(entry.getValue())); return map; }
/** * Returns all query parameters. * * @return parameters */ public Map<String, String[]> params() { final Map<String, String[]> params = new HashMap<String, String[]>(); final Map<?, ?> map = req.getParameterMap(); for (final Entry<?, ?> s : map.entrySet()) { final String key = s.getKey().toString(); final String[] vals = s.getValue() instanceof String[] ? (String[]) s.getValue() : new String[] {s.getValue().toString()}; params.put(key, vals); } return params; }
@Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (!path.equals(request.getRequestURI())) { return; } response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter out = null; try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); out = response.getWriter(); Map<String, Endpoint> endpointMap = tracker.getEndpointMap(); Map<String, Long> expirationMap = tracker.getExpirationMap(); out.println("Active sessions:"); out.println(); for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) { String key = ep.getKey(); out.print(ep.getKey()); out.print(" => "); out.print(ep.getValue()); Long expiration = expirationMap.get(key); if (expiration == null) { out.println(" (expiration unknown)"); } else { out.print(" (expires "); out.print(df.format(new Date(expiration))); out.println(")"); } } out.println(); out.println("Events:"); out.println(); for (EndpointEvent event : tracker.getEvents()) { out.print(df.format(new Date(event.getTimestamp()))); out.print(" "); out.print(event.getStatus().name()); out.print(" "); out.print(event.getConnectionId()); out.print(" "); out.print(event.getDetails()); out.println(); } } finally { try { if (out != null) { out.close(); } } catch (Throwable ignored) { } } baseRequest.setHandled(true); }
@Override public Enumeration<String> getAttributeNames() { return new Enumerator(attributes.entrySet()); }
/** * Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to * the given directory, and limiting the upload size to the specified length. If the content is * too large, an IOException is thrown. This constructor actually parses the * <tt>multipart/form-data</tt> and throws an IOException if there's any problem reading or * parsing the request. * * <p>To avoid file collisions, this constructor takes an implementation of the FileRenamePolicy * interface to allow a pluggable rename policy. * * @param request the servlet request. * @param saveDirectory the directory in which to save any uploaded files. * @param maxPostSize the maximum size of the POST content. * @param encoding the encoding of the response, such as ISO-8859-1 * @param policy a pluggable file rename policy * @exception IOException if the uploaded content is larger than <tt>maxPostSize</tt> or there's a * problem reading or parsing the request. */ public CosMultipartRequest( HttpServletRequest request, String saveDirectory, int maxPostSize, String encoding, FileRenamePolicy policy) throws IOException { // Sanity check values if (request == null) throw new IllegalArgumentException("request cannot be null"); if (saveDirectory == null) throw new IllegalArgumentException("saveDirectory cannot be null"); if (maxPostSize <= 0) { throw new IllegalArgumentException("maxPostSize must be positive"); } // Save the dir File dir = new File(saveDirectory); // Check saveDirectory is truly a directory if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory: " + saveDirectory); // Check saveDirectory is writable if (!dir.canWrite()) throw new IllegalArgumentException("Not writable: " + saveDirectory); // Parse the incoming multipart, storing files in the dir provided, // and populate the meta objects which describe what we found MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding); // Some people like to fetch query string parameters from // MultipartRequest, so here we make that possible. Thanks to // Ben Johnson, [email protected], for the idea. if (request.getQueryString() != null) { // Let HttpUtils create a name->String[] structure Map<String, String[]> queryParameters = RequestUtils.parseQueryString(request.getQueryString()); // For our own use, name it a name->Vector structure for (Entry<String, String[]> entry : queryParameters.entrySet()) { parameters.put(entry.getKey(), Arrays.asList(entry.getValue())); } } Part part; while ((part = parser.readNextPart()) != null) { String name = part.getName(); if (name == null) { throw new IOException("Malformed input: parameter name missing (known Opera 7 bug)"); } if (part.isParam()) { // It's a parameter part, add it to the vector of values ParamPart paramPart = (ParamPart) part; String value = paramPart.getStringValue(); List<String> existingValues = parameters.get(name); if (existingValues == null) { existingValues = new ArrayList<String>(); parameters.put(name, existingValues); } existingValues.add(value); } else if (part.isFile()) { // It's a file part FilePart filePart = (FilePart) part; String fileName = filePart.getFileName(); if (fileName != null) { filePart.setRenamePolicy(policy); // null policy is OK // The part actually contained a file filePart.writeTo(dir); files.put( name, new UploadedFile( dir.toString(), filePart.getFileName(), fileName, filePart.getContentType())); } else { // The field did not contain a file files.put(name, new UploadedFile(null, null, null, null)); } } } }
private void dnaCommand(HttpServletRequest req, DazzleResponse resp, DazzleDataSource dds) throws IOException, DataSourceException, ServletException, DazzleException { DazzleReferenceSource drs = (DazzleReferenceSource) dds; List segments = DazzleTools.getSegments(dds, req, resp); if (segments.size() == 0) { throw new DazzleException( DASStatus.STATUS_BAD_COMMAND_ARGUMENTS, "No segments specified for dna command"); } // Fetch and validate the requests. Map segmentResults = new HashMap(); for (Iterator i = segments.iterator(); i.hasNext(); ) { Segment seg = (Segment) i.next(); try { Sequence seq = drs.getSequence(seg.getReference()); if (seq.getAlphabet() != DNATools.getDNA()) { throw new DazzleException( DASStatus.STATUS_SERVER_ERROR, "Sequence " + seg.toString() + " is not in the DNA alphabet"); } if (seg.isBounded()) { if (seg.getMin() < 1 || seg.getMax() > seq.length()) { throw new DazzleException( DASStatus.STATUS_BAD_COORDS, "Segment " + seg.toString() + " doesn't fit sequence of length " + seq.length()); } } segmentResults.put(seg, seq); } catch (NoSuchElementException ex) { throw new DazzleException(DASStatus.STATUS_BAD_REFERENCE, ex); } catch (DataSourceException ex) { throw new DazzleException(DASStatus.STATUS_SERVER_ERROR, ex); } } // // Looks okay -- generate the response document // XMLWriter xw = resp.startDasXML("DASDNA", "dasdna.dtd"); try { xw.openTag("DASDNA"); for (Iterator i = segmentResults.entrySet().iterator(); i.hasNext(); ) { Map.Entry me = (Map.Entry) i.next(); Segment seg = (Segment) me.getKey(); Sequence seq = (Sequence) me.getValue(); xw.openTag("SEQUENCE"); xw.attribute("id", seg.getReference()); xw.attribute("version", drs.getLandmarkVersion(seg.getReference())); if (seg.isBounded()) { xw.attribute("start", "" + seg.getStart()); xw.attribute("stop", "" + seg.getStop()); } else { xw.attribute("start", "" + 1); xw.attribute("stop", "" + seq.length()); } SymbolList syms = seq; if (seg.isBounded()) { syms = syms.subList(seg.getMin(), seg.getMax()); } if (seg.isInverted()) { syms = DNATools.reverseComplement(syms); } xw.openTag("DNA"); xw.attribute("length", "" + syms.length()); for (int pos = 1; pos <= syms.length(); pos += 60) { int maxPos = Math.min(syms.length(), pos + 59); xw.println(syms.subStr(pos, maxPos)); } xw.closeTag("DNA"); xw.closeTag("SEQUENCE"); } xw.closeTag("DASDNA"); xw.close(); } catch (Exception ex) { throw new DazzleException(ex, "Error writing DNA document"); } }