Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

In this page you can find the example usage for java.io PrintWriter append.

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * Login and return a Saml token as a result
 * //from   w w w.j a  v a2  s.  co  m
 * @param htServiceRequest
 *            the service request
 * @param servletResponse
 *            the servlet response
 * @param pwOut
 *            the output PrintWriter
 * @throws ASelectException
 */
private void handleLoginToken(HashMap htServiceRequest, HttpServletResponse servletResponse, PrintWriter pwOut)
        throws ASelectException {
    final int SPLIT_HEADER = 3500;
    String sMethod = "handleLoginToken";
    AuthSPHandlerManager _authspHandlerManager = AuthSPHandlerManager.getHandle();
    String sStatus = "401 Unauthorized";

    String sResponse = "";

    String sAppId = (String) htServiceRequest.get("app_id");
    String sAuthSp = (String) htServiceRequest.get("authsp");
    String sUid = (String) htServiceRequest.get("uid");
    String sPassword = (String) htServiceRequest.get("password");
    String sSharedSecret = (String) htServiceRequest.get("shared_secret");

    String sOutputFormat = (String) htServiceRequest.get("output_format");

    String sSignature = (String) htServiceRequest.get("signature");
    //      _systemLogger.log(Level.INFO, MODULE, sMethod, "reveived sSignature:" + sSignature);

    boolean sSigningRequired = _applicationManager.isSigningRequired(sAppId);
    //      _systemLogger.log(Level.INFO, MODULE, sMethod, "sSigningRequired:" + sSigningRequired);

    String sApplSharedSecret = _applicationManager.getApplication(sAppId).getSharedSecret();
    //      _systemLogger.log(Level.INFO, MODULE, sMethod, "sApplSharedSecret:" + sApplSharedSecret);

    //      if ("".equals(sAppId) || "".equals(sAuthSp) || "".equals(sUid) ||
    if (sAppId == null || "".equals(sAppId) || sAuthSp == null || "".equals(sAuthSp) || sUid == null
            || "".equals(sUid) ||
            //               "".equals(sPassword)|| "".equals(sSharedSecret)) {
            //         "".equals(sPassword)|| ( !sSigningRequired && "".equals(sSharedSecret) )) {
            sPassword == null || "".equals(sPassword)
            || (sApplSharedSecret != null && (sSharedSecret == null || "".equals(sSharedSecret)))
            || (sSigningRequired && (sSignature == null || "".equals(sSignature)))) {
        _systemLogger.log(Level.WARNING, MODULE, sMethod, "Mandatory parameter is missing");
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
    }

    // Perform an authenticate request
    _systemLogger.log(Level.INFO, MODULE, sMethod, "AUTHN { ");
    HashMap<String, String> hmRequest = new HashMap<String, String>();
    hmRequest.put("request", "authenticate");
    hmRequest.put("app_id", sAppId);
    hmRequest.put("a-select-server", _sMyServerId);
    hmRequest.put("app_url", "login_token");
    hmRequest.put("shared_secret", sSharedSecret);

    if (sSigningRequired) { // not defensive because of backward compatibility
        hmRequest.put("check-signature", "true");
        hmRequest.put("signature", sSignature);
    } else {
        hmRequest.put("check-signature", "false"); // this is an internal call, so don't
    }

    // No "usi" available in this entry
    hmRequest.put("usi", Tools.generateUniqueSensorId()); // 20120111, Bauke added
    _systemLogger.log(Level.FINEST, MODULE, sMethod, "hmRequest=" + hmRequest);

    // Exception for bad shared_secret:
    HashMap<String, Object> hmResponse = handleAuthenticateAndCreateSession(hmRequest, null);
    _systemLogger.log(Level.FINEST, MODULE, sMethod, "hmResponse=" + hmResponse);

    String sResultCode = (String) hmResponse.get("result_code");
    if (!sResultCode.equals(Errors.ERROR_ASELECT_SUCCESS)) { // never happens (either success or exception is raised
        _systemLogger.log(Level.WARNING, MODULE, sMethod, "} AUTHN unsuccessful, result_code=" + sResultCode);
        throw new ASelectException(Errors.ERROR_ASELECT_IO);
    }
    _systemLogger.log(Level.FINEST, MODULE, sMethod, "} AUTHN htResponse=" + hmResponse);

    // Retrieve the session just created
    String sRid = (String) hmResponse.get("rid");
    _systemLogger.log(Level.INFO, MODULE, sMethod, "Supplied rid=" + sRid);

    // The session was created by handleAuthenticateAndCreateSession()
    _htSessionContext = (HashMap) hmResponse.get("session"); // 20120404, Bauke: was getSessionContext(sRid)
    if (_htSessionContext == null) {
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_SESSION_EXPIRED);
    }
    _htSessionContext.put("direct_authsp", sAuthSp); // for handleDirectLogin2
    _htSessionContext.put("organization", _sMyOrg);
    _htSessionContext.put("client_ip", "login_token");

    _sessionManager.setUpdateSession(_htSessionContext, _systemLogger); // 20120401, Bauke: postpone session action

    // Check login user and password
    HashMap<String, String> hmDirectRequest = new HashMap<String, String>();
    hmDirectRequest.put("request", "direct_login2");
    hmDirectRequest.put("rid", sRid);
    hmDirectRequest.put("user_id", sUid);
    hmDirectRequest.put("password", sPassword);

    // Only perform user/password authentication (will update the session):
    IAuthSPDirectLoginProtocolHandler oProtocolHandler = _authspHandlerManager
            .getAuthSPDirectLoginProtocolHandler(sAuthSp);
    _systemLogger.log(Level.FINEST, MODULE, sMethod, "HttpSR=" + servletResponse);
    boolean bSuccess = oProtocolHandler.handleDirectLoginRequest(hmDirectRequest, null/*serlvet request*/,
            null/*servlet response*/, _htSessionContext, null/*additional*/, null /*output writer*/,
            _sMyServerId, "en", "nl");
    _systemLogger.log(Level.FINEST, MODULE, sMethod, "Success=" + bSuccess + " hm=" + hmDirectRequest);

    // Pass result in the header, but only if successful
    if (bSuccess) {
        sStatus = "200 OK";
        // Reload session for results
        _htSessionContext = _sessionManager.getSessionContext(sRid);
        if (_htSessionContext == null) {
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_SESSION_EXPIRED);
        }

        // Gather attributes
        HashMap hmContext = new HashMap();
        hmContext.put("uid", sUid);
        hmContext.put("app_id", sAppId);
        hmContext.put("authsp", sAuthSp);
        hmContext.put("organization", _sMyOrg);
        Utils.copyHashmapValue("authsp_type", hmContext, _htSessionContext);
        Utils.copyHashmapValue("authsp_level", hmContext, _htSessionContext);

        AttributeGatherer oAttributeGatherer = AttributeGatherer.getHandle();
        HashMap<String, Object> htAttribs = oAttributeGatherer.gatherAttributes(hmContext);

        // Return Saml 20 token
        String subject = sRid.toString(); // transientID, elsewhere the TGT value is used

        String sWantSigning = "true"; // always signing on
        Assertion assertion = HandlerTools.createAttributeStatementAssertion(htAttribs, _sServerUrl, subject,
                "true".equalsIgnoreCase(sWantSigning));
        String sResult = XMLHelper.nodeToString(assertion.getDOM());
        _systemLogger.log(Level.FINE, MODULE, sMethod, "sResult=" + sResult);

        if ("saml".equalsIgnoreCase(sOutputFormat)) {
            sResponse = sResult;
        } else if ("samlhtml".equalsIgnoreCase(sOutputFormat)) {
            sResponse = StringEscapeUtils.escapeHtml(sResult);
        } else if ("cgi".equalsIgnoreCase(sOutputFormat)) {
            sResponse = org.aselect.server.utils.Utils.serializeAttributes(htAttribs);
            BASE64Decoder b64dec = new BASE64Decoder();
            sResponse = new String(b64dec.decodeBuffer(sResponse));
        } else if ("cgibase64".equalsIgnoreCase(sOutputFormat)) {
            sResponse = org.aselect.server.utils.Utils.serializeAttributes(htAttribs);
        } else {
            // backward compatibility
            sResponse = "<html><head><title>" + sStatus + "</title></head><body><h1>" + sStatus
                    + "</h1></body></html>";
            try {
                BASE64Encoder b64enc = new BASE64Encoder();
                sResult = b64enc.encode(sResult.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod, e.getMessage(), e);
                throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
            }

            // Set headers, split in chunks
            for (int i = 1;; i++) {
                int len = sResult.length();
                int hdrLen = (len <= SPLIT_HEADER) ? len : SPLIT_HEADER;
                _systemLogger.log(Level.FINE, MODULE, sMethod, "i=" + i + " len=" + len + " hdrLen=" + hdrLen);
                servletResponse.setHeader("X-saml-attribute-token" + Integer.toString(i),
                        sResult.substring(0, hdrLen));
                // pwOut.flush() at this point will only set the first header 
                if (len <= SPLIT_HEADER)
                    break;
                sResult = sResult.substring(SPLIT_HEADER);
            }
        }
        servletResponse.setStatus(HttpServletResponse.SC_OK);
    } else {
        //         servletResponse.setStatus(401);
        _systemLogger.log(Level.FINE, MODULE, sMethod, "Sending UNAUTHORIZED");
        servletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }

    AuthenticationLogger authenticationLogger = ASelectAuthenticationLogger.getHandle();
    authenticationLogger.log(new Object[] { "login_token", sUid, (String) htServiceRequest.get("client_ip"),
            _sMyOrg, sAppId, bSuccess ? "granted" : "denied" });

    pwOut.flush(); // otherwise: java.lang.ArrayIndexOutOfBoundsException: 8192 when output gets large
    //      pwOut.append("<html><head><title>"+sStatus+"</title></head><body><h1>"+sStatus+"</h1></body></html>");
    _systemLogger.log(Level.FINE, MODULE, sMethod, "Sending response=" + sResponse);
    pwOut.append(sResponse);
    _systemLogger.log(Level.FINE, MODULE, sMethod, "done");
}