Example usage for javax.servlet.http HttpServletRequest getScheme

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

Introduction

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

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser.java

public static void parse(AuthenticationSession moasession, String target, String oaURL, String bkuURL,
        String templateURL, String useMandate, String ccc, String module, String action, HttpServletRequest req)
        throws WrongParametersException, MOAIDException {

    String targetFriendlyName = null;

    //       String sso = req.getParameter(PARAM_SSO);

    // escape parameter strings
    target = StringEscapeUtils.escapeHtml(target);
    //oaURL = StringEscapeUtils.escapeHtml(oaURL);
    bkuURL = StringEscapeUtils.escapeHtml(bkuURL);
    templateURL = StringEscapeUtils.escapeHtml(templateURL);
    useMandate = StringEscapeUtils.escapeHtml(useMandate);
    ccc = StringEscapeUtils.escapeHtml(ccc);
    //       sso = StringEscapeUtils.escapeHtml(sso);

    // check parameter

    //pvp2.x can use general identifier (equals oaURL in SAML1)
    //      if (!ParamValidatorUtils.isValidOA(oaURL))
    //           throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12");

    if (!ParamValidatorUtils.isValidUseMandate(useMandate))
        throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12");
    if (!ParamValidatorUtils.isValidCCC(ccc))
        throw new WrongParametersException("StartAuthentication", PARAM_CCC, "auth.12");
    //       if (!ParamValidatorUtils.isValidUseMandate(sso))
    //            throw new WrongParametersException("StartAuthentication", PARAM_SSO, "auth.12");

    //check UseMandate flag
    String useMandateString = null;
    boolean useMandateBoolean = false;
    if ((useMandate != null) && (useMandate.compareTo("") != 0)) {
        useMandateString = useMandate;//from   ww w  . j  a va  2  s.  co m
    } else {
        useMandateString = "false";
    }

    if (useMandateString.compareToIgnoreCase("true") == 0)
        useMandateBoolean = true;
    else
        useMandateBoolean = false;

    moasession.setUseMandate(useMandateString);

    //load OnlineApplication configuration
    OAAuthParameter oaParam;
    if (moasession.getPublicOAURLPrefix() != null) {
        Logger.debug("Loading OA parameters for PublicURLPrefix: " + moasession.getPublicOAURLPrefix());
        oaParam = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());

        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() });

    } else {
        oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(oaURL);

        if (oaParam == null)
            throw new AuthenticationException("auth.00", new Object[] { oaURL });

        // get target and target friendly name from config
        String targetConfig = oaParam.getTarget();
        String targetFriendlyNameConfig = oaParam.getTargetFriendlyName();

        if (StringUtils.isEmpty(targetConfig)
                || (module.equals(SAML1Protocol.PATH) && !StringUtils.isEmpty(target))) {
            //INFO: ONLY SAML1 legacy mode
            // if SAML1 is used and target attribute is given in request
            // use requested target
            // check target parameter
            if (!ParamValidatorUtils.isValidTarget(target)) {
                Logger.error("Selected target is invalid. Using target: " + target);
                throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12");
            }

        } else {
            // use target from config                
            target = targetConfig;
            targetFriendlyName = targetFriendlyNameConfig;
        }

        //         //check useSSO flag
        //         String useSSOString = null;
        //         boolean useSSOBoolean = false;
        //         if ((sso != null) && (sso.compareTo("") != 0)) {
        //            useSSOString = sso;
        //         } else {
        //            useSSOString = "false";
        //         }
        //
        //         if (useSSOString.compareToIgnoreCase("true") == 0)
        //            useSSOBoolean = true;
        //         else
        //            useSSOBoolean = false;

        //moasession.setSsoRequested(useSSOBoolean);
        moasession.setSsoRequested(true && oaParam.useSSO()); //make always SSO if OA requested it!!!!

        //Validate BKU URI
        List<String> allowedbkus = oaParam.getBKUURL();
        allowedbkus.addAll(AuthConfigurationProvider.getInstance().getDefaultBKUURLs());
        if (!ParamValidatorUtils.isValidBKUURI(bkuURL, allowedbkus))
            throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12");

        moasession.setBkuURL(bkuURL);

        if ((!oaParam.getBusinessService())) {
            if (isEmpty(target))
                throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.05");

        } else {
            if (useMandateBoolean) {
                Logger.error("Online-Mandate Mode for business application not supported.");
                throw new AuthenticationException("auth.17", null);
            }
            target = null;
            targetFriendlyName = null;
        }

        moasession.setPublicOAURLPrefix(oaParam.getPublicURLPrefix());

        moasession.setTarget(target);
        moasession.setBusinessService(oaParam.getBusinessService());
        //moasession.setStorkService(oaParam.getStorkService());
        Logger.debug(
                "Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService());
        moasession.setTargetFriendlyName(targetFriendlyName);
        moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier());
    }

    //check OnlineApplicationURL
    if (isEmpty(oaURL))
        throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.05");
    moasession.setOAURLRequested(oaURL);

    //check AuthURL
    String authURL = req.getScheme() + "://" + req.getServerName();
    if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443)
            || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)) {
        authURL = authURL.concat(":" + req.getServerPort());
    }
    authURL = authURL.concat(req.getContextPath() + "/");

    if (!authURL.startsWith("https:"))
        throw new AuthenticationException("auth.07", new Object[] { authURL + "*" });

    //set Auth URL from configuration
    moasession.setAuthURL(AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/");

    //check and set SourceID
    if (oaParam.getSAML1Parameter() != null) {
        String sourceID = oaParam.getSAML1Parameter().getSourceID();
        if (MiscUtil.isNotEmpty(sourceID))
            moasession.setSourceID(sourceID);
    }

    if (MiscUtil.isEmpty(templateURL)) {

        List<TemplateType> templateURLList = oaParam.getTemplateURL();
        List<String> defaulTemplateURLList = AuthConfigurationProvider.getInstance().getSLRequestTemplates();

        if (templateURLList != null && templateURLList.size() > 0
                && MiscUtil.isNotEmpty(templateURLList.get(0).getURL())) {
            templateURL = FileUtils.makeAbsoluteURL(oaParam.getTemplateURL().get(0).getURL(),
                    AuthConfigurationProvider.getInstance().getRootConfigFileDir());
            Logger.info("No SL-Template in request, load SL-Template from OA configuration (URL: " + templateURL
                    + ")");

        } else if ((defaulTemplateURLList.size() > 0) && MiscUtil.isNotEmpty(defaulTemplateURLList.get(0))) {
            templateURL = FileUtils.makeAbsoluteURL(defaulTemplateURLList.get(0),
                    AuthConfigurationProvider.getInstance().getRootConfigFileDir());
            Logger.info("No SL-Template in request, load SL-Template from general configuration (URL: "
                    + templateURL + ")");

        } else {
            Logger.error("NO SL-Tempalte found in OA config");
            throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12");

        }

    }

    if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL()))
        throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12");
    moasession.setTemplateURL(templateURL);

    moasession.setCcc(ccc);

}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*w  w w.  j  a v  a2 s.  c  om*/
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java

public String harvestStudy_action() {
    String link = null;//from w  w w  .  jav a2  s  . c o  m
    HarvestingDataverse hd = null;
    try {
        hd = harvestingDataverseService.find(harvestDVId);
        Long studyId = harvesterService.getRecord(hd, harvestIdentifier,
                hd.getHarvestFormatType().getMetadataPrefix());

        if (studyId != null) {
            indexService.updateStudy(studyId);

            // create link String
            HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest();
            link = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + "/dv/" + hd.getVdc().getAlias()
                    + "/faces/study/StudyPage.xhtml?studyId=" + studyId;
        }

        addMessage("harvestMessage", "Harvest succeeded" + (link == null ? "." : ": " + link));
    } catch (Exception e) {
        e.printStackTrace();
        addMessage("harvestMessage", "Harvest failed: An unexpected error occurred trying to get this record.");
        addMessage("harvestMessage", "Exception message: " + e.getMessage());
        addMessage("harvestMessage", "Harvest URL: " + hd.getServerUrl() + "?verb=GetRecord&identifier="
                + harvestIdentifier + "&metadataPrefix=" + hd.getHarvestFormatType().getMetadataPrefix());
    }

    return null;
}

From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java

public String importSingleFile_action() {
    //L.A.if(inputFile==null) return null; 
    //L.A.File originalFile = inputFile.getFile();

    //File originalFile = null; 

    if (uploadedDdiFile != null) {

        try {//www  . j av  a  2  s.co  m

            Study study = studyService.importStudy(uploadedDdiFile, getImportFileFormat(), getImportDVId(),
                    getVDCSessionBean().getLoginBean().getUser().getId());
            indexService.updateStudy(study.getId());
            // create result message
            HttpServletRequest req = (HttpServletRequest) getExternalContext().getRequest();
            String studyURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + "/dv/" + study.getOwner().getAlias()
                    + "/faces/study/StudyPage.xhtml?globalId=" + study.getGlobalId();

            addMessage("importMessage", "Import succeeded.");
            addMessage("importMessage", "Study URL: " + studyURL);

        } catch (Exception e) {
            e.printStackTrace();
            addMessage("harvestMessage",
                    "Import failed: An unexpected error occurred trying to import this study.");
            addMessage("harvestMessage", "Exception message: " + e.getMessage());
        }
    }

    return null;
}

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

/** Perform form authentication.
 * Called from SecurityHandler.//from w w w.  j  av a2s.c o  m
 * @return UserPrincipal if authenticated else null.
 */
public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest httpRequest,
        HttpResponse httpResponse) throws IOException {
    HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    HttpServletResponse response = httpResponse == null ? null
            : (HttpServletResponse) httpResponse.getWrapper();

    // Handle paths
    String uri = pathInContext;

    // Setup session 
    HttpSession session = request.getSession(response != null);
    if (session == null)
        return null;

    // Handle a request for authentication.
    if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) {
        // Check the session object for login info.
        FormCredential form_cred = new FormCredential();
        form_cred.authenticate(realm, request.getParameter(__J_USERNAME), request.getParameter(__J_PASSWORD),
                httpRequest);

        String nuri = (String) session.getAttribute(__J_URI);
        if (nuri == null || nuri.length() == 0) {
            nuri = request.getContextPath();
            if (nuri.length() == 0)
                nuri = "/";
        }

        if (form_cred._userPrincipal != null) {
            // Authenticated OK
            if (log.isDebugEnabled())
                log.debug("Form authentication OK for " + form_cred._jUserName);
            session.removeAttribute(__J_URI); // Remove popped return URI.
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._jUserName);
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            session.setAttribute(__J_AUTHENTICATED, form_cred);

            // Sign-on to SSO mechanism
            if (realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }

            // Redirect to original request
            if (response != null) {
                response.setContentLength(0);
                response.sendRedirect(response.encodeRedirectURL(nuri));
            }
        } else if (response != null) {
            if (log.isDebugEnabled())
                log.debug("Form authentication FAILED for " + form_cred._jUserName);
            if (_formErrorPage != null) {
                response.setContentLength(0);
                response.sendRedirect(
                        response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage)));
            } else {
                response.sendError(HttpResponse.__403_Forbidden);
            }
        }

        // Security check is always false, only true after final redirection.
        return null;
    }

    // Check if the session is already authenticated.
    FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);

    if (form_cred != null) {
        // We have a form credential. Has it been distributed?
        if (form_cred._userPrincipal == null) {
            // This form_cred appears to have been distributed.  Need to reauth
            form_cred.authenticate(realm, httpRequest);

            // Sign-on to SSO mechanism
            if (form_cred._userPrincipal != null && realm instanceof SSORealm) {
                ((SSORealm) realm).setSingleSignOn(httpRequest, httpResponse, form_cred._userPrincipal,
                        new Password(form_cred._jPassword));
            }
        } else if (!realm.reauthenticate(form_cred._userPrincipal))
            // Else check that it is still authenticated.
            form_cred._userPrincipal = null;

        // If this credential is still authenticated
        if (form_cred._userPrincipal != null) {
            if (log.isDebugEnabled())
                log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName());
            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            httpRequest.setAuthUser(form_cred._userPrincipal.getName());
            httpRequest.setUserPrincipal(form_cred._userPrincipal);
            return form_cred._userPrincipal;
        } else
            session.setAttribute(__J_AUTHENTICATED, null);
    } else if (realm instanceof SSORealm) {
        // Try a single sign on.
        Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse);

        if (httpRequest.hasUserPrincipal()) {
            form_cred = new FormCredential();
            form_cred._userPrincipal = request.getUserPrincipal();
            form_cred._jUserName = form_cred._userPrincipal.getName();
            if (cred != null)
                form_cred._jPassword = cred.toString();
            if (log.isDebugEnabled())
                log.debug("SSO for " + form_cred._userPrincipal);

            httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
            session.setAttribute(__J_AUTHENTICATED, form_cred);
            return form_cred._userPrincipal;
        }
    }

    // Don't authenticate authform or errorpage
    if (isLoginOrErrorPage(pathInContext))
        return SecurityConstraint.__NOBODY;

    // redirect to login page
    if (response != null) {
        if (httpRequest.getQuery() != null)
            uri += "?" + httpRequest.getQuery();
        session.setAttribute(__J_URI, request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + URI.addPaths(request.getContextPath(), uri));
        response.setContentLength(0);
        response.sendRedirect(
                response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage)));
    }

    return null;
}

From source file:com.viewer.servlets.ViewDocument.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {/*  w  ww . ja  v  a  2  s . c  o  m*/
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        try {
            result.setDocumentDescription(
                    (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
        } catch (ParseException x) {
            throw new ServletException(x);
        }
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages;
        try {
            htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
            cssList = tempRef_cssList.argValue;

            ArrayList<String> pagesContent = new ArrayList<String>();
            for (PageHtml page : htmlPages) {
                pagesContent.add(page.getHtmlContent());
            }
            String[] htmlContent = pagesContent.toArray(new String[0]);
            result.setPageHtml(htmlContent);
            result.setPageCss(new String[] { String.join(" ", temp_cssList) });

            for (int i = 0; i < result.getPageHtml().length; i++) {
                String html = result.getPageHtml()[i];
                int indexOfScript = html.indexOf("script");
                if (indexOfScript > 0) {
                    result.getPageHtml()[i] = html.substring(0, indexOfScript);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

/**
  * Processes the request made from the HTML visual interface of Strabon Endpoint.
  * //from   w  w  w  .j av  a  2s  .  com
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher dispatcher;

    // check whether Update submit button was fired
    String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit");

    if (reqFuncionality.equals("Update")) {
        // get the dispatcher for forwarding the rendering of the response
        dispatcher = request.getRequestDispatcher("/Update");
        dispatcher.forward(request, response);

    } else {
        String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
        String format = request.getParameter("format");
        String handle = request.getParameter("handle");
        String maxLimit = request.getParameter("maxLimit");

        // get stSPARQLQueryResultFormat from given format name
        TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format);

        if (query == null || format == null || queryResultFormat == null) {
            dispatcher = request.getRequestDispatcher("query.jsp");
            request.setAttribute(ERROR, PARAM_ERROR);
            dispatcher.forward(request, response);

        } else {
            query = strabonWrapper.addLimit(query, maxLimit);
            if ("download".equals(handle)) { // download as attachment
                ServletOutputStream out = response.getOutputStream();

                response.setContentType(queryResultFormat.getDefaultMIMEType());
                response.setHeader("Content-Disposition", "attachment; filename=results."
                        + queryResultFormat.getDefaultFileExtension() + "; " + queryResultFormat.getCharset());

                try {
                    strabonWrapper.query(query, format, out);
                    response.setStatus(HttpServletResponse.SC_OK);

                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    out.print(ResponseMessages.getXMLHeader());
                    out.print(ResponseMessages.getXMLException(e.getMessage()));
                    out.print(ResponseMessages.getXMLFooter());
                }

                out.flush();

            } else if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle))
                    && (queryResultFormat == stSPARQLQueryResultFormat.KML
                            || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) {
                // show map (only valid for KML/KMZ)

                // get dispatcher
                dispatcher = request.getRequestDispatcher("query.jsp");

                // re-assign handle
                request.setAttribute("handle", handle);

                SecureRandom random = new SecureRandom();
                String temp = new BigInteger(130, random).toString(32);

                // the temporary KML/KMZ file to create in the server
                String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension();
                ;

                try {
                    Date date = new Date();

                    // get the absolute path of the temporary directory
                    if (!request.getParameter("handle").toString().contains("timemap")) {
                        tempDirectory = appName + "-temp";

                        basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/";
                        // fix the temporary directory for this web application

                        FileUtils.forceMkdir(new File(basePath));

                        @SuppressWarnings("unchecked")
                        Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false);
                        while (it.hasNext()) {
                            File tbd = new File((it.next()).getAbsolutePath());
                            if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) {
                                FileUtils.forceDelete(new File(tbd.getAbsolutePath()));
                            }
                        }
                    } else { //timemap case
                        tempDirectory = "js/timemap";
                        basePath = context.getRealPath("/") + tempDirectory + "/";
                        // fix the temporary directory for this web application
                    }

                    // fix the temporary directory for this web application

                    // create temporary KML/KMZ file
                    File file = new File(basePath + tempKMLFile);
                    // if file does not exist, then create it
                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    try {
                        // query and write the result in the temporary KML/KMZ file
                        FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile);
                        strabonWrapper.query(query, format, fos);
                        fos.close();

                        if (request.getParameter("handle").toString().contains("timemap")) {
                            request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile);
                        } else {
                            request.setAttribute("pathToKML",
                                    request.getScheme() + "://" + request.getServerName() + ":"
                                            + request.getServerPort() + "/" + tempDirectory + "/"
                                            + tempKMLFile);
                        }

                    } catch (MalformedQueryException e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                        request.setAttribute(ERROR, e.getMessage());

                    } catch (Exception e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                        request.setAttribute(ERROR, e.getMessage());
                    }

                    dispatcher.forward(request, response);

                } catch (IOException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                }

            } else { // "plain" is assumed as the default
                dispatcher = request.getRequestDispatcher("query.jsp");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                try {
                    strabonWrapper.query(query, format, bos);
                    if (format.equals(Common.getHTMLFormat())) {
                        request.setAttribute(RESPONSE, bos.toString());
                    } else if (format.equals(Format.PIECHART.toString())
                            || format.equals(Format.AREACHART.toString())
                            || format.equals(Format.COLUMNCHART.toString())) {
                        request.setAttribute("format", "CHART");
                        request.setAttribute(RESPONSE, strabonWrapper.getgChartString());
                    }

                    else {
                        request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));
                    }

                } catch (MalformedQueryException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                    request.setAttribute(ERROR, e.getMessage());

                } catch (Exception e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                    request.setAttribute(ERROR, e.getMessage());

                } finally {
                    dispatcher.forward(request, response);
                }
            }
        }
    }
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * ?// w  w  w .j a va  2  s. c  o  m
 *
 * @param context
 * @param request
 * @param attributes
 * @param requestJson
 */
public LinkedHashMap<String, Object> createUserInfo(ServletContext context, HttpServletRequest request,
        String attributes, String requestJson) {
    LinkedHashMap<String, Object> result = null;

    Set<String> returnAttributeNameSet = new HashSet<>();

    // ?
    setError(0, null, null);

    // ??
    if (attributes != null && !attributes.isEmpty()) {
        // 
        String[] tempList = attributes.split(",");
        for (int i = 0; i < tempList.length; i++) {
            String attributeName = tempList[i].trim();
            // ???????
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null && !attributeSchema.isEmpty()) {
                returnAttributeNameSet.add(attributeName);
            } else {
                // ???????
                String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    }

    // ?
    if (requestJson == null || requestJson.isEmpty()) {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // (JSON)?
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String, Object> requestObject = null;
    try {
        requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() {
        });
    } catch (JsonParseException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (JsonMappingException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN);
        return result;
    }

    // ?
    if (requestObject != null && !requestObject.isEmpty()) {
        Iterator<String> attributeIt = requestObject.keySet().iterator();
        while (attributeIt.hasNext()) {
            // ???
            String attributeName = attributeIt.next();
            // ?
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null) {
                // ????
                Object mutability = attributeSchema.get("mutability");
                if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) {
                    // readOnly 
                    String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }

                // ??
                // ()
            } else {
                // ????
                String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    } else {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // ?
    // ()

    LinkedHashMap<String, Object> newUserInfo = new LinkedHashMap<String, Object>();

    // id?
    UUID uuid = UUID.randomUUID();
    newUserInfo.put("id", uuid.toString());

    Iterator<String> attributeIt = requestObject.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();
        // ?
        Object attributeValue = requestObject.get(attributeName);

        newUserInfo.put(attributeName, attributeValue);
    }

    // meta?
    LinkedHashMap<String, Object> metaValues = new LinkedHashMap<String, Object>();
    // meta.resourceType 
    metaValues.put("resourceType", "User");
    // meta.created 
    SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC"));
    metaValues.put("created", xsdDateTime.format(new Date()));
    // meta.location 
    String location = request.getScheme() + "://" + request.getServerName();
    int serverPort = request.getServerPort();
    if (serverPort != 80 && serverPort != 443) {
        location += ":" + Integer.toString(serverPort);
    }
    location += request.getContextPath();
    location += "/scim/Users/" + uuid.toString();
    metaValues.put("location", location);
    newUserInfo.put("meta", metaValues);

    // (??)
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Users");
    if (users == null) {
        users = new ArrayList<LinkedHashMap<String, Object>>();
    }
    users.add(newUserInfo);
    context.setAttribute("Users", users);

    // ??
    result = new LinkedHashMap<String, Object>();
    attributeIt = newUserInfo.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();

        // ?
        LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName,
                true);
        Object returned = attributeSchema.get("returned");

        if (returned != null && returned.toString().equalsIgnoreCase("never")) {
            continue;
        }

        // ?
        Object attributeValue = newUserInfo.get(attributeName);

        result.put(attributeName, attributeValue);
    }

    return result;
}

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 {/* w  ww.jav  a2s . com*/
            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.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;//from  w  ww. jav  a 2  s.  c  o  m
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}