Example usage for java.util.zip DeflaterOutputStream write

List of usage examples for java.util.zip DeflaterOutputStream write

Introduction

In this page you can find the example usage for java.util.zip DeflaterOutputStream write.

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;//from  ww w.  j  av  a 2  s . co m
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

    try {
        // Get the Subject marshaller
        Marshaller marshaller = new LogoutRequestMarshaller();

        // Marshall the Subject
        //Element assertionElement = marshaller.marshall(lr);

        String xml = OpenSAMLUtils.xml2str(lr);
        xml = xml.substring(xml.indexOf("?>") + 2);

        if (logger.isDebugEnabled()) {
            logger.debug("=======AuthnRequest============");
            logger.debug(xml);
            logger.debug("=======AuthnRequest============");
        }

        byte[] bxml = xml.getBytes("UTF-8");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                new Deflater(Deflater.BEST_COMPRESSION, true));

        compressor.write(bxml);
        compressor.flush();
        compressor.close();

        String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
        StringBuffer redirURL = new StringBuffer();
        StringBuffer query = new StringBuffer();

        idBytes = new byte[20];
        random.nextBytes(idBytes);

        query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

        query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
        //http://www.w3.org/2000/09/xmldsig#rsa-sha1

        java.security.Signature signer = java.security.Signature.getInstance(javaAlg);

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        signer.update(query.toString().getBytes("UTF-8"));
        String base64Sig = new String(Base64.encodeBase64(signer.sign()));
        query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));

        redirURL.append(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:com.vmware.demo.SamlService.java

public String generateSAMLRequest(String assertionConsumerServiceURL, String nameIdFormat) {
    String samlRequest = "";

    try {/*from   w  ww.j a  v a  2s .  c  o  m*/
        // Generate ID
        String randId = "A71AB3E13";

        // Create an issuer Object
        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
        issuer.setValue(issuerString);

        // Create NameIDPolicy
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        if (StringUtils.isNotEmpty(nameIdFormat)) {
            nameIdPolicy.setFormat(nameIdFormat);
        }
        nameIdPolicy.setSPNameQualifier(issuerString);
        nameIdPolicy.setAllowCreate(true);

        // Create AuthnContextClassRef
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
                .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
        authnContextClassRef
                .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

        // Create RequestedAuthnContext
        RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                "AuthnRequest", "samlp");
        authRequest.setForceAuthn(false);
        authRequest.setIsPassive(false);
        authRequest.setIssueInstant(new DateTime());
        authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        authRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(randId);
        authRequest.setVersion(SAMLVersion.VERSION_20);
        Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(authRequest);
        org.w3c.dom.Element authDOM = marshaller.marshall(authRequest);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        String messageXML = rspWrt.toString();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        deflaterOutputStream.write(messageXML.getBytes());
        deflaterOutputStream.close();
        samlRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
        //samlRequest = URLEncoder.encode(samlRequest);

        logger.info("samlRequest: " + samlRequest);

    } catch (MarshallingException e) {
        logger.error("General Error", e);
    } catch (IOException e) {
        logger.error("General Error", e);
    }
    return samlRequest;
}

From source file:com.autonomy.aci.client.transport.impl.AbstractEncryptionCodec.java

/**
 * Deflates the passed in <tt>String</tt> and prefixes the result with <tt>AUTN:</tt> before returning.
 * @param bytes The byte array to deflate
 * @return The deflated string prefixed with <tt>AUTN:</tt> as a byte array
 * @throws EncryptionCodecException If an error occurred during processing
 *///  ww  w  . jav a2  s .  c o m
protected byte[] deflateInternal(final byte[] bytes) throws EncryptionCodecException {
    LOGGER.trace("deflateInternal() called...");

    // This is what will deflate for us...
    DeflaterOutputStream deflater = null;

    try {
        // Create the output container...
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Create the deflater...
        deflater = new DeflaterOutputStream(baos);

        LOGGER.debug("Deflating content...");

        // Deflate the input string...
        deflater.write(bytes);
        deflater.finish();

        // Get the deflated bytes...
        final byte[] deflated = baos.toByteArray();

        LOGGER.debug("Adding prefix to deflated content...");

        // Get The deflated array prefix of AUTN: in bytes...
        final byte[] prefix = "AUTN:".getBytes("UTF-8");

        // Copy both the prefix and the deflated query string into a new array...
        final byte[] toEncrypt = new byte[prefix.length + deflated.length];
        System.arraycopy(prefix, 0, toEncrypt, 0, prefix.length);
        System.arraycopy(deflated, 0, toEncrypt, prefix.length, deflated.length);

        LOGGER.debug("Returning deflated and prefixed string...");

        // Return the deflated query string...
        return toEncrypt;
    } catch (final IOException ioe) {
        throw new EncryptionCodecException("Unable to deflate the input.", ioe);
    } finally {
        IOUtils.getInstance().closeQuietly(deflater);
    }
}

From source file:com.giri.target.svr.SeleniumTestRunner.java

private String toB64Text(final String text, final boolean compress) throws Exception {
    final byte[] inputbs = text.getBytes(Charset.forName("UTF-8"));

    final byte[] bytesToConvert;
    if (compress) {
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        final Deflater d = new Deflater();
        final DeflaterOutputStream dout = new DeflaterOutputStream(bout, d);
        dout.write(inputbs);
        dout.close();/*from   w  ww .  j a  v a  2 s  .c  o  m*/
        bout.flush();
        bytesToConvert = bout.toByteArray();
    } else {
        bytesToConvert = inputbs;
    }

    final byte[] s64encBts = Base64.encodeBase64(bytesToConvert);

    return new String(s64encBts);
}

From source file:com.xwiki.authentication.saml.XWikiSAMLAuthenticator.java

public void showLogin(XWikiContext context) throws XWikiException {
    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();

    try {//from  ww  w  .java 2s .  c om
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to bootstrap saml module");
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to bootstrap saml module");
    }
    XMLObjectBuilderFactory builderFactory = org.opensaml.Configuration.getBuilderFactory();

    // Generate ID
    String randId = RandomStringUtils.randomAlphanumeric(42);
    if (LOG.isDebugEnabled())
        LOG.debug("Random ID: " + randId);

    String sourceurl = request.getParameter("xredirect");
    if (sourceurl == null) {
        if (context.getAction().startsWith("login"))
            sourceurl = context.getWiki().getURL("Main.WebHome", "view", context);
        else {
            context.getWiki();
            sourceurl = XWiki.getRequestURL(request).toString();
        }
    }

    request.getSession().setAttribute("saml_url", sourceurl);
    request.getSession().setAttribute("saml_id", randId);

    //Create an issuer Object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
    issuer.setValue(getSAMLIssuer(context));

    //Create NameIDPolicy
    NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
    NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
    nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    nameIdPolicy.setSPNameQualifier(getSAMLNameQualifier(context));
    nameIdPolicy.setAllowCreate(true);

    //Create AuthnContextClassRef
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
            .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
    authnContextClassRef
            .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

    //Create RequestedAuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    DateTime issueInstant = new DateTime();
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
            "AuthnRequest", "samlp");
    authRequest.setForceAuthn(false);
    authRequest.setIsPassive(false);
    authRequest.setIssueInstant(issueInstant);
    authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    authRequest.setAssertionConsumerServiceURL(getSAMLAuthenticatorURL(context));
    authRequest.setIssuer(issuer);
    authRequest.setNameIDPolicy(nameIdPolicy);
    authRequest.setRequestedAuthnContext(requestedAuthnContext);
    authRequest.setID(randId);
    authRequest.setVersion(SAMLVersion.VERSION_20);
    String stringRep = authRequest.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("New AuthnRequestImpl: " + stringRep);
        LOG.debug("Assertion Consumer Service URL: " + authRequest.getAssertionConsumerServiceURL());
    }

    // Now we must build our representation to put into the html form to be submitted to the idp
    MarshallerFactory mfact = org.opensaml.Configuration.getMarshallerFactory();
    Marshaller marshaller = (Marshaller) mfact.getMarshaller(authRequest);
    if (marshaller == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to get marshaller for " + authRequest);
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to get marshaller for " + authRequest);
    } else {
        Element authDOM;
        String samlRequest = "";
        try {
            authDOM = marshaller.marshall(authRequest);
            StringWriter rspWrt = new StringWriter();
            XMLHelper.writeNode(authDOM, rspWrt);
            String messageXML = rspWrt.toString();
            Deflater deflater = new Deflater(Deflater.DEFLATED, true);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream,
                    deflater);
            deflaterOutputStream.write(messageXML.getBytes());
            deflaterOutputStream.close();
            samlRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
            String outputString = new String(byteArrayOutputStream.toByteArray());
            samlRequest = URLEncoder.encode(samlRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Converted AuthRequest: " + messageXML);
                // LOG.debug("samlRequest: " + samlRequest);
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Failed to marshaller request for " + authRequest);
            }
            throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                    "Failed to marshaller request for " + authRequest);
        }

        String actionURL = getSAMLAuthenticatorURL(context);
        String url = actionURL + "?SAMLRequest=" + samlRequest;
        if (LOG.isInfoEnabled()) {
            LOG.info("Saml request sent to " + url);
        }
        try {
            response.sendRedirect(url);
            context.setFinished(true);
        } catch (IOException e) {
        }
    }
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public String encodeSAMLObject(SignableSAMLObject signableSAMLObject) throws MarshallingException, IOException {
    log.debug("Encoding SAML Object " + signableSAMLObject);

    // Now we must build our representation to put into the html form to be
    // submitted to the idp
    Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(signableSAMLObject);
    org.w3c.dom.Element authDOM = marshaller.marshall(signableSAMLObject);
    StringWriter rspWrt = new StringWriter();
    XMLHelper.writeNode(authDOM, rspWrt);
    String messageXML = rspWrt.toString();

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(messageXML.getBytes("UTF-8"));
    deflaterOutputStream.close();//from  w  w w . j  a v  a2s  .  c  o  m
    String samlRequestParameter = Shared.encodeBytes(byteArrayOutputStream.toByteArray());
    return samlRequestParameter;
}

From source file:PngEncoder.java

/**
 * Writes the IDAT (Image data) chunks to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *///from  www  .  jav a  2s.c o  m
private void writeIdatChunks(OutputStream out, Checksum csum) throws IOException {
    int rowWidth = width * outputBpp; // size of image data in a row in bytes.

    int row = 0;

    Deflater deflater = new Deflater(compressionLevel);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DeflaterOutputStream defOut = new DeflaterOutputStream(byteOut, deflater);

    byte[] filteredPixelQueue = new byte[rowWidth];

    // Output Pixel Queues
    byte[][] outputPixelQueue = new byte[2][rowWidth];
    Arrays.fill(outputPixelQueue[1], (byte) 0);
    int outputPixelQueueRow = 0;
    int outputPixelQueuePrevRow = 1;

    while (row < height) {
        if (filter == null) {
            defOut.write(0);
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            defOut.write(outputPixelQueue[outputPixelQueueRow], 0, rowWidth);
        } else {
            defOut.write(filter.getType());
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            filter.filter(filteredPixelQueue, outputPixelQueue[outputPixelQueueRow],
                    outputPixelQueue[outputPixelQueuePrevRow], outputBpp);
            defOut.write(filteredPixelQueue, 0, rowWidth);
        }

        ++row;
        outputPixelQueueRow = row & 1;
        outputPixelQueuePrevRow = outputPixelQueueRow ^ 1;
    }
    defOut.finish();
    byteOut.close();

    writeInt(out, byteOut.size());
    csum.reset();
    out.write(IDAT);
    byteOut.writeTo(out);
    writeInt(out, (int) csum.getValue());
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

private String deflate(byte[] msg) throws IOException {

    Deflater dfl = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DeflaterOutputStream dos = new DeflaterOutputStream(out, dfl);
    dos.write(msg);
    dos.close();// w w  w . ja  va  2s .co m

    return encode(out.toByteArray(), true);
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private String encryptToken(String codeTokenKeyName, Gson gson, UUID refreshToken)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
    byte[] bjson = refreshToken.toString().getBytes("UTF-8");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE,
            GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(codeTokenKeyName));

    byte[] encJson = cipher.doFinal(bjson);
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));

    Token token = new Token();
    token.setEncryptedRequest(base64d);//  w ww  . j  a v  a 2  s .c om
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    byte[] bxml = gson.toJson(token).getBytes("UTF-8");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(bxml);
    compressor.flush();
    compressor.close();

    String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
    return b64;
}

From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java

public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump,
        String jumpPage) throws MalformedURLException, ServletException {
    {/*www  . j a  v  a 2 s  . co  m*/
        RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

        HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
                .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

        boolean isMultiIdp = authParams.get("isMultiIdP") != null
                && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");

        String postAuthnReqTo = "";
        String redirAuthnReqTo = "";
        String assertionConsumerServiceURL = "";
        boolean signAuthnReq = false;

        String uri = (String) req.getAttribute(ProxyConstants.AUTH_REDIR_URI);
        if (uri == null) {
            uri = req.getRequestURI();
        }

        if (isMultiIdp) {

            URL url = new URL(req.getRequestURL().toString());
            String hostName = url.getHost();
            String dn = authParams.get("idpDir").getValues().get(0);

            try {
                StringBuffer b = new StringBuffer();

                LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("hostname", hostName).toString(),
                        new ArrayList<String>());
                if (!res.hasMore()) {
                    throw new ServletException("No IdP found");
                }

                LDAPEntry entry = res.next();
                postAuthnReqTo = entry.getAttribute("idpURL").getStringValue();

                redirAuthnReqTo = entry.getAttribute("idpRedirURL").getStringValue();

                assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);
                signAuthnReq = entry.getAttribute("signAuthnReq").getStringValue().equalsIgnoreCase("1");

            } catch (LDAPException e) {
                throw new ServletException("Could not load IdP data", e);
            }

        } else {
            postAuthnReqTo = authParams.get("idpURL").getValues().get(0);// "http://idp.partner.domain.com:8080/opensso/SSOPOST/metaAlias/testSaml2Idp";

            redirAuthnReqTo = authParams.get("idpRedirURL").getValues().get(0);

            assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);// "http://sp.localdomain.com:8080/SampleSP/echo";

            if (authParams.get("forceToSSL") != null
                    && authParams.get("forceToSSL").getValues().get(0).equalsIgnoreCase("true")) {
                if (!assertionConsumerServiceURL.startsWith("https")) {
                    assertionConsumerServiceURL = assertionConsumerServiceURL.replace("http://", "https://");
                }
            }

            signAuthnReq = authParams.get("signAuthnReq") != null
                    && authParams.get("signAuthnReq").getValues().get(0).equalsIgnoreCase("true");
        }

        ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

        AuthnRequestBuilder authnBuilder = new AuthnRequestBuilder();
        AuthnRequest authn = authnBuilder.buildObject();
        authn.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
        authn.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        //authn.setDestination(postAuthnReqTo);
        authn.setDestination(redirAuthnReqTo);
        DateTime dt = new DateTime();

        String authMechanism = authParams.get("authCtxRef").getValues().get(0);

        byte[] idBytes = new byte[20];
        random.nextBytes(idBytes);

        /*StringBuffer id = new StringBuffer();
        for (byte b : idBytes) {
           id.append(Hex.encode(idBytes));
        }*/

        StringBuffer b = new StringBuffer();
        b.append('f').append(Hex.encodeHexString(idBytes));

        String id = b.toString();

        authn.setIssueInstant(dt);
        //authn.setID(Long.toString(random.nextLong()));
        authn.setID(id.toString());
        session.setAttribute("AUTOIDM_SAML2_REQUEST", authn.getID());
        IssuerBuilder ib = new IssuerBuilder();
        Issuer issuer = ib.buildObject();
        issuer.setValue(assertionConsumerServiceURL);

        authn.setIssuer(issuer);
        //authn.setAssertionConsumerServiceIndex(0);
        //authn.setAttributeConsumingServiceIndex(0);

        NameIDPolicyBuilder nidbpb = new NameIDPolicyBuilder();
        NameIDPolicy nidp = nidbpb.buildObject();
        //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
        nidp.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");
        nidp.setAllowCreate(true);
        nidp.setSPNameQualifier(assertionConsumerServiceURL);
        //authn.setNameIDPolicy(nidp);

        authn.setIsPassive(false);
        //authn.setProviderName("tremolosecurity.com");

        if (!authMechanism.isEmpty() && !authMechanism.equalsIgnoreCase("none")) {
            AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
            AuthnContextClassRef accr = accrb.buildObject();

            accr.setAuthnContextClassRef(authMechanism);

            //accr.setAuthnContextClassRef("urn:federation:authentication:windows");
            //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

            RequestedAuthnContextBuilder racb = new RequestedAuthnContextBuilder();
            RequestedAuthnContext rac = racb.buildObject();
            rac.getAuthnContextClassRefs().add(accr);
            rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
            authn.setRequestedAuthnContext(rac);
        }

        authn.setForceAuthn(false);

        try {
            // Get the Subject marshaller
            Marshaller marshaller = new AuthnRequestMarshaller();

            // Marshall the Subject
            //Element assertionElement = marshaller.marshall(authn);

            String xml = OpenSAMLUtils.xml2str(authn);
            xml = xml.substring(xml.indexOf("?>") + 2);

            if (logger.isDebugEnabled()) {
                logger.debug("=======AuthnRequest============");
                logger.debug(xml);
                logger.debug("=======AuthnRequest============");
            }

            byte[] bxml = xml.getBytes("UTF-8");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                    new Deflater(Deflater.BEST_COMPRESSION, true));

            compressor.write(bxml);
            compressor.flush();
            compressor.close();

            String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
            StringBuffer redirURL = new StringBuffer();
            StringBuffer query = new StringBuffer();

            idBytes = new byte[20];
            random.nextBytes(idBytes);

            query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                    .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

            if (signAuthnReq) {

                String sigAlg = authParams.get("sigAlg") != null ? authParams.get("sigAlg").getValues().get(0)
                        : "RSA-SHA1";

                String xmlSigAlg = SAML2Auth.xmlDigSigAlgs.get(sigAlg);
                String javaSigAlg = SAML2Auth.javaDigSigAlgs.get(sigAlg);

                //sb.append("SAMLRequest=").append(xml).append("&SigAlg=").append(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "UTF-8"));
                query.append("&SigAlg=").append(URLEncoder.encode(xmlSigAlg, "UTF-8"));

                java.security.Signature signer = java.security.Signature.getInstance(javaSigAlg);

                if (authParams.get("spSigKey") == null) {
                    throw new ServletException("No signature certificate specified");
                }
                String spSigKey = authParams.get("spSigKey").getValues().get(0);

                signer.initSign(cfgMgr.getPrivateKey(spSigKey));
                signer.update(query.toString().getBytes("UTF-8"));
                String base64Sig = new String(Base64.encodeBase64(signer.sign()));
                query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));
            }

            redirURL.append(redirAuthnReqTo).append("?").append(query.toString());

            if (isJump) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Redirecting to Jump Page");
                    logger.debug("SAML2_JUMPPAGE='" + req.getAttribute("TREMOLO_AUTH_REDIR_URI"));
                }

                session.setAttribute("SAML2_JUMPPAGE", redirURL.toString());
                resp.sendRedirect(jumpPage);
            } else {
                resp.sendRedirect(redirURL.toString());
            }

            /*String b64 = new String(
                  org.apache.directory.shared.ldap.util.Base64
                .encode(bxml));
                    
            req.setAttribute("postaction", postAuthnReqTo);
            req.setAttribute("postdata", b64);
            req.getRequestDispatcher("/auth/fed/postauthnreq.jsp").forward(
                  req, resp);*/

        } catch (Exception e) {
            throw new ServletException("Error generating new authn request", e);
        }
    }
}