Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl.

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java

/**
 * initiate the authentication request/*from ww  w.  ja  v a 2 s  . com*/
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    String resourceName = SMSOTPConstants.PROPERTIES_FILE;
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Properties prop = new Properties();

    InputStream resourceStream = loader.getResourceAsStream(resourceName);
    try {
        prop.load(resourceStream);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Can not find the file", e);
    }

    newAuthenticatorProperties = context.getAuthenticatorProperties();
    newAuthenticatorProperties.put("username", prop.getProperty("username"));
    newAuthenticatorProperties.put("password", prop.getProperty("password"));
    newAuthenticatorProperties.put("from", prop.getProperty("from"));
    newAuthenticatorProperties.put("text", prop.getProperty("text"));
    context.setAuthenticatorProperties(newAuthenticatorProperties);

    OneTimePassword token = new OneTimePassword();
    String secret = OneTimePassword.getRandomNumber(SMSOTPConstants.SECRET_KEY_LENGTH);
    otpToken = token.generateToken(secret, "" + SMSOTPConstants.NUMBER_BASE, SMSOTPConstants.NUMBER_DIGIT);
    Object myToken = SMSOTPConstants.OTP_TOKEN;
    context.setProperty(SMSOTPConstants.OTP_TOKEN, myToken);

    Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
    clientId = authenticatorProperties.get(SMSOTPConstants.API_KEY);
    clientSecret = authenticatorProperties.get(SMSOTPConstants.API_SECRET);
    smsUrl = authenticatorProperties.get(SMSOTPConstants.SMS_URL);

    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL()
            .replace("authenticationendpoint/login.do", SMSOTPConstants.LOGIN_PAGE);
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());
    String retryParam = "";

    if (context.isRetrying()) {
        retryParam = SMSOTPConstants.RETRY_PARAMS;
    }

    try {
        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&authenticators="
                + getName() + retryParam);
    } catch (IOException e) {
        log.error("Authentication failed!", e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }

    String username = null;
    for (Integer stepMap : context.getSequenceConfig().getStepMap().keySet())
        if (context.getSequenceConfig().getStepMap().get(stepMap).getAuthenticatedUser() != null
                && context.getSequenceConfig().getStepMap().get(stepMap).getAuthenticatedAutenticator()
                        .getApplicationAuthenticator() instanceof LocalApplicationAuthenticator) {

            username = String
                    .valueOf(context.getSequenceConfig().getStepMap().get(stepMap).getAuthenticatedUser());
            break;
        }
    if (StringUtils.isNotEmpty(username)) {
        UserRealm userRealm = null;
        try {
            String tenantDomain = MultitenantUtils.getTenantDomain(username);
            int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);

            RealmService realmService = IdentityTenantUtil.getRealmService();
            userRealm = (UserRealm) realmService.getTenantUserRealm(tenantId);
        } catch (Exception e) {
            throw new AuthenticationFailedException("Cannot find the user realm", e);
        }
        username = MultitenantUtils.getTenantAwareUsername(String.valueOf(username));
        if (userRealm != null) {
            try {
                mobile = userRealm.getUserStoreManager()
                        .getUserClaimValue(username, SMSOTPConstants.MOBILE_CLAIM, null).toString();
            } catch (UserStoreException e) {
                log.error("Cannot find the user claim for mobile", e);
                throw new AuthenticationFailedException(
                        "Cannot find the user claim for mobile " + e.getMessage(), e);
            }
        }
    }

    if (StringUtils.isNotEmpty(clientId) && StringUtils.isNotEmpty(clientSecret)
            && StringUtils.isNotEmpty(mobile)) {
        fullUrl = setUrl();
        try {
            if (!sendRESTCall(smsUrl, fullUrl)) {
                log.error("Unable to send the code");
                throw new AuthenticationFailedException("Unable to send the code");
            }
        } catch (IOException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while sending the HTTP request", e);
            }
        }
    }
}

From source file:fll.web.GatherBugReport.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    ZipOutputStream zipOut = null;
    final StringBuilder message = new StringBuilder();
    try {//from www.  j  av a 2  s .co  m
        if (null != SessionAttributes.getMessage(session)) {
            message.append(SessionAttributes.getMessage(session));
        }

        connection = datasource.getConnection();
        final Document challengeDocument = ApplicationAttributes.getChallengeDocument(application);

        final File fllWebInfDir = new File(application.getRealPath("/WEB-INF"));
        final String nowStr = new SimpleDateFormat("yyyy-MM-dd_HH-mm").format(new Date());
        final File bugReportFile = File.createTempFile(nowStr, ".zip", fllWebInfDir);

        zipOut = new ZipOutputStream(new FileOutputStream(bugReportFile));

        final String description = request.getParameter("bug_description");
        if (null != description) {
            zipOut.putNextEntry(new ZipEntry("bug_description.txt"));
            zipOut.write(description.getBytes(Utilities.DEFAULT_CHARSET));
        }

        zipOut.putNextEntry(new ZipEntry("server_info.txt"));
        zipOut.write(String.format(
                "Java version: %s%nJava vendor: %s%nOS Name: %s%nOS Arch: %s%nOS Version: %s%nServlet API: %d.%d%nServlet container: %s%n",
                System.getProperty("java.vendor"), //
                System.getProperty("java.version"), //
                System.getProperty("os.name"), //
                System.getProperty("os.arch"), //
                System.getProperty("os.version"), //
                application.getMajorVersion(), application.getMinorVersion(), //
                application.getServerInfo()).getBytes(Utilities.DEFAULT_CHARSET));

        addDatabase(zipOut, connection, challengeDocument);
        addLogFiles(zipOut, application);

        message.append(String.format(
                "<i>Bug report saved to '%s', please notify the computer person in charge to look for bug report files.</i>",
                bugReportFile.getAbsolutePath()));
        session.setAttribute(SessionAttributes.MESSAGE, message);

        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/"));

    } catch (final SQLException sqle) {
        throw new RuntimeException(sqle);
    } finally {
        SQLFunctions.close(connection);
        IOUtils.closeQuietly(zipOut);
    }

}

From source file:org.sakaiproject.login.tool.LoginTool.java

/**
 * Respond to requests.//w w  w .  ja  v a  2 s . c  o  m
 *
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // get the session
    Session session = SessionManager.getCurrentSession();

    // get my tool registration
    Tool tool = (Tool) req.getAttribute(Tool.TOOL);

    // recognize what to do from the path
    String option = req.getPathInfo();

    // maybe we don't want to do the container this time
    boolean skipContainer = false;

    // if missing, set it to "/login"
    if ((option == null) || ("/".equals(option))) {
        option = "/login";
    }

    // look for the extreme login (i.e. to skip container checks)
    else if ("/xlogin".equals(option)) {
        option = "/login";
        skipContainer = true;
    }

    // get the parts (the first will be "", second will be "login" or "logout")
    String[] parts = option.split("/");

    if (parts[1].equals("logout")) {
        // get the session info complete needs, since the logout will invalidate and clear the session
        String returnUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);

        // logout the user
        UsageSessionService.logout();

        complete(returnUrl, null, tool, res);
        return;
    } else {
        // see if we need to check container
        boolean checkContainer = ServerConfigurationService.getBoolean("container.login", false);
        if (checkContainer && !skipContainer) {
            // if we have not checked the container yet, check it now
            if (session.getAttribute(ATTR_CONTAINER_CHECKED) == null) {
                // save our return path
                session.setAttribute(ATTR_RETURN_URL, Web.returnUrl(req, null));

                String containerCheckPath = this.getServletConfig().getInitParameter("container");
                String containerCheckUrl = Web.serverUrl(req) + containerCheckPath;

                // support query parms in url for container auth
                String queryString = Validator.generateQueryString(req);
                if (queryString != null)
                    containerCheckUrl = containerCheckUrl + "?" + queryString;

                res.sendRedirect(res.encodeRedirectURL(containerCheckUrl));
                return;
            }
        }

        // send the form
        sendForm(req, res);
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void updateDocumentCategories(HttpServletRequest req, HttpServletResponse resp) {
    String id;//from   w  w w.j  a  va 2s.c om
    String repositoryName;
    String[] categories = req.getParameterValues("categories");
    try {
        id = getField(req, resp, "id");
        repositoryName = getField(req, resp, "repository");
    } catch (FieldNotFoundException e) {
        return;
    }
    try {
        Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
        RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile)
                .getRepositoryService();
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);
        Document doc = repositoryService.findDocument(ticket, id);
        DocumentProperties docProperties = doc.dumpProperties();
        List<Category> nodeCategories = repositoryService.findCategoriesForNode(ticket, doc.getId());
        Iterator<Category> ite = nodeCategories.iterator();
        while (ite.hasNext()) {
            Category category = ite.next();
            docProperties.addProperty(DocumentProperties.DOCUMENT_DELETE_CATEGORY, category.getId());
        }
        if (categories != null) {
            for (int cont = 0; categories.length > cont; cont++) {
                docProperties.addProperty(DocumentProperties.DOCUMENT_ADD_CATEGORY, categories[cont]);
            }
        }
        repositoryService.updateDocument(ticket, docProperties);

        String url = getRootURL(req) + "/forward?method=documentdocuments&repository=" + repositoryName + "&id="
                + doc.getId();
        resp.sendRedirect(resp.encodeRedirectURL(url));
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem adding categories.");
    }
}

From source file:com.wso2telco.gsma.authenticators.headerenrich.HeaderEnrichmentAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    log.info("Initiating authentication request");

    AuthenticationContextCache.getInstance().addToCache(
            new AuthenticationContextCacheKey(context.getContextIdentifier()),
            new AuthenticationContextCacheEntry(context));

    UserStatus userStatus = (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM);

    String operator = context.getProperty(Constants.OPERATOR).toString();
    String msisdn = context.getProperty(Constants.MSISDN).toString();
    boolean isRegistering = (boolean) context.getProperty(Constants.IS_REGISTERING);
    boolean showTnC = (boolean) context.getProperty(Constants.IS_SHOW_TNC);

    try {/*from  w  w w  .j  a v  a 2s.  c om*/
        isValidOperator(request, context, msisdn, operator, userStatus);
    } catch (AuthenticationFailedException e) {
        // take action based on scope properties
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.HE_AUTH_PROCESSING_FAIL, e.getMessage());
        actionBasedOnHEFailureResult(context);
        throw e;
    }

    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    if (log.isDebugEnabled()) {
        log.debug("MSISDN : " + msisdn);
        log.debug("Operator : " + operator);
        log.debug("Query parameters : " + queryParams);
    }

    try {

        String loginPage = getAuthEndpointUrl(showTnC, isRegistering);

        DataPublisherUtil.updateAndPublishUserStatus(
                (UserStatus) context.getParameter(Constants.USER_STATUS_DATA_PUBLISHING_PARAM),
                DataPublisherUtil.UserState.REDIRECT_TO_CONSENT_PAGE, "Redirecting to consent page");

        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams)) + "&redirect_uri="
                + request.getParameter("redirect_uri") + "&authenticators=" + getName() + ":" + "LOCAL");
    } catch (IOException e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.HE_AUTH_PROCESSING_FAIL, e.getMessage());
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
    return;

}

From source file:org.wso2.carbon.identity.application.authenticator.basicauth.BasicAuthenticator.java

@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {

    Map<String, String> parameterMap = getAuthenticatorConfig().getParameterMap();
    String showAuthFailureReason = null;
    if (parameterMap != null) {
        showAuthFailureReason = parameterMap.get("showAuthFailureReason");
        if (log.isDebugEnabled()) {
            log.debug("showAuthFailureReason has been set as : " + showAuthFailureReason);
        }//from  w w  w. j a  v  a2 s .  c  o m
    }

    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
    String queryParams = context.getContextIdIncludedQueryParams();

    try {
        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        }

        IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
        IdentityUtil.clearIdentityErrorMsg();

        if (showAuthFailureReason != null && "true".equals(showAuthFailureReason)) {
            if (errorContext != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Identity error message context is not null");
                }

                String errorCode = errorContext.getErrorCode();
                int remainingAttempts = errorContext.getMaximumLoginAttempts()
                        - errorContext.getFailedLoginAttempts();

                if (log.isDebugEnabled()) {
                    log.debug("errorCode : " + errorCode);
                    log.debug("username : " + request.getParameter(BasicAuthenticatorConstants.USER_NAME));
                    log.debug("remainingAttempts : " + remainingAttempts);
                }

                if (errorCode.equals(UserCoreConstants.ErrorCode.INVALID_CREDENTIAL)) {
                    retryParam = retryParam + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                            + BasicAuthenticatorConstants.FAILED_USERNAME
                            + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME),
                                    BasicAuthenticatorConstants.UTF_8)
                            + "&remainingAttempts=" + remainingAttempts;
                    response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                            + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":"
                            + BasicAuthenticatorConstants.LOCAL + retryParam);
                } else if (errorCode.equals(UserCoreConstants.ErrorCode.USER_IS_LOCKED)) {
                    String redirectURL = loginPage.replace("login.do", "retry.do");
                    if (remainingAttempts == 0) {
                        redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams))
                                + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                                + BasicAuthenticatorConstants.FAILED_USERNAME
                                + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME),
                                        BasicAuthenticatorConstants.UTF_8)
                                + "&remainingAttempts=0";
                    } else {
                        redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams))
                                + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                                + BasicAuthenticatorConstants.FAILED_USERNAME
                                + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME),
                                        BasicAuthenticatorConstants.UTF_8);
                    }
                    response.sendRedirect(redirectURL);

                } else if (errorCode.equals(UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST)) {
                    retryParam = retryParam + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                            + BasicAuthenticatorConstants.FAILED_USERNAME
                            + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME),
                                    BasicAuthenticatorConstants.UTF_8);
                    response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                            + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":"
                            + BasicAuthenticatorConstants.LOCAL + retryParam);
                }
            } else {
                response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                        + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":"
                        + BasicAuthenticatorConstants.LOCAL + retryParam);
            }
        } else {
            String errorCode = errorContext != null ? errorContext.getErrorCode() : null;
            if (errorCode != null && errorCode.equals(UserCoreConstants.ErrorCode.USER_IS_LOCKED)) {
                String redirectURL = loginPage.replace("login.do", "retry.do");
                redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams))
                        + BasicAuthenticatorConstants.FAILED_USERNAME
                        + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME),
                                BasicAuthenticatorConstants.UTF_8);
                response.sendRedirect(redirectURL);

            } else {
                response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                        + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":"
                        + BasicAuthenticatorConstants.LOCAL + retryParam);
            }
        }

    } catch (IOException e) {
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:cz.mzk.editor.server.ScanImgServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.addDateHeader("Last-Modified", new Date().getTime());
    resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
    resp.addDateHeader("Expires", DateUtils.addMonths(new Date(), 1).getTime());
    boolean full = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_FULL));
    String topSpace = req.getParameter(Constants.URL_PARAM_TOP_SPACE);
    String urlHeight = req.getParameter(Constants.URL_PARAM_HEIGHT);

    String uuid = req.getParameter(Constants.URL_PARAM_UUID);

    if (uuid == null || "".equals(uuid)) {
        uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_SCANS_PREFIX)
                + Constants.SERVLET_SCANS_PREFIX.length() + 1);
    }//from   w ww  .j a v a2s .com

    StringBuffer baseUrl = new StringBuffer();
    baseUrl.append("http://");
    if (!URLS.LOCALHOST()) {
        baseUrl.append(req.getServerName());
    } else {
        String hostname = config.getHostname();
        if (hostname.contains("://")) {
            baseUrl.append(hostname.substring(hostname.indexOf("://") + "://".length()));
        } else {
            baseUrl.append(hostname);
        }
    }
    StringBuffer sb = new StringBuffer();
    if (topSpace != null) {
        String metadata = IOUtils.toString(new URL(baseUrl + DJATOKA_URL_GET_METADATA + uuid),
                StandardCharsets.UTF_8);

        String height = null;
        height = metadata.substring(metadata.indexOf("ght\": \"") + 7, metadata.indexOf("\",\n\"dw"));
        String width = metadata.substring(metadata.indexOf("dth\": \"") + 7, metadata.indexOf("\",\n\"he"));

        int intHeight = Integer.parseInt(height);
        int intUrlHeight = Integer.parseInt(urlHeight);
        int intTopSpace = Integer.parseInt(topSpace);
        boolean isLower = intTopSpace > 0 && ((intHeight - intUrlHeight) < intTopSpace);
        String region = (isLower ? intHeight - intUrlHeight : (intTopSpace < 0 ? 0 : topSpace)) + ",1,"
                + urlHeight + "," + width;

        sb.append(baseUrl.toString()).append(DJATOKA_URL_FULL_PAGE_DETAIL).append(uuid)
                .append(DJATOKA_URL_REGION).append(region);

    } else {
        sb.append(baseUrl.toString())
                .append(full ? DJATOKA_URL_FULL_IMG : DJATOKA_URL + urlHeight + DJATOKA_URL_SUFFIX)
                .append(uuid);
    }
    resp.setContentType("image/jpeg");
    resp.sendRedirect(resp.encodeRedirectURL(sb.toString()));
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/*from  w  ww .j  a  v  a2 s.  co  m*/
        String userApprovedParamS = req.getParameter(ProxyUriUtils.PROXY_APPROVAL_PARAM);
        boolean userWasWarned = false;
        boolean userApproved = (userApprovedParamS != null && Boolean.valueOf(userApprovedParamS));
        boolean securityEnabled = isSecurityEnabled();
        final String remoteUser = req.getRemoteUser();
        final String pathInfo = req.getPathInfo();

        String parts[] = pathInfo.split("/", 3);
        if (parts.length < 2) {
            LOG.warn(remoteUser + " Gave an invalid proxy path " + pathInfo);
            notFound(resp, "Your path appears to be formatted incorrectly.");
            return;
        }
        //parts[0] is empty because path info always starts with a /
        String appId = parts[1];
        String rest = parts.length > 2 ? parts[2] : "";
        ApplicationId id = Apps.toAppID(appId);
        if (id == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + appId + " that is invalid");
            notFound(resp, appId + " appears to be formatted incorrectly.");
            return;
        }

        if (securityEnabled) {
            String cookieName = getCheckCookieName(id);
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (cookieName.equals(c.getName())) {
                        userWasWarned = true;
                        userApproved = userApproved || Boolean.valueOf(c.getValue());
                        break;
                    }
                }
            }
        }

        boolean checkUser = securityEnabled && (!userWasWarned || !userApproved);

        ApplicationReport applicationReport = null;
        try {
            applicationReport = getApplicationReport(id);
        } catch (ApplicationNotFoundException e) {
            applicationReport = null;
        }
        if (applicationReport == null) {
            LOG.warn(req.getRemoteUser() + " Attempting to access " + id + " that was not found");

            URI toFetch = ProxyUriUtils.getUriFromTrackingPlugins(id, this.trackingUriPlugins);
            if (toFetch != null) {
                resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
                return;
            }

            notFound(resp, "Application " + appId + " could not be found, " + "please try the history server");
            return;
        }
        String original = applicationReport.getOriginalTrackingUrl();
        URI trackingUri = null;
        // fallback to ResourceManager's app page if no tracking URI provided
        if (original == null || original.equals("N/A")) {
            resp.sendRedirect(resp.encodeRedirectURL(StringHelper.pjoin(rmAppPageUrlBase, id.toString())));
            return;
        } else {
            if (ProxyUriUtils.getSchemeFromUrl(original).isEmpty()) {
                trackingUri = ProxyUriUtils.getUriFromAMUrl(WebAppUtils.getHttpSchemePrefix(conf), original);
            } else {
                trackingUri = new URI(original);
            }
        }

        String runningUser = applicationReport.getUser();
        if (checkUser && !runningUser.equals(remoteUser)) {
            LOG.info("Asking " + remoteUser + " if they want to connect to the " + "app master GUI of " + appId
                    + " owned by " + runningUser);
            warnUserPage(resp, ProxyUriUtils.getPathAndQuery(id, rest, req.getQueryString(), true), runningUser,
                    id);
            return;
        }
        URI toFetch = new URI(trackingUri.getScheme(), trackingUri.getAuthority(),
                StringHelper.ujoin(trackingUri.getPath(), rest), req.getQueryString(), null);

        LOG.info(req.getRemoteUser() + " is accessing unchecked " + toFetch + " which is the app master GUI of "
                + appId + " owned by " + runningUser);

        switch (applicationReport.getYarnApplicationState()) {
        case KILLED:
        case FINISHED:
        case FAILED:
            resp.sendRedirect(resp.encodeRedirectURL(toFetch.toString()));
            return;
        }
        Cookie c = null;
        if (userWasWarned && userApproved) {
            c = makeCheckCookie(id, true);
        }
        proxyLink(req, resp, toFetch, c, getProxyHost());

    } catch (URISyntaxException e) {
        throw new IOException(e);
    } catch (YarnException e) {
        throw new IOException(e);
    }
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void create(HttpServletRequest req, HttpServletResponse resp) {

    String id = null;/*from   w  w  w.ja v  a 2s. c  o  m*/
    String repositoryName;
    String name;
    String description;
    String type;
    String keywords = null;
    try {
        type = getField(req, resp, "type");
        if (!type.equals("category")) {
            id = getField(req, resp, "id");
        }
        if (type.equals("document")) {
            keywords = getField(req, resp, "keywords");
        }
        repositoryName = getField(req, resp, "repository");
        name = getField(req, resp, "name");
        description = getField(req, resp, "description");
    } catch (FieldNotFoundException e) {
        return;
    }
    Ticket ticket = TicketService.getTicketService().getTicket(req, repositoryName);
    RepositoryService repositoryService = JLibraryServiceFactory.getInstance(profile).getRepositoryService();

    try {
        Repository repository = repositoryService.findRepository(repositoryName, ticket);
        repository.setServerProfile(profile);

        if (type.equals("directory")) {
            Directory directory = new Directory();
            directory.setName(name);
            directory.setDescription(description);
            directory.setParent(id);
            directory.setPosition(new Integer(1));
            DirectoryProperties properties = directory.dumpProperties();
            directory = repositoryService.createDirectory(ticket, properties);
            statsService.incCreatedDirectories();
            StringBuilder url = new StringBuilder(getRepositoryURL(req, repositoryName));
            url.append(directory.getPath());
            resp.sendRedirect(resp.encodeRedirectURL(url.toString()));
        } else if (type.equals("document")) {
            StringBuilder url = new StringBuilder(getRepositoryURL(req, repositoryName));

            Author author = null;
            try {
                author = repositoryService.findAuthorByName(ticket, ticket.getUser().getName());
            } catch (AuthorNotFoundException anfe) {
                author = Author.UNKNOWN;
            }
            Document document = new Document();
            document.setName(name);
            document.setDescription(description);
            document.setParent(id);
            document.setPosition(new Integer(1));
            document.setImportance(Node.IMPORTANCE_MEDIUM);
            document.setDate(new Date());
            document.setRelations(new HashSet());
            document.addCategory(Category.UNKNOWN);

            DocumentMetaData metaData = new DocumentMetaData();
            metaData.setDate(new Date());
            metaData.setTitle(name);
            metaData.setKeywords(keywords);
            metaData.setUrl(url.toString());
            metaData.setAuthor(author);
            document.setMetaData(metaData);
            byte[] dataContent = null;
            String content = req.getParameter("content");
            dataContent = content.getBytes();
            document.setPath(Text.escape(name) + ".html");
            document.setTypecode(Types.HTML_DOCUMENT);
            DocumentProperties properties = document.dumpProperties();
            document = repositoryService.createDocument(ticket, properties);
            statsService.incCreatedDocuments();
            if (dataContent != null) {
                repositoryService.updateContent(ticket, document.getId(), dataContent);
            } else {
                logErrorAndForward(req, resp, repositoryName, null,
                        "There was a problem trying to upload the document.");
            }
            String redirectUrl = getRootURL(req) + "/forward?method=documentcategories&repository="
                    + repositoryName + "&id=" + document.getId();
            resp.sendRedirect(resp.encodeRedirectURL(redirectUrl));
        } else if (type.equals("category")) {
            Category category = new Category();
            category.setId(""); //TODO: This is a bug, is to make dumpProperties work propertly
            category.setName(name);
            category.setDescription(description);
            category.setParent(null);
            category.setRepository(repository.getId());
            CategoryProperties properties = category.dumpProperties();
            category = repositoryService.createCategory(ticket, properties);
            statsService.incCreatedCategories();
            String url = getRepositoryURL(req, repositoryName) + "/categories/" + category.getName();
            resp.sendRedirect(resp.encodeRedirectURL(url));
        } else {
            String error = "Invalid operation : " + type;
            logErrorAndForward(req, resp, repositoryName, new InvalidOperationException(error), error);
        }

        resp.getOutputStream().flush();
    } catch (Exception e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem trying to create the object.");
    }
}

From source file:at.gv.egovernment.moa.id.configuration.filter.AuthenticationFilter.java

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterchain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) req;
    HttpServletResponse httpServletResponse = (HttpServletResponse) resp;

    HttpSession session = httpServletRequest.getSession();

    Object authuserobj = session.getAttribute(Constants.SESSION_AUTH);
    AuthenticatedUser authuser = (AuthenticatedUser) authuserobj;

    String requestURL = WebAppUtil.getRequestURLWithParameters(httpServletRequest, true);

    log.trace("Request URL: " + requestURL);

    AuthenticationManager authManager = AuthenticationManager.getInstance();
    if (!authManager.isActiveUser(authuser)) {
        //user is not active anymore. Invalidate session and reauthenticate user
        String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID);
        session.invalidate();/*from w ww  . ja va  2 s  .  co  m*/
        authuser = null;

        //TODO: set infotext

        session = httpServletRequest.getSession(true);
        session.setAttribute(Constants.SESSION_PVP2REQUESTID, authID);
    }

    if (authuser == null && !this.isExcluded(requestURL)) {

        if (config.isLoginDeaktivated()) {
            //add dummy Daten
            log.warn("Authentication is deaktivated. Dummy authentication-information are used!");

            if (authuser == null) {
                int sessionTimeOut = session.getMaxInactiveInterval();
                Date sessionExpired = new Date(
                        new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS));

                authuser = AuthenticatedUser.generateDefaultUser(sessionExpired);
                authManager.setActiveUser(authuser);

                //authuser = new AuthenticatedUser(1, "Max", "TestUser", true, false);
                httpServletRequest.getSession().setAttribute(Constants.SESSION_AUTH, authuser);
            }

            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                if (loginPageForward) {
                    log.debug("Authenticated page is set. Forwarding to \"" + getAuthenticatedPage() + "\".");
                    RequestDispatcher dispatcher = req.getRequestDispatcher(getAuthenticatedPage());
                    dispatcher.forward(httpServletRequest, httpServletResponse);
                } else {
                    log.debug("Authenticated page is set. Redirecting to \"" + getAuthenticatedPage() + "\".");
                    httpServletResponse
                            .sendRedirect(httpServletResponse.encodeRedirectURL(getAuthenticatedPage()));
                }
                return;
            }

        } else {
            if (MiscUtil.isNotEmpty(getAuthenticatedPage())) {
                log.debug(
                        "Unable to find authentication data. Authenticated page is given so there is no need to save original request url. "
                                + (loginPageForward ? "Forwarding" : "Redirecting") + " to login page \""
                                + loginPage + "\".");

            } else {
                log.debug("Unable to find authentication data. Storing request url and "
                        + (loginPageForward ? "forwarding" : "redirecting") + " to login page \"" + loginPage
                        + "\".");
                session.setAttribute(STORED_REQUEST_URL_ID, requestURL);

            }

            if (loginPageForward) {
                RequestDispatcher dispatcher = req.getRequestDispatcher(loginPage);
                dispatcher.forward(httpServletRequest, httpServletResponse);
                return;

            } else {
                httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(loginPage));
                return;

            }
        }

    } else {
        try {
            filterchain.doFilter(req, resp);

        } catch (Exception e) {

            //String redirectURL = "./index.action";
            //HttpServletResponse httpResp = (HttpServletResponse) resp;
            //redirectURL = httpResp.encodeRedirectURL(redirectURL);
            //resp.setContentType("text/html");
            //((HttpServletResponse) resp).setStatus(302);
            //httpResp.addHeader("Location", redirectURL);
            //log.warn("A Filter Error occurs -> Redirect to Login-Form");
        }
    }
}