Example usage for javax.servlet.http HttpServletResponse SC_FOUND

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

Introduction

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

Prototype

int SC_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_FOUND.

Click Source Link

Document

Status code (302) indicating that the resource reside temporarily under a different URI.

Usage

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint.java

/**
 * @param consent/*from   w  ww  . jav  a2 s  .  c o  m*/
 * @param sessionDataCacheEntry
 * @return
 * @throws OAuthSystemException
 */
private String handleUserConsent(HttpServletRequest request, String consent, OAuth2Parameters oauth2Params,
        SessionDataCacheEntry sessionDataCacheEntry, OIDCSessionState sessionState)
        throws OAuthSystemException {

    String applicationName = sessionDataCacheEntry.getoAuth2Parameters().getApplicationName();
    AuthenticatedUser loggedInUser = sessionDataCacheEntry.getLoggedInUser();
    String clientId = sessionDataCacheEntry.getoAuth2Parameters().getClientId();

    boolean skipConsent = EndpointUtil.getOAuthServerConfiguration().getOpenIDConnectSkipeUserConsentConfig();
    if (!skipConsent) {
        boolean approvedAlways = OAuthConstants.Consent.APPROVE_ALWAYS.equals(consent) ? true : false;
        if (approvedAlways) {
            OpenIDConnectUserRPStore.getInstance().putUserRPToStore(loggedInUser, applicationName,
                    approvedAlways, clientId);
        }
    }

    OAuthResponse oauthResponse = null;
    String responseType = oauth2Params.getResponseType();

    // authorizing the request
    OAuth2AuthorizeRespDTO authzRespDTO = authorize(oauth2Params, sessionDataCacheEntry);

    if (authzRespDTO != null && authzRespDTO.getErrorCode() == null) {
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        // all went okay
        if (StringUtils.isNotBlank(authzRespDTO.getAuthorizationCode())) {
            builder.setCode(authzRespDTO.getAuthorizationCode());
            addUserAttributesToCache(sessionDataCacheEntry, authzRespDTO.getAuthorizationCode(),
                    authzRespDTO.getCodeId());
        }
        if (StringUtils.isNotBlank(authzRespDTO.getAccessToken())
                && !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType)
                && !OAuthConstants.NONE.equalsIgnoreCase(responseType)) {
            builder.setAccessToken(authzRespDTO.getAccessToken());
            builder.setExpiresIn(authzRespDTO.getValidityPeriod());
            builder.setParam(OAuth.OAUTH_TOKEN_TYPE, "Bearer");
        }
        if (StringUtils.isNotBlank(authzRespDTO.getIdToken())) {
            builder.setParam("id_token", authzRespDTO.getIdToken());
        }
        if (StringUtils.isNotBlank(oauth2Params.getState())) {
            builder.setParam(OAuth.OAUTH_STATE, oauth2Params.getState());
        }
        String redirectURL = authzRespDTO.getCallbackURI();

        if (RESPONSE_MODE_FORM_POST.equals(oauth2Params.getResponseMode())) {
            String authenticatedIdPs = sessionDataCacheEntry.getAuthenticatedIdPs();
            if (authenticatedIdPs != null && !authenticatedIdPs.isEmpty()) {
                builder.setParam("AuthenticatedIdPs", sessionDataCacheEntry.getAuthenticatedIdPs());
            }
            oauthResponse = builder.location(redirectURL).buildJSONMessage();
        } else {
            oauthResponse = builder.location(redirectURL).buildQueryMessage();
        }

        sessionState.setAuthenticated(true);

    } else if (authzRespDTO != null && authzRespDTO.getErrorCode() != null) {
        // Authorization failure due to various reasons
        sessionState.setAuthenticated(false);
        String errorMsg;
        if (authzRespDTO.getErrorMsg() != null) {
            errorMsg = authzRespDTO.getErrorMsg();
        } else {
            errorMsg = "Error occurred while processing the request";
        }
        OAuthProblemException oauthProblemException = OAuthProblemException.error(authzRespDTO.getErrorCode(),
                errorMsg);
        return EndpointUtil.getErrorRedirectURL(oauthProblemException, oauth2Params);

    } else {
        // Authorization failure due to various reasons
        sessionState.setAuthenticated(false);
        String errorCode = OAuth2ErrorCodes.SERVER_ERROR;
        String errorMsg = "Error occurred while processing the request";
        OAuthProblemException oauthProblemException = OAuthProblemException.error(errorCode, errorMsg);
        return EndpointUtil.getErrorRedirectURL(oauthProblemException, oauth2Params);
    }

    //When response_mode equals to form_post, body parameter is passed back.
    if (RESPONSE_MODE_FORM_POST.equals(oauth2Params.getResponseMode())
            && StringUtils.isNotEmpty(oauthResponse.getBody())) {
        return oauthResponse.getBody();
    } else {
        //When responseType equal to "id_token" the resulting token is passed back as a query parameter
        //According to the specification it should pass as URL Fragment
        if (OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType)) {
            if (authzRespDTO.getCallbackURI().contains("?")) {
                return authzRespDTO.getCallbackURI() + "#" + StringUtils
                        .substring(oauthResponse.getLocationUri(), authzRespDTO.getCallbackURI().length() + 1);
            } else {
                return oauthResponse.getLocationUri().replace("?", "#");
            }
        } else {
            return appendAuthenticatedIDPs(sessionDataCacheEntry, oauthResponse.getLocationUri());
        }
    }
}

From source file:org.jahia.bin.Render.java

/**
 * This method allows you to define where you want to redirect the user after request.
 *
 * @param url//from   w  ww .j a v a  2s  . c o m
 * @param path
 * @param req
 * @param resp
 * @param parameters
 * @param bypassCache If true we will append a parameter to the URL that should match the id of the resource to refresh
 * @throws IOException
 */
public static void performRedirect(String url, String path, HttpServletRequest req, HttpServletResponse resp,
        Map<String, List<String>> parameters, boolean bypassCache) throws IOException {
    String renderedURL = null;

    List<String> stringList = parameters.get(NEW_NODE_OUTPUT_FORMAT);
    String outputFormat = !CollectionUtils.isEmpty(stringList) && stringList.get(0) != null ? stringList.get(0)
            : "html";

    stringList = parameters.get(REDIRECT_HTTP_RESPONSE_CODE);
    int responseCode = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? Integer.parseInt(stringList.get(0))
            : HttpServletResponse.SC_SEE_OTHER;

    stringList = parameters.get(REDIRECT_TO);
    String stayOnPage = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
            ? StringUtils.substringBeforeLast(stringList.get(0), ";")
            : null;

    if (!Login.isAuthorizedRedirect(req, stayOnPage, true)) {
        logger.warn("Unauthorized attempt redirect to {}", stayOnPage);
        stayOnPage = null;
    }

    if (!StringUtils.isEmpty(stayOnPage)) {
        renderedURL = stayOnPage + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    } else if (!StringUtils.isEmpty(url)) {
        String requestedURL = req.getRequestURI();
        //            String encodedPath = URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
        String decodedURL = URLDecoder.decode(requestedURL, "UTF-8");

        int index = decodedURL.indexOf(path);

        renderedURL = decodedURL.substring(0, index) + url
                + (!StringUtils.isEmpty(outputFormat) ? "." + outputFormat : "");
    }
    if (bypassCache) {
        stringList = parameters.get(RESOURCE_ID);
        String formuuid = !CollectionUtils.isEmpty(stringList) && !StringUtils.isBlank(stringList.get(0))
                ? stringList.get(0)
                : null;
        if (formuuid != null) {
            renderedURL = renderedURL + "?ec=" + formuuid;
        }
    }
    if (!StringUtils.isEmpty(renderedURL)) {
        String redirect = resp.encodeRedirectURL(renderedURL);
        if (SettingsBean.getInstance().isDisableJsessionIdParameter()) {
            String s = ";" + SettingsBean.getInstance().getJsessionIdParameterName();
            if (redirect.contains(s)) {
                redirect = SessionidRemovalResponseWrapper.removeJsessionId(redirect);
            }
        }
        if (StringUtils.isEmpty(stayOnPage)) {
            resp.setHeader("Location", redirect);
        } else if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
            resp.setHeader("Location", redirect);
        }
        if (responseCode == HttpServletResponse.SC_FOUND) {
            resp.sendRedirect(redirect);
        } else {
            resp.setStatus(responseCode);
        }
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

/**
 *
 * Tests the scenario of authorization request from the client
 *//*from   w  ww . ja  va 2s . c  o m*/
@Test(dataProvider = "provideAuthzRequestData", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest(String clientId, String redirectUri, String pkceChallengeCode,
        String pkceChallengeMethod, String prompt, boolean clientValid, boolean pkceEnabled,
        boolean supportPlainPkce, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap();
    Map<String, Object> requestAttributes = new HashMap();

    requestParams.put(CLIENT_ID, new String[] { clientId });

    // No consent data is saved in the cache yet and client doesn't send cache key
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { null });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE, new String[] { pkceChallengeCode });
    requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD, new String[] { pkceChallengeMethod });
    requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
    if (redirectUri != null) {
        requestParams.put("acr_values", new String[] { redirectUri });
        requestParams.put("claims", new String[] { "essentialClaims" });
        requestParams.put(MultitenantConstants.TENANT_DOMAIN,
                new String[] { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME });
    }
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    // No authentication data is saved in the cache yet and client doesn't send cache key
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, null);

    if (prompt != null) {
        requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { prompt });
    }

    boolean checkErrorCode = ERROR_PAGE_URL.equals(expectedLocation);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);

    mockOAuthServerConfiguration();

    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
    responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
    responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);

    when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);

    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);

    mockEndpointUtil();
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    when(oAuth2Service.isPKCESupportEnabled()).thenReturn(pkceEnabled);
    if (ERROR_PAGE_URL.equals(expectedLocation) && OAuthConstants.Prompt.NONE.equals(prompt)) {
        doThrow(new IdentityOAuth2Exception("error")).when(EndpointUtil.class, "getLoginPageURL", anyString(),
                anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap());
        checkErrorCode = false;
    }

    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);

    OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
    validationResponseDTO.setValidClient(clientValid);
    validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
    if (!clientValid) {
        validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
        validationResponseDTO.setErrorMsg("client is invalid");
    }
    validationResponseDTO.setPkceMandatory(supportPlainPkce);
    validationResponseDTO.setPkceSupportPlain(supportPlainPkce);
    when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);

    final String[] redirectUrl = new String[1];

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            String key = (String) invocation.getArguments()[0];
            redirectUrl[0] = key;
            return null;
        }
    }).when(httpServletResponse).sendRedirect(anyString());

    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }

    if (response != null) {
        assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");

        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");

        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)),
                "Location header not found in the response");
        String location = (String) responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0);
        assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");

        if (checkErrorCode) {
            assertTrue(location.contains(OAuth2ErrorCodes.INVALID_REQUEST),
                    "Expected error code not found in URL");
        }
    } else {
        assertNotNull(redirectUrl[0], "Response not redirected to outside");
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Handles a YaCy servlet template, reads the template and replaces the template
 * items with actual values. Because of supported server side includes target 
 * might not be the same as request.getPathInfo
 * /*  ww  w .j  a v a 2  s .  c o  m*/
 * @param target the path to the template
 * @param request the remote servlet request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Switchboard sb = Switchboard.getSwitchboard();

    String localeSelection = sb.getConfig("locale.language", "browser");
    if (localeSelection.endsWith("browser")) {
        String lng = request.getLocale().getLanguage();
        if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer
            localeSelection = "default";
        } else {
            localeSelection = lng;
        }
    }
    File targetFile = getLocalizedFile(target, localeSelection);
    File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile());
    String targetExt = target.substring(target.lastIndexOf('.') + 1);

    long now = System.currentTimeMillis();
    if (target.endsWith(".css")) {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year)
    } else if (target.endsWith(".png")) {
        // expires in 1 minute (reduce heavy image creation load)
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear();
        }
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60));
    } else {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now
    }

    if ((targetClass != null)) {
        serverObjects args = new serverObjects();
        Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters
        while (argNames.hasMoreElements()) {
            String argName = argNames.nextElement();
            // standard attributes are just pushed as string
            args.put(argName, request.getParameter(argName));
        }
        RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt);
        // add multipart-form fields to parameter
        if (ServletFileUpload.isMultipartContent(request)) {
            final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING);
            if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) {
                parseMultipart(new GZIPRequestWrapper(request), args);
            } else {
                parseMultipart(request, args);
            }
        }
        // eof modification to read attribute
        Object tmp;
        try {
            if (args.isEmpty()) {
                // yacy servlets typically test for args != null (but not for args .isEmpty())
                tmp = invokeServlet(targetClass, legacyRequestHeader, null);
            } else {
                tmp = invokeServlet(targetClass, legacyRequestHeader, args);
            }
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof InvalidURLLicenceException) {
                /* A non authaurized user is trying to fetch a image with a bad or already released license code */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            if (e.getCause() instanceof TemplateMissingParameterException) {
                /* A template is used but miss some required parameter */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        }

        if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) {

            net.yacy.cora.util.ByteBuffer result = null;

            if (tmp instanceof RasterPlotter) {
                final RasterPlotter yp = (RasterPlotter) tmp;
                // send an image to client
                result = RasterPlotter.exportImage(yp.getImage(), "png");
            } else if (tmp instanceof EncodedImage) {
                final EncodedImage yp = (EncodedImage) tmp;
                result = yp.getImage();
                /** When encodedImage is empty, return a code 500 rather than only an empty response 
                 * as it is better handled across different browsers */
                if (result == null || result.length() == 0) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    result.close();
                    return;
                }
                if (yp.isStatic()) { // static image never expires
                    response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour
                }
            } else if (tmp instanceof Image) {
                final Image i = (Image) tmp;

                // generate an byte array from the generated image
                int width = i.getWidth(null);
                if (width < 0) {
                    width = 96; // bad hack
                }
                int height = i.getHeight(null);
                if (height < 0) {
                    height = 96; // bad hack
                }
                final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                bi.createGraphics().drawImage(i, 0, 0, width, height, null);
                result = RasterPlotter.exportImage(bi, targetExt);
            }

            updateRespHeadersForImages(target, response);
            final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());
            response.setContentType(mimeType);
            response.setContentLength(result.length());
            response.setStatus(HttpServletResponse.SC_OK);

            result.writeTo(response.getOutputStream());
            result.close();
            return;
        }

        if (tmp instanceof InputStream) {
            /* Images and favicons can also be written directly from an inputStream */
            updateRespHeadersForImages(target, response);

            writeInputStream(response, targetExt, (InputStream) tmp);
            return;
        }

        servletProperties templatePatterns;
        if (tmp == null) {
            // if no args given, then tp will be an empty Hashtable object (not null)
            templatePatterns = new servletProperties();
        } else if (tmp instanceof servletProperties) {
            templatePatterns = (servletProperties) tmp;

            if (templatePatterns.getOutgoingHeader() != null) {
                // handle responseHeader entries set by servlet
                ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader();
                for (String hdrkey : tmpouthdr.keySet()) {
                    if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. )
                        String val = tmpouthdr.get(hdrkey);
                        if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN)
                            response.setHeader(hdrkey, tmpouthdr.get(hdrkey));
                        }
                    }
                }
                // handle login cookie
                if (tmpouthdr.getCookiesEntries() != null) {
                    for (Cookie c : tmpouthdr.getCookiesEntries()) {
                        response.addCookie(c);
                    }
                }
            }
        } else {
            templatePatterns = new servletProperties((serverObjects) tmp);
        }

        // handle YaCy http commands
        // handle action auth: check if the servlets requests authentication
        if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
            if (!request.authenticate(response)) {
                return;
            }
            //handle action forward
        } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
            String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");

            if (location.isEmpty()) {
                location = request.getPathInfo();
            }
            //TODO: handle equivalent of this from httpdfilehandler
            // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo());
            // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?

            response.setHeader(HeaderFramework.LOCATION, location);
            response.setStatus(HttpServletResponse.SC_FOUND);
            return;
        }

        if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {

            sb.setConfig("server.servlets.called",
                    appendPath(sb.getConfig("server.servlets.called", ""), target));
            if (args != null && !args.isEmpty()) {
                sb.setConfig("server.servlets.submitted",
                        appendPath(sb.getConfig("server.servlets.submitted", ""), target));
            }

            // add the application version, the uptime and the client name to every rewrite table
            templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
            templatePatterns.put(servletProperties.PEER_STAT_UPTIME,
                    ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID());
            templatePatterns.put(servletProperties.PEER_STAT_MYTIME,
                    GenericFormatter.SHORT_SECOND_FORMATTER.format());
            templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target));
            Seed myPeer = sb.peers.mySeed();
            templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
            templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
            boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2;
            templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol)

            templatePatterns.put("simpleheadernavbar",
                    sb.getConfig("decoration.simpleheadernavbar", "navbar-default"));

            // add navigation keys to enable or disable menu items
            templatePatterns.put("navigation-p2p",
                    sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
            templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0);
            String submitted = sb.getConfig("server.servlets.submitted", "");
            boolean crawler_enabled = true; /*
                                            submitted.contains("Crawler_p") ||
                                            submitted.contains("ConfigBasic") ||
                                            submitted.contains("Load_RSS_p");*/
            boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p")
                    || submitted.contains("CrawlStart");
            templatePatterns.put("navigation-crawlmonitor", crawler_enabled);
            templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0);
            templatePatterns.put("navigation-advanced", advanced_enabled);
            templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0);
            templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT,
                    sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, ""));
            templatePatterns.put("clientlanguage", localeSelection);

            String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());

            InputStream fis;
            long fileSize = targetFile.length();

            if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
                // read file completely into ram, avoid that too many files are open at the same time
                fis = new ByteArrayInputStream(FileUtils.read(targetFile));
            } else {
                fis = new BufferedInputStream(new FileInputStream(targetFile));
            }

            // set response header
            response.setContentType(mimeType);
            response.setStatus(HttpServletResponse.SC_OK);
            ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
            try {
                // apply templates
                TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns);

                // handle SSI
                parseSSI(bas.toByteArray(), request, response);
            } finally {
                try {
                    fis.close();
                } catch (IOException ignored) {
                    ConcurrentLog.warn("FILEHANDLER",
                            "YaCyDefaultServlet: could not close target file " + targetFile.getName());
                }

                try {
                    bas.close();
                } catch (IOException ignored) {
                    /* Should never happen with a ByteArrayOutputStream */
                }
            }
        }
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@DataProvider(name = "provideUserConsentData")
public Object[][] provideUserConsentData() {
    String authzCode = "67428657950009705658674645643";
    String accessToken = "56789876734982650746509776325";
    String idToken = "eyJzdWIiOiJQUklNQVJZXC9zdXJlc2hhdHQiLCJlbWFpbCI6InN1cmVzaGdlbXVudUBteW1haWwuY29tIiwibmFtZSI"
            + "6IlN1cmVzaCBBdHRhbmF5YWtlIiwiZmFtaWx5X25hbWUiOiJBdHRhbmF5YWtlIiwicHJlZmVycmVkX3VzZXJuYW1lIjoic3VyZXN"
            + "oZ2VtdW51IiwiZ2l2ZW5fbmFtZSI6IlN1cmVzaCJ9";

    // These values are provided to cover all the branches in handleUserConsent private method.
    return new Object[][] {
            { true, OAuthConstants.Consent.APPROVE_ALWAYS, false, OAuth2ErrorCodes.SERVER_ERROR, null, null,
                    null, null, null, null, null, HttpServletResponse.SC_FOUND, APP_REDIRECT_URL },

            { false, OAuthConstants.Consent.APPROVE_ALWAYS, true, null, authzCode, null, null, null, null,
                    "idp1", null, HttpServletResponse.SC_FOUND, APP_REDIRECT_URL },

            { false, OAuthConstants.Consent.APPROVE_ALWAYS, false, null, null, accessToken, null,
                    OAuthConstants.ACCESS_TOKEN, RESPONSE_MODE_FORM_POST, "idp1", "ACTIVE",
                    HttpServletResponse.SC_OK, null },

            { false, OAuthConstants.Consent.APPROVE_ALWAYS, false, null, null, accessToken, idToken,
                    OAuthConstants.ID_TOKEN, RESPONSE_MODE_FORM_POST, null, "ACTIVE", HttpServletResponse.SC_OK,
                    null },//from   w w  w .  j a  va  2s. c  om

            { false, OAuthConstants.Consent.APPROVE, false, null, null, accessToken, idToken,
                    OAuthConstants.NONE, RESPONSE_MODE_FORM_POST, "", "", HttpServletResponse.SC_OK, null },

            { false, OAuthConstants.Consent.APPROVE, false, null, null, accessToken, idToken,
                    OAuthConstants.ID_TOKEN, null, null, "ACTIVE", HttpServletResponse.SC_FOUND,
                    APP_REDIRECT_URL },

            { false, OAuthConstants.Consent.APPROVE, false, null, null, accessToken, null,
                    OAuthConstants.ID_TOKEN, null, null, "ACTIVE", HttpServletResponse.SC_FOUND,
                    APP_REDIRECT_URL },

            { false, OAuthConstants.Consent.APPROVE_ALWAYS, false, OAuth2ErrorCodes.INVALID_CLIENT, null, null,
                    null, null, null, null, null, HttpServletResponse.SC_FOUND, APP_REDIRECT_URL },

    };
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@Test(dataProvider = "provideDataForUserAuthz", groups = "testWithConnection")
public void testDoUserAuthz(String prompt, String idTokenHint, boolean hasUserApproved, boolean skipConsent,
        boolean idTokenHintValid, String loggedInUser, String idTokenHintSubject, String errorCode)
        throws Exception {
    AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);

    result.getSubject().setAuthenticatedSubjectIdentifier(loggedInUser);
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();

    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });

    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
    requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);

    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);

    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, null,
            APP_REDIRECT_URL);// w  ww  .  j av a 2s. c om
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    oAuth2Params.setPrompt(prompt);
    oAuth2Params.setIDTokenHint(idTokenHint);

    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
    when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
    when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
    when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);

    mockEndpointUtil();

    mockOAuthServerConfiguration();

    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);

    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString()))
            .thenReturn(hasUserApproved);

    spy(OAuth2Util.class);
    doReturn(idTokenHintValid).when(OAuth2Util.class, "validateIdToken", anyString());

    mockStatic(SignedJWT.class);
    if ("invalid".equals(idTokenHint)) {
        when(SignedJWT.parse(anyString())).thenThrow(new ParseException("error", 1));
    } else {
        when(SignedJWT.parse(anyString())).thenReturn(signedJWT);
    }
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    jwtClaimsSetBuilder.subject(idTokenHintSubject);
    JWTClaimsSet jwtClaimsSet = jwtClaimsSetBuilder.build();
    when(signedJWT.getJWTClaimsSet()).thenReturn(jwtClaimsSet);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");

    mockApplicationManagementService();

    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }

    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");

    if (errorCode != null) {
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");

        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)),
                "Location header not found in the response");
        String location = (String) responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0);
        assertTrue(location.contains(errorCode), "Expected error code not found in URL");
    }

}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@DataProvider(name = "provideOidcSessionData")
public Object[][] provideOidcSessionData() {
    Cookie opBrowserStateCookie = new Cookie("opbs", "2345678776gffdgdsfafa");
    OIDCSessionState previousSessionState1 = new OIDCSessionState();
    OIDCSessionState previousSessionState2 = new OIDCSessionState();

    previousSessionState1.setSessionParticipants(new HashSet<>(Arrays.asList(CLIENT_ID_VALUE)));
    previousSessionState2.setSessionParticipants(new HashSet<String>());

    String[] returnValues = new String[] { "http://localhost:8080/redirect?session_state=sessionStateValue",
            "<form method=\"post\" action=\"http://localhost:8080/redirect\">" };

    // This object provides values to cover the branches in ManageOIDCSessionState() private method
    return new Object[][] {
            { opBrowserStateCookie, previousSessionState1, APP_REDIRECT_URL, null, HttpServletResponse.SC_FOUND,
                    returnValues[0] },/*from  w  ww  . j a  va2  s.c  o m*/
            { opBrowserStateCookie, previousSessionState2, APP_REDIRECT_URL, RESPONSE_MODE_FORM_POST,
                    HttpServletResponse.SC_OK, returnValues[1] },
            { null, previousSessionState1, APP_REDIRECT_URL, null, HttpServletResponse.SC_FOUND,
                    returnValues[0] },
            { null, previousSessionState1, APP_REDIRECT_URL, null, HttpServletResponse.SC_FOUND,
                    returnValues[0] },
            { opBrowserStateCookie, null, APP_REDIRECT_URL, null, HttpServletResponse.SC_FOUND,
                    returnValues[0] }, };
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@Test(dependsOnGroups = "testWithConnection")
public void testIdentityOAuthAdminException() throws Exception {

    //OAuthAdminException will not occur due to introduce a new Service to get the App State instead directly use
    // dao/*from  ww  w  .  ja v a 2 s  .  c o  m*/
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();

    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS,
            AuthenticatorFlowStatus.SUCCESS_COMPLETED);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);

    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);

    connection.close(); // Closing connection to create SQLException
    mockEndpointUtil();
    mockStatic(OAuth2Util.OAuthURL.class);
    when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");

    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }

    assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND);
}

From source file:de.escidoc.core.test.aa.AaTestBase.java

/**
 * Tests logging out an user. Before logging out, the user is logged in.
 * //w ww  . j  a va  2  s .  co  m
 * @param loginname
 *            The login name of the user to log in and log out.
 * @param password
 *            The password of the user.
 * @throws Exception
 *             If anything fails.
 */
protected void doTestLogout(final String loginname, final String password) throws Exception {

    String userHandle = null;
    try {
        userHandle = login(loginname, password, true);
    } catch (final Exception e) {
        EscidocAbstractTest.failException("INIT: Log in of the user failed.", e);
    }
    assertNotNull(userHandle);

    PWCallback.setHandle(userHandle);

    try {
        logout(userHandle);

        // Check status-code when requesting resource with invalid handle
        final String httpUrl = getFrameworkUrl() + Constants.ROLE_BASE_URI + "/"
                + getObjidFromHref(ROLE_HREF_SYSTEM_ADMINISTRATOR);

        final int statusCode = getStatusCode(httpUrl);
        if (statusCode != HttpServletResponse.SC_FOUND) {

            throw new Exception(
                    "Retrieving resource with invalid handle " + "returned wrong status " + statusCode);
        }

    } catch (final Exception e) {
        EscidocAbstractTest.failException("Logging out of the user failed.", e);
    } finally {
        PWCallback.setHandle(PWCallback.DEFAULT_HANDLE);
    }
}