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:org.kuali.mobility.tours.controllers.ToursController.java

@RequestMapping(value = "/view/{tourId}", method = RequestMethod.GET)
public String viewTour(HttpServletRequest request, Model uiModel, @PathVariable("tourId") long tourId) {
    try {//from  www  .jav  a 2 s .c  om
        User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
        Tour tour = toursService.findTourById(tourId);

        if (!toursService.hasAccessToViewTour(user, tour)) {
            uiModel.addAttribute("message", "You do not have access to view this tour.");
            return "tours/message";
        }

        if (tour != null) {
            if (tour.getPointsOfInterest() != null) {
                Collections.sort(tour.getPointsOfInterest());
            }
            try {
                if (tour.getFbText1() != null)
                    tour.setFbText1(URLEncoder.encode(tour.getFbText1(), "UTF-8"));
                if (tour.getFbText2() != null)
                    tour.setFbText2(URLEncoder.encode(tour.getFbText2(), "UTF-8"));
            } catch (Exception e) {

            }
            uiModel.addAttribute("tour", tour);
            try {
                uiModel.addAttribute("pageUrl",
                        URLEncoder.encode(request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath() + "/tours/view/"
                                + tour.getTourId(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving tour." + tourId, e);
    }
    return "tours/tour";
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * PUT?/*from  w ww .  j  a  v a2 s .co m*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {
            // PUT(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // 
            LinkedHashMap<String, Object> resultObject = op.updateUserInfo(context, request, targetId,
                    attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                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/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:org.apache.cocoon.servlet.DebugFilter.java

/**
 * Log debug information about the current environment.
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */// w ww  .  ja v  a2 s.  c  o m
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws IOException, ServletException {
    // we don't do debug msgs if this is not a http servlet request
    if (!(req instanceof HttpServletRequest)) {
        filterChain.doFilter(req, res);
        return;
    }
    try {
        ++activeRequestCount;
        final HttpServletRequest request = (HttpServletRequest) req;

        if (getLogger().isDebugEnabled()) {
            final StringBuffer msg = new StringBuffer();

            msg.append("DEBUGGING INFORMATION:").append(lineSeparator);
            msg.append("REQUEST: ").append(request.getRequestURI()).append(lineSeparator).append(lineSeparator);
            msg.append("CONTEXT PATH: ").append(request.getContextPath()).append(lineSeparator);
            msg.append("SERVLET PATH: ").append(request.getServletPath()).append(lineSeparator);
            msg.append("PATH INFO: ").append(request.getPathInfo()).append(lineSeparator).append(lineSeparator);

            msg.append("REMOTE HOST: ").append(request.getRemoteHost()).append(lineSeparator);
            msg.append("REMOTE ADDRESS: ").append(request.getRemoteAddr()).append(lineSeparator);
            msg.append("REMOTE USER: ").append(request.getRemoteUser()).append(lineSeparator);
            msg.append("REQUEST SESSION ID: ").append(request.getRequestedSessionId()).append(lineSeparator);
            msg.append("REQUEST PREFERRED LOCALE: ").append(request.getLocale().toString())
                    .append(lineSeparator);
            msg.append("SERVER HOST: ").append(request.getServerName()).append(lineSeparator);
            msg.append("SERVER PORT: ").append(request.getServerPort()).append(lineSeparator)
                    .append(lineSeparator);

            msg.append("METHOD: ").append(request.getMethod()).append(lineSeparator);
            msg.append("CONTENT LENGTH: ").append(request.getContentLength()).append(lineSeparator);
            msg.append("PROTOCOL: ").append(request.getProtocol()).append(lineSeparator);
            msg.append("SCHEME: ").append(request.getScheme()).append(lineSeparator);
            msg.append("AUTH TYPE: ").append(request.getAuthType()).append(lineSeparator).append(lineSeparator);
            msg.append("CURRENT ACTIVE REQUESTS: ").append(activeRequestCount).append(lineSeparator);

            // log all of the request parameters
            final Enumeration e = request.getParameterNames();

            msg.append("REQUEST PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e.hasMoreElements()) {
                String p = (String) e.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                String[] params = request.getParameterValues(p);
                for (int i = 0; i < params.length; i++) {
                    msg.append("[" + params[i] + "]");
                    if (i != (params.length - 1)) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            // log all of the header parameters
            final Enumeration e2 = request.getHeaderNames();

            msg.append("HEADER PARAMETERS:").append(lineSeparator).append(lineSeparator);

            while (e2.hasMoreElements()) {
                String p = (String) e2.nextElement();

                msg.append("PARAM: '").append(p).append("' ").append("VALUES: '");
                Enumeration e3 = request.getHeaders(p);
                while (e3.hasMoreElements()) {
                    msg.append("[" + e3.nextElement() + "]");
                    if (e3.hasMoreElements()) {
                        msg.append(", ");
                    }
                }

                msg.append("'").append(lineSeparator);
            }

            msg.append(lineSeparator).append("SESSION ATTRIBUTES:").append(lineSeparator).append(lineSeparator);

            // log all of the session attributes
            final HttpSession session = ((HttpServletRequest) req).getSession(false);
            if (session != null) {
                // Fix bug #12139: Session can be modified while still
                // being enumerated here
                synchronized (session) {
                    final Enumeration se = session.getAttributeNames();
                    while (se.hasMoreElements()) {
                        String p = (String) se.nextElement();
                        msg.append("PARAM: '").append(p).append("' ").append("VALUE: '")
                                .append(session.getAttribute(p)).append("'").append(lineSeparator);
                    }
                }
            }
            getLogger().debug(msg.toString());
        }

        // Delegate
        filterChain.doFilter(request, res);
    } finally {
        --activeRequestCount;
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.ScreenController.java

@RequestMapping(value = "/screen.upload")
public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
    try {//from  ww  w .  j a  v  a  2s  .  c  o m
        String sid = request.getParameter("sid");
        Long users_id = sessiondataDao.checkSession(sid);
        String publicSID = request.getParameter("publicSID");
        if (publicSID == null) {
            throw new Exception("publicSID is empty: " + publicSID);
        }
        if (users_id == 0) {
            //checkSession will return 0 in case of invalid session
            throw new Exception("Request from invalid user " + users_id);
        }

        String domain = request.getParameter("domain");
        if (domain == null) {
            throw new Exception("domain is empty: " + domain);
        }

        String languageAsString = request.getParameter("languageAsString");
        if (languageAsString == null) {
            throw new Exception("languageAsString is empty: " + languageAsString);
        }
        Long language_id = Long.parseLong(languageAsString);

        String rtmphostlocal = request.getParameter("rtmphostlocal");
        if (rtmphostlocal == null) {
            throw new Exception("rtmphostlocal is empty: " + rtmphostlocal);
        }

        String red5httpport = request.getParameter("red5httpport");
        if (red5httpport == null) {
            throw new Exception("red5httpport is empty: " + red5httpport);
        }

        String httpRootKey = request.getParameter("httpRootKey");
        if (httpRootKey == null) {
            throw new Exception("httpRootKey is empty could not start sharer");
        }

        String baseURL = request.getScheme() + "://" + rtmphostlocal + ":" + red5httpport + httpRootKey;

        log.debug("httpRootKey " + httpRootKey);
        log.debug("language_id :: " + language_id);
        String label_sharer = "Sharer";

        try {
            label_sharer = getLabels(language_id, 730, 731, 732, 733, 734, 735, 737, 738, 739, 740, 741, 742,
                    844, 869, 870, 871, 872, 878, 1089, 1090, 1091, 1092, 1093, 1465, 1466, 1467, 1468, 1469,
                    1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477);
        } catch (Exception e) {
            log.error("Error resolving Language labels : ", e);
        }
        log.debug("Creating JNLP Template for TCP solution");

        //libs
        StringBuilder libs = new StringBuilder();
        File screenShareDir = OmFileHelper.getScreenSharingDir();
        for (File jar : screenShareDir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".jar");
            }
        })) {
            libs.append("\t\t<jar href=\"").append(jar.getName()).append("\"/>\n");
        }
        log.debug("RTMP Sharer labels :: " + label_sharer);

        ConnectionType conType = ConnectionType.valueOf(request.getParameter("connectionType"));

        String startUpClass;
        switch (conType) {
        case rtmp:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPScreenShare";
            break;
        case rtmps:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPSScreenShare";
            break;
        case rtmpt:
            startUpClass = "org.apache.openmeetings.screen.webstart.RTMPTScreenShare";
            break;
        default:
            throw new Exception("Unknown connection type");
        }

        String orgIdAsString = request.getParameter("organization_id");
        if (orgIdAsString == null) {
            throw new Exception("orgIdAsString is empty could not start sharer");
        }

        String port = request.getParameter("port");
        if (port == null) {
            throw new Exception("port is empty: ");
        }
        Client rc = sessionManager.getClientByPublicSID(publicSID, false, null);
        if (rc == null) {
            throw new Exception("port is empty: ");
        }
        Long roomId = rc.getRoom_id();
        boolean allowRecording = rc.getAllowRecording() && (0 == sessionManager.getRecordingCount(roomId));
        boolean allowPublishing = (0 == sessionManager.getPublishingCount(roomId));

        Context ctx = new VelocityContext();
        ctx.put("APP_NAME", configurationDao.getAppName());
        ctx.put("PUBLIC_SID", publicSID);
        ctx.put("LABELSHARER", label_sharer);
        addKeystore(ctx);
        ctx.put("LIBRARIES", libs);
        ctx.put("organization_id", orgIdAsString);
        ctx.put("startUpClass", startUpClass);
        ctx.put("codebase", baseURL + OmFileHelper.SCREENSHARING_DIR);
        ctx.put("red5-host", rtmphostlocal);
        ctx.put("red5-app", OpenmeetingsVariables.webAppRootKey + "/" + roomId);
        ctx.put("default_quality_screensharing",
                configurationDao.getConfValue("default.quality.screensharing", String.class, "1"));
        //invited guest does not have valid user_id (have user_id == -1)
        ctx.put("user_id", users_id);
        ctx.put("port", port);
        ctx.put("allowRecording", allowRecording);
        ctx.put("allowPublishing", allowPublishing);

        String requestedFile = StringUtils.deleteWhitespace(domain + "_" + roomId) + ".jnlp";
        response.setContentType("application/x-java-jnlp-file");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "Inline; filename=\"" + requestedFile + "\"");

        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        ve.mergeTemplate("screenshare.vm", "UTF-8", ctx, response.getWriter());
    } catch (Exception er) {
        log.error("[ScreenController]", er);
    }
}

From source file:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java

private Resource resolveInternal(final HttpServletRequest request, String absPath) {
    // make sure abspath is not null and is absolute
    if (absPath == null) {
        absPath = "/";
    } else if (!absPath.startsWith("/")) {
        absPath = "/" + absPath;
    }// www.j  a  va2  s. c o  m

    // check for special namespace prefix treatment
    absPath = unmangleNamespaces(absPath);

    // Assume http://localhost:80 if request is null
    String[] realPathList = { absPath };
    String requestPath;
    if (request != null) {
        requestPath = getMapPath(request.getScheme(), request.getServerName(), request.getServerPort(),
                absPath);
    } else {
        requestPath = getMapPath("http", "localhost", 80, absPath);
    }

    logger.debug("resolve: Resolving request path {}", requestPath);

    // loop while finding internal or external redirect into the
    // content out of the virtual host mapping tree
    // the counter is to ensure we are not caught in an endless loop here
    // TODO: might do better to be able to log the loop and help the user
    for (int i = 0; i < 100; i++) {

        String[] mappedPath = null;

        final Iterator<MapEntry> mapEntriesIterator = this.factory.getMapEntries()
                .getResolveMapsIterator(requestPath);
        while (mapEntriesIterator.hasNext()) {
            final MapEntry mapEntry = mapEntriesIterator.next();
            mappedPath = mapEntry.replace(requestPath);
            if (mappedPath != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry,
                            Arrays.toString(mappedPath));
                }
                if (mapEntry.isInternal()) {
                    // internal redirect
                    logger.debug("resolve: Redirecting internally");
                    break;
                }

                // external redirect
                logger.debug("resolve: Returning external redirect");
                return this.factory.getResourceDecoratorTracker()
                        .decorate(new RedirectResource(this, absPath, mappedPath[0], mapEntry.getStatus()));
            }
        }

        // if there is no virtual host based path mapping, abort
        // and use the original realPath
        if (mappedPath == null) {
            logger.debug("resolve: Request path {} does not match any MapEntry", requestPath);
            break;
        }

        // if the mapped path is not an URL, use this path to continue
        if (!mappedPath[0].contains("://")) {
            logger.debug("resolve: Mapped path is for resource tree");
            realPathList = mappedPath;
            break;
        }

        // otherwise the mapped path is an URI and we have to try to
        // resolve that URI now, using the URI's path as the real path
        try {
            final URI uri = new URI(mappedPath[0], false);
            requestPath = getMapPath(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
            realPathList = new String[] { uri.getPath() };

            logger.debug("resolve: Mapped path is an URL, using new request path {}", requestPath);
        } catch (final URIException use) {
            // TODO: log and fail
            throw new ResourceNotFoundException(absPath);
        }
    }

    // now we have the real path resolved from virtual host mapping
    // this path may be absolute or relative, in which case we try
    // to resolve it against the search path

    Resource res = null;
    for (int i = 0; res == null && i < realPathList.length; i++) {
        final ParsedParameters parsedPath = new ParsedParameters(realPathList[i]);
        final String realPath = parsedPath.getRawPath();

        // first check whether the requested resource is a StarResource
        if (StarResource.appliesTo(realPath)) {
            logger.debug("resolve: Mapped path {} is a Star Resource", realPath);
            res = new StarResource(this, ensureAbsPath(realPath));

        } else {

            if (realPath.startsWith("/")) {

                // let's check it with a direct access first
                logger.debug("resolve: Try absolute mapped path {}", realPath);
                res = resolveInternal(realPath, parsedPath.getParameters());

            } else {

                final String[] searchPath = getSearchPath();
                for (int spi = 0; res == null && spi < searchPath.length; spi++) {
                    logger.debug("resolve: Try relative mapped path with search path entry {}",
                            searchPath[spi]);
                    res = resolveInternal(searchPath[spi] + realPath, parsedPath.getParameters());
                }

            }
        }
    }

    // if no resource has been found, use a NonExistingResource
    if (res == null) {
        final ParsedParameters parsedPath = new ParsedParameters(realPathList[0]);
        final String resourcePath = ensureAbsPath(parsedPath.getRawPath());
        logger.debug("resolve: Path {} does not resolve, returning NonExistingResource at {}", absPath,
                resourcePath);

        res = new NonExistingResource(this, resourcePath);
        // SLING-864: if the path contains a dot we assume this to be
        // the start for any selectors, extension, suffix, which may be
        // used for further request processing.
        // the resolution path must be the full path and is already set within
        // the non existing resource
        final int index = resourcePath.indexOf('.');
        if (index != -1) {
            res.getResourceMetadata().setResolutionPathInfo(resourcePath.substring(index));
        }
        res.getResourceMetadata().setParameterMap(parsedPath.getParameters());
    } else {
        logger.debug("resolve: Path {} resolves to Resource {}", absPath, res);
    }

    return this.factory.getResourceDecoratorTracker().decorate(res);
}

From source file:org.ecocean.MarkedIndividual.java

public String getUrl(HttpServletRequest request) {
    return request.getScheme() + "://" + CommonConfiguration.getURLLocation(request)
            + "/individuals.jsp?number=" + this.getIndividualID();
}

From source file:org.kuali.mobility.writer.tags.ArticleImageTag.java

public void doTag() {
    PageContext pageContext = (PageContext) getJspContext();
    JspWriter out = pageContext.getOut();
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String contextPath = request.getContextPath();
    ServletContext servletContext = pageContext.getServletContext();
    WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    IconsService iconService = (IconsService) ac.getBean("iconsService");

    String thumbNailPath;//  w ww . java2s  . c  o m
    String fullPath = null;
    final String instanceURL = contextPath + prefix + instance;
    /*
     * First check if the article exits, and it has image media.
     * If it does not exist or has no image, we need to use
     * the default image for that instance of the tool
     */
    if (article == null || article.getImage() == null || article.getImage().getId() == 0) {

        /*
         * Check if there is an icon themed for this instance of the writer tool
         */
        if (StringUtils.isEmpty(instance) && iconService.getIcon(WRITER_ICON_NAME, instance) != null) {
            thumbNailPath = contextPath + "/getIcon/" + WRITER_ICON_NAME + "-" + instance + "-80@2.png";
        } else {
            thumbNailPath = contextPath + "/getIcon/WriterArticle-80@2.png";
        }
    } else {
        thumbNailPath = instanceURL + "/media/" + article.getImage().getId() + "?thumb=1";
        fullPath = instanceURL + "/media/view/" + article.getImage().getId();
    }
    boolean addLink = (wrapLink && fullPath != null);
    boolean isNative = (Boolean) request.getSession(true).getAttribute(NativeCookieInterceptor.SESSION_NATIVE);
    try {
        // Wrap with link if required
        if (addLink && isNative) {
            String serverPath = request.getScheme() + "://" + request.getServerName();
            if (request.getServerPort() != 80) {
                serverPath += ":" + request.getServerPort();
            }
            serverPath += fullPath;
            writeChildBrowserJS(out, serverPath);
        } else if (addLink) {
            out.print("<a href=\"");
            out.print(fullPath);
            out.print("\">");
        }

        // Put image container
        out.print("<img src=\"");
        out.print(thumbNailPath);
        out.print("\"");

        // Add image id if specified
        if (this.id != null) {
            out.print(" id=\"");
            out.print(this.id);
            out.print("\"");
        }

        // Add style if specified
        if (this.style != null) {
            out.print(" style=\"");
            out.print(this.style);
            out.print("\"");
        }

        out.print(" />");

        // Close wrapping link
        if (addLink) {
            out.print("</a>");
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:net.sourceforge.msscodefactory.cfensyntax.v2_2.CFEnSyntaxSMWar.CFEnSyntaxSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from w  w  w .j  av  a 2  s  .co  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doGet";
    ICFEnSyntaxSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFEnSyntaxSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFEnSyntaxSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
            return;
        }
    }

    CFEnSyntaxAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
        return;
    }

    ICFEnSyntaxSchema dbSchema = null;
    try {
        dbSchema = CFEnSyntaxSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();
        ICFEnSyntaxSecUserObj secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

        ICFEnSyntaxClusterObj secCluster = schemaObj.getClusterTableObj()
                .readClusterByIdIdx(auth.getSecClusterId());
        if (secCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "secCluster");
        }
        String clusterDescription = secCluster.getRequiredDescription();

        String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getRequestURI().toString();
        int lastSlash = thisURI.lastIndexOf('/');
        String baseURI = thisURI.substring(0, lastSlash);

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel;</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");

    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFEnSyntaxSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:com.cyclopsgroup.waterview.servlet.ServletRuntimeData.java

/**
 * Default constructor of default web runtime
 *
 * @param request Http request object/*  w  ww  . jav  a 2s. c o m*/
 * @param response Http response object
 * @param context Http servlet context
 * @param fileUpload File upload component
 * @param services ServiceManager object
 * @param applicationBase application base url
 * @throws Exception Throw it out
 */
ServletRuntimeData(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        FileUpload fileUpload, ServiceManager services, String applicationBase) throws Exception {
    this.response = response;
    this.context = context;

    setQueryString(request.getQueryString());
    setRefererUrl(request.getHeader("referer"));

    //Session Context
    setSessionContext(new HttpSessionContext(request.getSession()));
    setSessionId(request.getSession().getId());

    setRequestContext(new ServletRequestContext(request));

    //Request path
    String requestPath = request.getPathInfo();
    setRequestPath(requestPath == null ? StringUtils.EMPTY : requestPath);

    //Output
    OutputStream outputStream = response.getOutputStream();
    setOutputStream(outputStream);

    InterpolationFilterWriter filterWriter = new InterpolationFilterWriter(new OutputStreamWriter(outputStream),
            '%') {
        /**
         * Overwrite or implement method interpolate()
         *
         * @see com.cyclopsgroup.waterview.utils.InterpolationFilterWriter#interpolate(java.lang.String)
         */
        protected String interpolate(String name) throws Exception {
            I18NService i18n = (I18NService) getServiceManager().lookup(I18NService.ROLE);
            return i18n.translate(name, getLocale());
        }
    };
    setOutput(new PrintWriter(filterWriter));

    //Request value parser
    if (FileUpload.isMultipartContent(request)) {
        setParams(new MultipartServletRequestParameters(request, fileUpload));
    } else {
        setParams(new ServletRequestParameters(request));
    }

    //Service manager
    setServiceManager(services);

    //Application base url
    if (StringUtils.isEmpty(applicationBase)) {
        StringBuffer sb = new StringBuffer(request.getScheme());
        sb.append("://").append(request.getServerName());
        if (request.getServerPort() != 80) {
            sb.append(':').append(request.getServerPort());
        }
        sb.append(request.getContextPath());
        applicationBase = sb.toString();
    }
    setApplicationBaseUrl(applicationBase);

    //Page base url
    setPageBaseUrl(applicationBase + request.getServletPath());
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form.//from  ww w  .j  a  v a 2s.co  m
 *
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    String templateFile = (String) session.getAttribute("faban.submit.template");
    String styleSheet = (String) session.getAttribute("faban.submit.stylesheet");

    String srcURL = new File(templateFile).toURI().toString();

    logger.finer("benchmark.template: " + srcURL);
    session.removeAttribute("faban.submit.template");
    session.removeAttribute("faban.submit.stylesheet");

    try {
        String requestURI = request.getRequestURI();
        String formURI = null;
        String contextPath = request.getContextPath();
        String benchPath = contextPath + "/bm_submit/";
        if (requestURI.startsWith(benchPath)) {
            int idx = requestURI.indexOf('/', benchPath.length());
            String benchName = requestURI.substring(benchPath.length(), idx);
            String formName = requestURI.substring(idx + 1);
            formURI = com.sun.faban.harness.common.Config.FABAN_HOME + "benchmarks/" + benchName + "/META-INF/"
                    + formName;
        } else {
            StringBuffer buffer = new StringBuffer(request.getScheme());
            buffer.append("://");
            buffer.append(request.getServerName());
            buffer.append(":");
            buffer.append(request.getServerPort());
            buffer.append(request.getContextPath());
            buffer.append(request.getParameter("form"));
            formURI = buffer.toString();
        }

        if (formURI == null) {
            throw new IOException("Resource not found: " + formURI);
        }
        logger.finer("Form URI: " + formURI);

        String css = request.getParameter("css");
        String actionURL = response.encodeURL(request.getRequestURI());
        logger.finer("actionURL: " + actionURL);

        // Find the base URL used by Faban. We do not use Config.FABAN_URL
        // because this base URL can vary by the interface name the Faban
        // master is accessed in this session. Otherwise it is identical.
        StringBuffer baseURL = request.getRequestURL();
        int uriLength = baseURL.length() - requestURI.length() + contextPath.length();
        baseURL.setLength(++uriLength); // Add the ending slash

        adapter = new Adapter();
        if (configFile != null && configFile.length() > 0)
            adapter.setConfigPath(configFile);

        File xsl = null;
        if (styleSheet != null)
            xsl = new File(styleSheet);

        if (xsl != null && xsl.exists()) {
            adapter.xslPath = xsl.getParent();
            adapter.stylesheet = xsl.getName();
        } else {
            adapter.xslPath = xsltDir;
            adapter.stylesheet = "faban.xsl";
        }

        adapter.baseURI = baseURL.toString();
        adapter.formURI = formURI;
        adapter.actionURL = actionURL;
        adapter.beanCtx.put("chiba.web.uploadDir", uploadDir);
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        adapter.beanCtx.put("benchmark.template", srcURL);

        if (css != null) {
            adapter.CSSFile = css;
            logger.fine("using css stylesheet: " + css);
        }

        Map servletMap = new HashMap();
        servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
        adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String s = (String) params.nextElement();
            //store all request-params we don't use in the beanCtx map
            if (!(s.equals("form") || s.equals("xslt") || s.equals("css") || s.equals("action_url"))) {
                String value = request.getParameter(s);
                adapter.beanCtx.put(s, value);
                logger.finer("added request param '" + s + "' to beanCtx");
            }
        }
        adapter.init();
        adapter.execute();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        adapter.generator.setOutput(out);
        adapter.buildUI();
        session.setAttribute("chiba.adapter", adapter);
        out.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}