Example usage for javax.servlet.http HttpServletRequest getHeaderNames

List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaderNames.

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:cz.metacentrum.perun.oauth.PerunAuthenticator.java

private AuthenticatedPrincipal setupPrincipal(HttpServletRequest req) {
    String extSourceLoaString = null;
    String extLogin = null;//from  ww  w . j a  v a  2  s. c  om
    String extSourceName = null;
    String extSourceType = null;
    int extSourceLoa = 0;
    Map<String, String> additionalInformations = new HashMap<String, String>();

    // If we have header Shib-Identity-Provider, then the user uses identity federation to authenticate
    if (req.getHeader("Shib-Identity-Provider") != null && !req.getHeader("Shib-Identity-Provider").isEmpty()) {
        extSourceName = (String) req.getHeader("Shib-Identity-Provider");
        extSourceType = ExtSourcesManager.EXTSOURCE_IDP;
        if (req.getHeader("loa") != null && !req.getHeader("loa").isEmpty()) {
            extSourceLoaString = req.getHeader("loa");
        } else {
            extSourceLoaString = "2";
        }
        // FIXME: find better place where do the operation with attributes from federation
        if (req.getHeader("eppn") != null && !req.getHeader("eppn").isEmpty()) {
            try {
                String eppn = new String(req.getHeader("eppn").getBytes("ISO-8859-1"));

                // Remove scope from the eppn attribute
                additionalInformations.put("eppnwoscope", eppn.replaceAll("(.*)@.*", "$1"));
            } catch (UnsupportedEncodingException e) {
                log.error("Cannot encode header eppn with value from ISO-8859-1.");
            }
        }
        if (req.getRemoteUser() != null && !req.getRemoteUser().isEmpty()) {
            extLogin = req.getRemoteUser();
        }
    }

    // EXT_SOURCE was defined in Apache configuration (e.g. Kerberos or Local)
    else if (req.getAttribute("EXTSOURCE") != null) {
        extSourceName = (String) req.getAttribute("EXTSOURCE");
        extSourceType = (String) req.getAttribute("EXTSOURCETYPE");
        extSourceLoaString = (String) req.getAttribute("EXTSOURCELOA");

        if (req.getRemoteUser() != null && !req.getRemoteUser().isEmpty()) {
            extLogin = req.getRemoteUser();
        } else if (req.getAttribute("ENV_REMOTE_USER") != null
                && !((String) req.getAttribute("ENV_REMOTE_USER")).isEmpty()) {
            extLogin = (String) req.getAttribute("ENV_REMOTE_USER");
        } else if (extSourceName.equals(ExtSourcesManager.EXTSOURCE_NAME_LOCAL)) {
            /** LOCAL EXTSOURCE **/
            // If ExtSource is LOCAL then generate REMOTE_USER name on the fly
            extLogin = Long.toString(System.currentTimeMillis());
        }
    }

    // X509 cert was used
    // Cert must be last since Apache asks for certificate everytime and fills cert properties even when Kerberos is in place.
    else if (extLogin == null && req.getAttribute("SSL_CLIENT_VERIFY") != null
            && ((String) req.getAttribute("SSL_CLIENT_VERIFY")).equals("SUCCESS")) {
        extSourceName = (String) req.getAttribute("SSL_CLIENT_I_DN");
        extSourceType = ExtSourcesManager.EXTSOURCE_X509;
        extSourceLoaString = (String) req.getAttribute("EXTSOURCELOA");
        extLogin = (String) req.getAttribute("SSL_CLIENT_S_DN");

        // Store X509
        additionalInformations.put("SSL_CLIENT_S_DN", (String) req.getAttribute("SSL_CLIENT_S_DN"));
        additionalInformations.put("dn", (String) req.getAttribute("SSL_CLIENT_S_DN"));

        // Get the X.509 certificate object
        X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");

        // Get the emails
        if (certs != null && certs.length > 0 && certs[0] != null) {
            String emails = "";

            Collection<List<?>> altNames;
            try {
                altNames = certs[0].getSubjectAlternativeNames();
                if (altNames != null) {
                    for (List<?> entry : altNames) {
                        if (((Integer) entry.get(0)) == 1) {
                            emails = (String) entry.get(1);
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                log.error("Error during parsing certificate {}", certs);
            }

            additionalInformations.put("mail", emails);

            // Get organization from the certificate
            String oRegExpPattern = "(o|O)(\\s)*=([^+,])*";
            Pattern oPattern = Pattern.compile(oRegExpPattern);
            Matcher oMatcher = oPattern.matcher(certs[0].getSubjectX500Principal().getName());
            if (oMatcher.find()) {
                String[] org = oMatcher.group().split("=");
                if (org[1] != null && !org[1].isEmpty()) {
                    additionalInformations.put("o", org[1]);
                }
            }
        }
    }

    // Read all headers and store them in additionalInformation
    String headerName = "";
    for (Enumeration<String> headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = (String) headerNames.nextElement();
        // Tomcat expects all headers are in ISO-8859-1
        try {
            additionalInformations.put(headerName,
                    new String(req.getHeader(headerName).getBytes("ISO-8859-1")));
        } catch (UnsupportedEncodingException e) {
            log.error("Cannot encode header {} with value from ISO-8859-1.", headerName,
                    req.getHeader(headerName));
        }
    }

    // extSourceLoa must be number, if any specified then set to 0
    if (extSourceLoaString == null || extSourceLoaString.isEmpty()) {
        extSourceLoa = 0;
    } else {
        try {
            extSourceLoa = Integer.parseInt(extSourceLoaString);
        } catch (NumberFormatException ex) {
            extSourceLoa = 0;
        }
    }

    if (StringUtils.isBlank(extLogin) || StringUtils.isBlank(extSourceName)) {
        throw new IllegalStateException("extLogin or extSourceName is empty.");
    }

    AuthenticatedPrincipal principal = new AuthenticatedPrincipal(extLogin);

    additionalInformations.put("extSourceName", extSourceName);
    additionalInformations.put("extSourceType", extSourceType);
    additionalInformations.put("extSourceLoa", String.valueOf(extSourceLoa));
    principal.setAttributes(additionalInformations);

    principal.setAdminPrincipal(true);

    return principal;
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {//from   w  w w  . ja va 2s  .  c  om
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.nuxeo.ecm.webapp.liveedit.LiveEditBootstrapHelper.java

/**
 * Creates the bootstrap file. It is called from the browser's addon. The URL composition tells the case and what to
 * create. The structure is depicted in the NXP-1881. Rux NXP-1959: add new tag on root level describing the action:
 * actionEdit, actionNew or actionFromTemplate.
 *
 * @return the bootstrap file content//from w  w w . ja va  2 s . c  om
 */
public void getBootstrap() throws IOException {
    String currentRepoID = documentManager.getRepositoryName();

    CoreSession session = documentManager;
    CoreSession templateSession = documentManager;
    try {
        if (repoID != null && !currentRepoID.equals(repoID)) {
            session = CoreInstance.openCoreSession(repoID);
        }

        if (templateRepoID != null && !currentRepoID.equals(templateRepoID)) {
            templateSession = CoreInstance.openCoreSession(templateRepoID);
        }

        DocumentModel doc = null;
        DocumentModel templateDoc = null;
        String filename = null;
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            // fetch the document to edit to get its mimetype and document
            // type
            doc = session.getDocument(new IdRef(docRef));
            docType = doc.getType();
            Blob blob = null;
            if (blobPropertyName != null) {
                blob = (Blob) doc.getPropertyValue(blobPropertyName);
                if (blob == null) {
                    throw new NuxeoException(
                            String.format("could not find blob to edit with property '%s'", blobPropertyName));
                }
            } else {
                blob = (Blob) doc.getProperty(schema, blobField);
                if (blob == null) {
                    throw new NuxeoException(String.format(
                            "could not find blob to edit with schema '%s' and field '%s'", schema, blobField));
                }
            }
            mimetype = blob.getMimeType();
            if (filenamePropertyName != null) {
                filename = (String) doc.getPropertyValue(filenamePropertyName);
            } else {
                filename = (String) doc.getProperty(schema, filenameField);
            }
        } else if (ACTION_CREATE_DOCUMENT.equals(action)) {
            // creating a new document all parameters are read from the
            // request parameters
        } else if (ACTION_CREATE_DOCUMENT_FROM_TEMPLATE.equals(action)) {
            // fetch the template blob to get its mimetype
            templateDoc = templateSession.getDocument(new IdRef(templateDocRef));
            Blob blob = (Blob) templateDoc.getProperty(templateSchema, templateBlobField);
            if (blob == null) {
                throw new NuxeoException(
                        String.format("could not find template blob with schema '%s' and field '%s'",
                                templateSchema, templateBlobField));
            }
            mimetype = blob.getMimeType();
            // leave docType from the request query parameter
        } else {
            throw new NuxeoException(String.format(
                    "action '%s' is not a valid LiveEdit action: should be one of '%s', '%s' or '%s'", action,
                    ACTION_CREATE_DOCUMENT, ACTION_CREATE_DOCUMENT_FROM_TEMPLATE, ACTION_EDIT_DOCUMENT));
        }

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        Element root = DocumentFactory.getInstance().createElement(liveEditTag);
        root.addNamespace("", XML_LE_NAMESPACE);
        // RUX NXP-1959: action id
        Element actionInfo = root.addElement(actionSelectorTag);
        actionInfo.setText(action);

        // Document related informations
        Element docInfo = root.addElement(documentTag);
        addTextElement(docInfo, docRefTag, docRef);
        Element docPathT = docInfo.addElement(docPathTag);
        Element docTitleT = docInfo.addElement(docTitleTag);
        if (doc != null) {
            docPathT.setText(doc.getPathAsString());
            docTitleT.setText(doc.getTitle());
        }
        addTextElement(docInfo, docRepositoryTag, repoID);

        addTextElement(docInfo, docSchemaNameTag, schema);
        addTextElement(docInfo, docFieldNameTag, blobField);
        addTextElement(docInfo, docBlobFieldNameTag, blobField);
        Element docFieldPathT = docInfo.addElement(docfieldPathTag);
        Element docBlobFieldPathT = docInfo.addElement(docBlobFieldPathTag);
        if (blobPropertyName != null) {
            // FIXME AT: NXP-2306: send blobPropertyName correctly (?)
            docFieldPathT.setText(blobPropertyName);
            docBlobFieldPathT.setText(blobPropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFieldPathT.setText(schema + ':' + blobField);
                docBlobFieldPathT.setText(schema + ':' + blobField);
            }
        }
        addTextElement(docInfo, docFilenameFieldNameTag, filenameField);
        Element docFilenameFieldPathT = docInfo.addElement(docFilenameFieldPathTag);
        if (filenamePropertyName != null) {
            docFilenameFieldPathT.setText(filenamePropertyName);
        } else {
            if (schema != null && blobField != null) {
                docFilenameFieldPathT.setText(schema + ':' + filenameField);
            }
        }

        addTextElement(docInfo, docfileNameTag, filename);
        addTextElement(docInfo, docTypeTag, docType);
        addTextElement(docInfo, docMimetypeTag, mimetype);
        addTextElement(docInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element docFileAuthorizedExtensions = docInfo.addElement(docFileAuthorizedExtensionsTag);
        List<String> authorizedExtensions = getFileExtensions(mimetype);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(docFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        Element docIsVersionT = docInfo.addElement(docIsVersionTag);
        Element docIsLockedT = docInfo.addElement(docIsLockedTag);
        if (ACTION_EDIT_DOCUMENT.equals(action)) {
            docIsVersionT.setText(Boolean.toString(doc.isVersion()));
            docIsLockedT.setText(Boolean.toString(doc.isLocked()));
        }

        // template information for ACTION_CREATE_DOCUMENT_FROM_TEMPLATE

        Element templateDocInfo = root.addElement(templateDocumentTag);
        addTextElement(templateDocInfo, docRefTag, templateDocRef);
        docPathT = templateDocInfo.addElement(docPathTag);
        docTitleT = templateDocInfo.addElement(docTitleTag);
        if (templateDoc != null) {
            docPathT.setText(templateDoc.getPathAsString());
            docTitleT.setText(templateDoc.getTitle());
        }
        addTextElement(templateDocInfo, docRepositoryTag, templateRepoID);
        addTextElement(templateDocInfo, docSchemaNameTag, templateSchema);
        addTextElement(templateDocInfo, docFieldNameTag, templateBlobField);
        addTextElement(templateDocInfo, docBlobFieldNameTag, templateBlobField);
        docFieldPathT = templateDocInfo.addElement(docfieldPathTag);
        docBlobFieldPathT = templateDocInfo.addElement(docBlobFieldPathTag);
        if (templateSchema != null && templateBlobField != null) {
            docFieldPathT.setText(templateSchema + ":" + templateBlobField);
            docBlobFieldPathT.setText(templateSchema + ":" + templateBlobField);
        }
        addTextElement(templateDocInfo, docMimetypeTag, mimetype);
        addTextElement(templateDocInfo, docFileExtensionTag, getFileExtension(mimetype));

        Element templateFileAuthorizedExtensions = templateDocInfo.addElement(docFileAuthorizedExtensionsTag);
        if (authorizedExtensions != null) {
            for (String extension : authorizedExtensions) {
                addTextElement(templateFileAuthorizedExtensions, docFileAuthorizedExtensionTag, extension);
            }
        }

        // Browser request related informations
        Element requestInfo = root.addElement(requestInfoTag);
        Cookie[] cookies = request.getCookies();
        Element cookiesT = requestInfo.addElement(requestCookiesTag);
        for (Cookie cookie : cookies) {
            Element cookieT = cookiesT.addElement(requestCookieTag);
            cookieT.addAttribute("name", cookie.getName());
            cookieT.setText(cookie.getValue());
        }
        Element headersT = requestInfo.addElement(requestHeadersTag);
        Enumeration hEnum = request.getHeaderNames();
        while (hEnum.hasMoreElements()) {
            String hName = (String) hEnum.nextElement();
            if (!hName.equalsIgnoreCase("cookie")) {
                Element headerT = headersT.addElement(requestHeaderTag);
                headerT.addAttribute("name", hName);
                headerT.setText(request.getHeader(hName));
            }
        }
        addTextElement(requestInfo, requestBaseURLTag, BaseURL.getBaseURL(request));

        // User related informations
        String username = context.getExternalContext().getUserPrincipal().getName();
        Element userInfo = root.addElement(userInfoTag);
        addTextElement(userInfo, userNameTag, username);
        addTextElement(userInfo, userPasswordTag, "");
        addTextElement(userInfo, userTokenTag, "");
        addTextElement(userInfo, userLocaleTag, context.getViewRoot().getLocale().toString());
        // Rux NXP-1882: the wsdl locations
        String baseUrl = BaseURL.getBaseURL(request);
        Element wsdlLocations = root.addElement(wsdlLocationsTag);
        Element wsdlAccessWST = wsdlLocations.addElement(wsdlAccessWebServiceTag);
        wsdlAccessWST.setText(baseUrl + "webservices/nuxeoAccess?wsdl");
        Element wsdlEEWST = wsdlLocations.addElement(wsdlLEWebServiceTag);
        wsdlEEWST.setText(baseUrl + "webservices/nuxeoLEWS?wsdl");

        // Server related informations
        Element serverInfo = root.addElement(serverInfoTag);
        Element serverVersionT = serverInfo.addElement(serverVersionTag);
        serverVersionT.setText("5.1"); // TODO: use a buildtime generated
        // version tag instead

        // Client related informations
        Element editId = root.addElement(editIdTag);
        editId.setText(getEditId(doc, session, username));

        // serialize bootstrap XML document in the response
        Document xmlDoc = DocumentFactory.getInstance().createDocument();
        xmlDoc.setRootElement(root);
        response.setContentType("text/xml; charset=UTF-8");

        // use a formatter to make it easier to debug live edit client
        // implementations
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(response.getOutputStream(), format);
        writer.write(xmlDoc);

        response.flushBuffer();
        context.responseComplete();
    } finally {
        if (session != null && session != documentManager) {
            session.close();
        }
        if (templateSession != null && templateSession != documentManager) {
            templateSession.close();
        }
    }
}

From source file:org.apache.nifi.processors.standard.servlets.ListenHTTPServlet.java

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final ProcessContext context = processContext;

    ProcessSessionFactory sessionFactory;
    do {/*from  w ww.  ja  va  2 s . c o  m*/
        sessionFactory = sessionFactoryHolder.get();
        if (sessionFactory == null) {
            try {
                Thread.sleep(10);
            } catch (final InterruptedException e) {
            }
        }
    } while (sessionFactory == null);

    final ProcessSession session = sessionFactory.createSession();
    FlowFile flowFile = null;
    String holdUuid = null;
    String foundSubject = null;
    try {
        final long n = filesReceived.getAndIncrement() % FILES_BEFORE_CHECKING_DESTINATION_SPACE;
        if (n == 0 || !spaceAvailable.get()) {
            if (context.getAvailableRelationships().isEmpty()) {
                spaceAvailable.set(false);
                if (logger.isDebugEnabled()) {
                    logger.debug("Received request from " + request.getRemoteHost()
                            + " but no space available; Indicating Service Unavailable");
                }
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            } else {
                spaceAvailable.set(true);
            }
        }
        response.setHeader("Content-Type", MediaType.TEXT_PLAIN);

        final boolean contentGzipped = Boolean.parseBoolean(request.getHeader(GZIPPED_HEADER));

        final X509Certificate[] certs = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        foundSubject = DEFAULT_FOUND_SUBJECT;
        if (certs != null && certs.length > 0) {
            for (final X509Certificate cert : certs) {
                foundSubject = cert.getSubjectDN().getName();
                if (authorizedPattern.matcher(foundSubject).matches()) {
                    break;
                } else {
                    logger.warn("Rejecting transfer attempt from " + foundSubject
                            + " because the DN is not authorized, host=" + request.getRemoteHost());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "not allowed based on dn");
                    return;
                }
            }
        }

        final String destinationVersion = request.getHeader(PROTOCOL_VERSION_HEADER);
        Integer protocolVersion = null;
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion);
            } catch (final NumberFormatException e) {
                // Value was invalid. Treat as if the header were missing.
            }
        }

        final boolean destinationIsLegacyNiFi = (protocolVersion == null);
        final boolean createHold = Boolean.parseBoolean(request.getHeader(FLOWFILE_CONFIRMATION_HEADER));
        final String contentType = request.getContentType();

        final InputStream unthrottled = contentGzipped ? new GZIPInputStream(request.getInputStream())
                : request.getInputStream();

        final InputStream in = (streamThrottler == null) ? unthrottled
                : streamThrottler.newThrottledInputStream(unthrottled);

        if (logger.isDebugEnabled()) {
            logger.debug("Received request from " + request.getRemoteHost() + ", createHold=" + createHold
                    + ", content-type=" + contentType + ", gzip=" + contentGzipped);
        }

        final AtomicBoolean hasMoreData = new AtomicBoolean(false);
        final FlowFileUnpackager unpackager;
        if (APPLICATION_FLOW_FILE_V3.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV3();
        } else if (APPLICATION_FLOW_FILE_V2.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV2();
        } else if (APPLICATION_FLOW_FILE_V1.equals(contentType)) {
            unpackager = new FlowFileUnpackagerV1();
        } else {
            unpackager = null;
        }

        final Set<FlowFile> flowFileSet = new HashSet<>();

        do {
            final long startNanos = System.nanoTime();
            final Map<String, String> attributes = new HashMap<>();
            flowFile = session.create();
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(final OutputStream rawOut) throws IOException {
                    try (final BufferedOutputStream bos = new BufferedOutputStream(rawOut, 65536)) {
                        if (unpackager == null) {
                            IOUtils.copy(in, bos);
                            hasMoreData.set(false);
                        } else {
                            attributes.putAll(unpackager.unpackageFlowFile(in, bos));

                            if (destinationIsLegacyNiFi) {
                                if (attributes.containsKey("nf.file.name")) {
                                    // for backward compatibility with old nifi...
                                    attributes.put(CoreAttributes.FILENAME.key(),
                                            attributes.remove("nf.file.name"));
                                }

                                if (attributes.containsKey("nf.file.path")) {
                                    attributes.put(CoreAttributes.PATH.key(),
                                            attributes.remove("nf.file.path"));
                                }
                            }

                            hasMoreData.set(unpackager.hasMoreData());
                        }
                    }
                }
            });

            final long transferNanos = System.nanoTime() - startNanos;
            final long transferMillis = TimeUnit.MILLISECONDS.convert(transferNanos, TimeUnit.NANOSECONDS);

            // put metadata on flowfile
            final String nameVal = request.getHeader(CoreAttributes.FILENAME.key());
            if (StringUtils.isNotBlank(nameVal)) {
                attributes.put(CoreAttributes.FILENAME.key(), nameVal);
            }

            // put arbitrary headers on flow file
            for (Enumeration<String> headerEnum = request.getHeaderNames(); headerEnum.hasMoreElements();) {
                String headerName = headerEnum.nextElement();
                if (headerPattern != null && headerPattern.matcher(headerName).matches()) {
                    String headerValue = request.getHeader(headerName);
                    attributes.put(headerName, headerValue);
                }
            }

            String sourceSystemFlowFileIdentifier = attributes.get(CoreAttributes.UUID.key());
            if (sourceSystemFlowFileIdentifier != null) {
                sourceSystemFlowFileIdentifier = "urn:nifi:" + sourceSystemFlowFileIdentifier;

                // If we receveied a UUID, we want to give the FlowFile a new UUID and register the sending system's
                // identifier as the SourceSystemFlowFileIdentifier field in the Provenance RECEIVE event
                attributes.put(CoreAttributes.UUID.key(), UUID.randomUUID().toString());
            }

            flowFile = session.putAllAttributes(flowFile, attributes);
            session.getProvenanceReporter().receive(flowFile, request.getRequestURL().toString(),
                    sourceSystemFlowFileIdentifier, "Remote DN=" + foundSubject, transferMillis);
            flowFile = session.putAttribute(flowFile, "restlistener.remote.source.host",
                    request.getRemoteHost());
            flowFile = session.putAttribute(flowFile, "restlistener.remote.user.dn", foundSubject);
            flowFileSet.add(flowFile);

            if (holdUuid == null) {
                holdUuid = flowFile.getAttribute(CoreAttributes.UUID.key());
            }
        } while (hasMoreData.get());

        if (createHold) {
            String uuid = (holdUuid == null) ? UUID.randomUUID().toString() : holdUuid;

            if (flowFileMap.containsKey(uuid)) {
                uuid = UUID.randomUUID().toString();
            }

            final FlowFileEntryTimeWrapper wrapper = new FlowFileEntryTimeWrapper(session, flowFileSet,
                    System.currentTimeMillis());
            FlowFileEntryTimeWrapper previousWrapper;
            do {
                previousWrapper = flowFileMap.putIfAbsent(uuid, wrapper);
                if (previousWrapper != null) {
                    uuid = UUID.randomUUID().toString();
                }
            } while (previousWrapper != null);

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            final String ackUri = "/" + basePath + "/holds/" + uuid;
            response.addHeader(LOCATION_HEADER_NAME, ackUri);
            response.addHeader(LOCATION_URI_INTENT_NAME, LOCATION_URI_INTENT_VALUE);
            response.getOutputStream().write(ackUri.getBytes("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Ingested {} from Remote Host: [{}] Port [{}] SubjectDN [{}]; placed hold on these {} files with ID {}",
                        new Object[] { flowFileSet, request.getRemoteHost(), request.getRemotePort(),
                                foundSubject, flowFileSet.size(), uuid });
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            logger.info(
                    "Received from Remote Host: [{}] Port [{}] SubjectDN [{}]; transferring to 'success' {}",
                    new Object[] { request.getRemoteHost(), request.getRemotePort(), foundSubject, flowFile });

            session.transfer(flowFileSet, ListenHTTP.RELATIONSHIP_SUCCESS);
            session.commit();
        }
    } catch (final Throwable t) {
        session.rollback();
        if (flowFile == null) {
            logger.error("Unable to receive file from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { request.getRemoteHost(), foundSubject, t });
        } else {
            logger.error("Unable to receive file {} from Remote Host: [{}] SubjectDN [{}] due to {}",
                    new Object[] { flowFile, request.getRemoteHost(), foundSubject, t });
        }
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
    }
}

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Show HTTP header information.//w w  w. ja  va  2s.  c o  m
 */
@SuppressWarnings("unchecked")
protected void showRequestInfo(HttpServletRequest req) {

    if (M_log.isDebugEnabled())
        M_log.debug("DefaultServlet Request Info");

    // Show generic info
    if (M_log.isDebugEnabled())
        M_log.debug("Encoding : " + req.getCharacterEncoding());
    if (M_log.isDebugEnabled())
        M_log.debug("Length : " + req.getContentLength());
    if (M_log.isDebugEnabled())
        M_log.debug("Type : " + req.getContentType());

    if (M_log.isDebugEnabled())
        M_log.debug("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("Protocol : " + req.getProtocol());
    if (M_log.isDebugEnabled())
        M_log.debug("Address : " + req.getRemoteAddr());
    if (M_log.isDebugEnabled())
        M_log.debug("Host : " + req.getRemoteHost());
    if (M_log.isDebugEnabled())
        M_log.debug("Scheme : " + req.getScheme());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Name : " + req.getServerName());
    if (M_log.isDebugEnabled())
        M_log.debug("Server Port : " + req.getServerPort());

    if (M_log.isDebugEnabled())
        M_log.debug("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getAttribute(attributeName).toString());
    }

    // Show HTTP info
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Header Info");

    if (M_log.isDebugEnabled())
        M_log.debug("Authentication Type : " + req.getAuthType());
    if (M_log.isDebugEnabled())
        M_log.debug("HTTP Method : " + req.getMethod());
    if (M_log.isDebugEnabled())
        M_log.debug("Path Info : " + req.getPathInfo());
    if (M_log.isDebugEnabled())
        M_log.debug("Path translated : " + req.getPathTranslated());
    if (M_log.isDebugEnabled())
        M_log.debug("Query string : " + req.getQueryString());
    if (M_log.isDebugEnabled())
        M_log.debug("Remote user : " + req.getRemoteUser());
    if (M_log.isDebugEnabled())
        M_log.debug("Requested session id : " + req.getRequestedSessionId());
    if (M_log.isDebugEnabled())
        M_log.debug("Request URI : " + req.getRequestURI());
    if (M_log.isDebugEnabled())
        M_log.debug("Context path : " + req.getContextPath());
    if (M_log.isDebugEnabled())
        M_log.debug("Servlet path : " + req.getServletPath());
    if (M_log.isDebugEnabled())
        M_log.debug("User principal : " + req.getUserPrincipal());
    if (M_log.isDebugEnabled())
        M_log.debug("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        if (M_log.isDebugEnabled())
            M_log.debug(req.getHeader(headerName));
    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//from   ww w.j  av  a 2 s .c  o m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.openqa.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {//from w  ww.  jav a 2  s.c  o m
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        response.addCookie(cookie);
    }

    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    pout.close();

    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Write/*from  ww w  . j a  v  a2  s.  c o m*/
 * 
 * @param req
 *            the HttpServletRequest object that contains the request the
 *            client made of the servlet
 * @param resp
 *            the HttpServletResponse object that contains the response the
 *            servlet returns to the client
 * @throws IOException
 *             if an input or output error occurs while the servlet is
 *             handling the PUT request
 * @throws ServletException
 *             if the request for the PUT cannot be handled
 */
@SuppressWarnings("unchecked")
public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream out = null;

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }
        logger.debug("S3ObjectRequest: " + or);

        CanonicalUser requestor = or.getRequestor();

        if (or.getKey() != null) {
            String value;
            long contentLength;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            DigestOutputStream digestOutputStream = null;
            S3Object oldS3Object = null;
            S3Object s3Object;
            StorageService storageService;
            Bucket bucket;
            String bucketName = or.getBucket();
            String key = or.getKey();

            if (!isValidKey(key)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong");
                return;
            }

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;
                s3Object = storageService.load(bucketName, key);

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }

                acp = s3Object.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                s3Object.setAcp(acp);

                storageService.store(s3Object);
            } else {
                // make sure requestor can "WRITE" to the bucket
                try {
                    bucket = storageService.loadBucket(bucketName);
                    bucket.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    oldS3Object = storageService.load(bucket.getName(), key);
                } catch (DataRetrievalFailureException e) {
                    // ignore
                }

                // create a new S3Object for this request to store an object
                try {
                    s3Object = storageService.createS3Object(bucket, key, requestor);
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                out = s3Object.getOutputStream();
                digestOutputStream = new DigestOutputStream(out, messageDigest);

                // Used instead of req.getContentLength(); because Amazon
                // limit is 5 gig, which is bigger than an int
                value = req.getHeader("Content-Length");
                if (value == null) {
                    resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength");
                    return;
                }
                contentLength = Long.valueOf(value).longValue();

                if (contentLength > 5368709120L) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge");
                    return;
                }

                long written = 0;
                int count;
                byte[] b = new byte[4096];
                ServletInputStream in = req.getInputStream();

                while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) {
                    digestOutputStream.write(b, 0, count);
                    written += count;
                }
                digestOutputStream.flush();

                if (written != contentLength) {
                    // transmission truncated
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (digestOutputStream != null) {
                        digestOutputStream.close();
                        digestOutputStream = null;
                    }
                    // clean up
                    storageService.remove(s3Object);
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody");
                    return;
                }

                s3Object.setContentDisposition(req.getHeader("Content-Disposition"));
                s3Object.setContentLength(contentLength);
                s3Object.setContentMD5(req.getHeader("Content-MD5"));
                value = req.getContentType();
                logger.debug("Put - Content-Type: " + value);
                if (value == null) {
                    value = S3Object.DEFAULT_CONTENT_TYPE;
                }
                s3Object.setContentType(value);
                logger.debug("Put - get content-type: " + s3Object.getContentType());
                s3Object.setLastModified(System.currentTimeMillis());

                // metadata
                int prefixLength = HEADER_PREFIX_USER_META.length();
                String name;
                for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
                    String headerName = (String) headerNames.nextElement();
                    if (headerName.startsWith(HEADER_PREFIX_USER_META)) {
                        name = headerName.substring(prefixLength).toLowerCase();
                        for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) {
                            value = (String) headers.nextElement();
                            s3Object.addMetadata(name, value);
                        }
                    }
                }

                // calculate ETag, hex encoding of MD5
                value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest()));
                resp.setHeader("ETag", value);
                s3Object.setETag(value);

                grantCannedAccessPolicies(req, s3Object.getAcp(), requestor);

                // NOTE: This could be reengineered to have a two-phase
                // commit.
                if (oldS3Object != null) {
                    storageService.remove(oldS3Object);
                }
                storageService.store(s3Object);
            }
        } else if (or.getBucket() != null) {
            StorageService storageService;
            Bucket bucket;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;

                logger.debug("User is providing new ACP for bucket " + or.getBucket());

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                acp = bucket.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                bucket.setAcp(acp);

                logger.debug("Saving bucket ACP");
                logger.debug("ACP: " + Acp.encode(bucket.getAcp()));

                storageService.storeBucket(bucket);
            } else {
                // validate bucket
                String bucketName = or.getBucket();

                if (!isValidBucketName(bucketName)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName");
                    return;
                }

                try {
                    bucket = storageService.createBucket(bucketName, requestor);
                } catch (BucketAlreadyExistsException e) {
                    resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists");
                    return;
                }

                grantCannedAccessPolicies(req, bucket.getAcp(), requestor);

                storageService.storeBucket(bucket);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("Unable to use MD5", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError");
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:de.zib.scalaris.examples.wikipedia.bliki.WikiServlet.java

/**
 * Creates a {@link WikiPageBean} object with the rendered content of a
 * given revision.// ww  w. ja v  a  2s .c om
 * 
 * @param title
 *            the title of the article to render
 * @param result
 *            the revision to render (must be successful and contain a
 *            revision)
 * @param renderer
 *            the renderer to use (0=plain text, 1=Bliki)
 * @param request
 *            the request object
 * @param connection
 *            connection to the database
 * @param page
 *            the bean for the page (the rendered content will be added to
 *            this object)
 * @param noRedirect
 *            if <tt>true</tt>, a redirect will be shown as such, otherwise
 *            the content of the redirected page will be show
 * @param wikiModel
 *            the wiki model to use
 * @param topLevel
 *            if this function is called from inside
 *            {@link #renderRevision()}, this will be <tt>false</tt>,
 *            otherwise always use <tt>true</tt>
 */
private void renderRevision(final String title, final RevisionResult result, final int renderer,
        final HttpServletRequest request, final Connection connection, final WikiPageBean page,
        final boolean noRedirect, final MyWikiModel wikiModel, final boolean topLevel) {
    // set the page's contents according to the renderer used
    // (categories are included in the content string, so they only
    // need special handling the wiki renderer is used)
    NormalisedTitle titleN = NormalisedTitle.fromUnnormalised(title, namespace);
    wikiModel.setNamespaceName(namespace.getNamespaceByNumber(titleN.namespace));
    wikiModel.setPageName(titleN.title);
    if (renderer > 0) {
        String mainText = wikiModel.renderPageWithCache(result.revision.unpackedText());
        if (titleN.namespace.equals(MyNamespace.CATEGORY_NAMESPACE_KEY)) {
            ValueResult<List<NormalisedTitle>> catPagesResult = getPagesInCategory(connection, titleN);
            page.addStats(catPagesResult.stats);
            page.getInvolvedKeys().addAll(catPagesResult.involvedKeys);
            if (catPagesResult.success) {
                final TreeSet<String> subCategories = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
                final TreeSet<String> categoryPages = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
                final List<NormalisedTitle> tplPages = new ArrayList<NormalisedTitle>(
                        catPagesResult.value.size());

                for (NormalisedTitle pageInCat : catPagesResult.value) {
                    if (pageInCat.namespace.equals(MyNamespace.CATEGORY_NAMESPACE_KEY)) {
                        subCategories.add(pageInCat.title);
                    } else if (pageInCat.namespace.equals(MyNamespace.TEMPLATE_NAMESPACE_KEY)) {
                        tplPages.add(pageInCat);
                        categoryPages.add(pageInCat.denormalise(namespace));
                    } else {
                        categoryPages.add(pageInCat.denormalise(namespace));
                    }
                }
                if (!tplPages.isEmpty()) {
                    // all pages using a template are in the category of the template, too
                    ValueResult<List<NormalisedTitle>> tplResult = getPagesInTemplates(connection, tplPages,
                            title);
                    page.addStats(tplResult.stats);
                    page.getInvolvedKeys().addAll(tplResult.involvedKeys);
                    if (tplResult.success) {
                        for (NormalisedTitle pageInTplOfCat : tplResult.value) {
                            if (pageInTplOfCat.namespace.equals(MyNamespace.CATEGORY_NAMESPACE_KEY)) {
                                subCategories.add(pageInTplOfCat.title);
                            } else if (pageInTplOfCat.namespace.equals(MyNamespace.TEMPLATE_NAMESPACE_KEY)) {
                                // TODO: go into recursion?! -> for now, just add the template
                                //                                  tplPages.add(pageInTplOfCat);
                                categoryPages.add(pageInTplOfCat.denormalise(namespace));
                            } else {
                                categoryPages.add(pageInTplOfCat.denormalise(namespace));
                            }
                        }
                    } else {
                        if (tplResult.connect_failed) {
                            setParam_error(request, "ERROR: DB connection failed");
                        } else {
                            setParam_error(request, "ERROR: template page lists unavailable");
                        }
                        addToParam_notice(request, "error getting pages using templates: " + tplResult.message);
                    }
                }
                page.setSubCategories(subCategories);
                page.setCategoryPages(categoryPages);
            } else {
                if (catPagesResult.connect_failed) {
                    setParam_error(request, "ERROR: DB connection failed");
                } else {
                    setParam_error(request, "ERROR: category page list unavailable");
                }
                addToParam_notice(request, "error getting category pages: " + catPagesResult.message);
            }
        }
        page.setTitle(title);
        page.setVersion(result.revision.getId());
        String redirectedPageName = wikiModel.getRedirectLink();
        if (redirectedPageName != null) {
            if (noRedirect) {
                if (topLevel) {
                    page.setContentSub("Redirect page");
                }
                mainText = wikiModel.renderRedirectPage(redirectedPageName);
                page.setDate(Revision.stringToCalendar(result.revision.getTimestamp()));
            } else {
                final String safeTitle = StringEscapeUtils.escapeHtml(title);
                final String redirectUrl = wikiModel.getWikiBaseURL().replace("${title}", title);
                page.setContentSub("(Redirected from <a href=\"" + redirectUrl + "&redirect=no\" title=\""
                        + safeTitle + "\">" + title + "</a>)");
                // add the content from the page directed to:
                wikiModel.tearDown();
                wikiModel.setUp();

                RevisionResult redirectResult = getRevision(connection, redirectedPageName, namespace);
                page.addStats(redirectResult.stats);
                page.getInvolvedKeys().addAll(redirectResult.involvedKeys);
                if (redirectResult.success) {
                    renderRevision(redirectedPageName, redirectResult, renderer, request, connection, page,
                            true, wikiModel, false);
                    return;
                } else {
                    // non-existing/non-successful page is like redirect=no
                    mainText = wikiModel.renderRedirectPage(redirectedPageName);
                    page.setDate(Revision.stringToCalendar(result.revision.getTimestamp()));
                }
            }
        } else {
            setSubPageNav(title, page, wikiModel);
        }
        page.setPage(mainText);
        page.setCategories(wikiModel.getCategories().keySet());
        page.addStats(wikiModel.getStats());
        page.getInvolvedKeys().addAll(wikiModel.getInvolvedKeys());
    } else if (renderer == 0) {
        // for debugging, show all parameters:
        StringBuilder sb = new StringBuilder();
        for (Enumeration<?> req_pars = request.getParameterNames(); req_pars.hasMoreElements();) {
            String element = (String) req_pars.nextElement();
            sb.append(element + " = ");
            sb.append(request.getParameter(element) + "\n");
        }
        sb.append("\n\n");
        for (Enumeration<?> headers = request.getHeaderNames(); headers.hasMoreElements();) {
            String element = (String) headers.nextElement();
            sb.append(element + " = ");
            sb.append(request.getHeader(element) + "\n");
        }
        page.setPage("<p>WikiText:<pre>" + StringEscapeUtils.escapeHtml(result.revision.unpackedText())
                + "</pre></p>" + "<p>Version:<pre>"
                + StringEscapeUtils.escapeHtml(String.valueOf(result.revision.getId())) + "</pre></p>"
                + "<p>Last change:<pre>" + StringEscapeUtils.escapeHtml(result.revision.getTimestamp())
                + "</pre></p>" + "<p>Request Parameters:<pre>" + StringEscapeUtils.escapeHtml(sb.toString())
                + "</pre></p>");
        page.setTitle(title);
        page.setVersion(result.revision.getId());
        page.setDate(Revision.stringToCalendar(result.revision.getTimestamp()));
    }
    page.setNotice(getParam_notice(request));
    page.setError(getParam_error(request));
    page.setWikiTitle(siteinfo.getSitename());
    page.setWikiNamespace(namespace);
}