Example usage for java.util.zip DeflaterOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Writes remaining compressed data to the output stream and closes the underlying stream.

Usage

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  w  ww . j a v a2 s .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   ww  w  .j  a v  a 2 s .c o m*/
    String samlRequestParameter = Shared.encodeBytes(byteArrayOutputStream.toByteArray());
    return samlRequestParameter;
}

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);/*from ww w .j  av a 2s.  co  m*/
    dos.close();

    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 w  w.ja v  a2 s  . c  o m*/
    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 {
    {/*from   w ww. j  a v a 2s  .c om*/
        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);
        }
    }
}

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

private void postResponse(OpenIDConnectTransaction transaction, HttpServletRequest request,
        HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws Exception {
    //first generate a lastmile token
    OpenIDConnectTrust trust = trusts.get(transaction.getClientID());

    ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    DateTime now = new DateTime();
    DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive());
    DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive());

    com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile(
            request.getRequestURI(), notBefore, notAfter, authInfo.getAuthLevel(), authInfo.getAuthMethod());
    lmreq.getAttributes().add(new Attribute("dn", authInfo.getUserDN()));
    Attribute attr = new Attribute("scope");
    attr.getValues().addAll(transaction.getScope());
    lmreq.getAttributes().add(attr);// w  w  w. j  a  v  a  2 s  .  c om
    if (transaction.getNonce() != null) {
        lmreq.getAttributes().add(new Attribute("nonce", transaction.getNonce()));
    }
    SecretKey key = cfgMgr.getSecretKey(trust.getCodeLastmileKeyName());

    String codeToken = lmreq.generateLastMileToken(key);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    compressor.write(org.bouncycastle.util.encoders.Base64.decode(codeToken.getBytes("UTF-8")));
    compressor.flush();
    compressor.close();

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

    StringBuffer b = new StringBuffer();
    b.append(transaction.getRedirectURI()).append("?").append("code=").append(URLEncoder.encode(b64, "UTF-8"))
            .append("&state=").append(URLEncoder.encode(transaction.getState(), "UTF-8"));

    response.sendRedirect(b.toString());

}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAML2AuthenticationHandler.java

private String encodeRequestMessage(RequestAbstractType requestMessage) {

    try {// w w w  .j  a  v  a  2 s .  c om
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        log.error("Error while initializing opensaml library", e);
        return null;
    }
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;
    try {
        authDOM = marshaller.marshall(requestMessage);

        /* Compress the message */
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        deflaterOutputStream.write(rspWrt.toString().getBytes());
        deflaterOutputStream.close();

        /* Encoding the compressed message */
        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
                Base64.DONT_BREAK_LINES);
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (MarshallingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (IOException e) {
        log.error("Error occurred while encoding SAML request", e);
    }
    return null;
}

From source file:PngEncoder.java

/**
 * Write the image data into the pngBytes array.
 * This will write one or more PNG "IDAT" chunks. In order
 * to conserve memory, this method grabs as many rows as will
 * fit into 32K bytes, or the whole image; whichever is less.
 *
 *
 * @return true if no errors; false if error grabbing pixels
 *//*from w ww  .j  a  va 2 s  .  c  o  m*/
protected boolean writeImageData() {
    int rowsLeft = this.height; // number of rows remaining to write
    int startRow = 0; // starting row to process this time through
    int nRows; // how many rows to grab at a time

    byte[] scanLines; // the scan lines to be compressed
    int scanPos; // where we are in the scan lines
    int startPos; // where this line's actual pixels start (used
                  // for filtering)

    byte[] compressedLines; // the resultant compressed lines
    int nCompressed; // how big is the compressed area?

    //int depth;              // color depth ( handle only 8 or 32 )

    PixelGrabber pg;

    this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;

    Deflater scrunch = new Deflater(this.compressionLevel);
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);

    DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch);
    try {
        while (rowsLeft > 0) {
            nRows = Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft);
            nRows = Math.max(nRows, 1);

            int[] pixels = new int[this.width * nRows];

            pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0, this.width);
            try {
                pg.grabPixels();
            } catch (Exception e) {
                System.err.println("interrupted waiting for pixels!");
                return false;
            }
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                System.err.println("image fetch aborted or errored");
                return false;
            }

            /*
             * Create a data chunk. scanLines adds "nRows" for
             * the filter bytes.
             */
            scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows];

            if (this.filter == FILTER_SUB) {
                this.leftBytes = new byte[16];
            }
            if (this.filter == FILTER_UP) {
                this.priorRow = new byte[this.width * this.bytesPerPixel];
            }

            scanPos = 0;
            startPos = 1;
            for (int i = 0; i < this.width * nRows; i++) {
                if (i % this.width == 0) {
                    scanLines[scanPos++] = (byte) this.filter;
                    startPos = scanPos;
                }
                scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
                if (this.encodeAlpha) {
                    scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff);
                }
                if ((i % this.width == this.width - 1) && (this.filter != FILTER_NONE)) {
                    if (this.filter == FILTER_SUB) {
                        filterSub(scanLines, startPos, this.width);
                    }
                    if (this.filter == FILTER_UP) {
                        filterUp(scanLines, startPos, this.width);
                    }
                }
            }

            /*
             * Write these lines to the output area
             */
            compBytes.write(scanLines, 0, scanPos);

            startRow += nRows;
            rowsLeft -= nRows;
        }
        compBytes.close();

        /*
         * Write the compressed bytes
         */
        compressedLines = outBytes.toByteArray();
        nCompressed = compressedLines.length;

        this.crc.reset();
        this.bytePos = writeInt4(nCompressed, this.bytePos);
        this.bytePos = writeBytes(IDAT, this.bytePos);
        this.crc.update(IDAT);
        this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos);
        this.crc.update(compressedLines, 0, nCompressed);

        this.crcValue = this.crc.getValue();
        this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
        scrunch.finish();
        scrunch.end();
        return true;
    } catch (IOException e) {
        System.err.println(e.toString());
        return false;
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcTransactionalStorage.java

protected String storeMessageInDatabase(Connection conn, String messageId, String correlationId,
        Timestamp receivedDateTime, String comments, String label, Serializable message)
        throws IOException, SQLException, JdbcException, SenderException {
    PreparedStatement stmt = null;
    try {//  ww w  . ja v  a2  s  .co  m
        IDbmsSupport dbmsSupport = getDbmsSupport();
        if (log.isDebugEnabled())
            log.debug("preparing insert statement [" + insertQuery + "]");
        if (!dbmsSupport.mustInsertEmptyBlobBeforeData()) {
            stmt = conn.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
        } else {
            stmt = conn.prepareStatement(insertQuery);
        }
        stmt.clearParameters();
        int parPos = 0;

        if (StringUtils.isNotEmpty(getTypeField())) {
            stmt.setString(++parPos, type);
        }
        if (StringUtils.isNotEmpty(getSlotId())) {
            stmt.setString(++parPos, getSlotId());
        }
        if (StringUtils.isNotEmpty(getHostField())) {
            stmt.setString(++parPos, host);
        }
        if (StringUtils.isNotEmpty(getLabelField())) {
            stmt.setString(++parPos, label);
        }
        stmt.setString(++parPos, messageId);
        stmt.setString(++parPos, correlationId);
        stmt.setTimestamp(++parPos, receivedDateTime);
        stmt.setString(++parPos, comments);
        if (type.equalsIgnoreCase(TYPE_MESSAGELOG_PIPE) || type.equalsIgnoreCase(TYPE_MESSAGELOG_RECEIVER)) {
            if (getRetention() < 0) {
                stmt.setTimestamp(++parPos, null);
            } else {
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DAY_OF_MONTH, getRetention());
                stmt.setTimestamp(++parPos, new Timestamp(cal.getTime().getTime()));
            }
        } else {
            stmt.setTimestamp(++parPos, null);
        }

        if (!isStoreFullMessage()) {
            if (isOnlyStoreWhenMessageIdUnique()) {
                stmt.setString(++parPos, messageId);
                stmt.setString(++parPos, slotId);
            }
            stmt.execute();
            return null;
        }
        if (!dbmsSupport.mustInsertEmptyBlobBeforeData()) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            if (isBlobsCompressed()) {
                DeflaterOutputStream dos = new DeflaterOutputStream(out);
                ObjectOutputStream oos = new ObjectOutputStream(dos);
                oos.writeObject(message);
                dos.close();
            } else {
                ObjectOutputStream oos = new ObjectOutputStream(out);
                oos.writeObject(message);
            }

            stmt.setBytes(++parPos, out.toByteArray());
            if (isOnlyStoreWhenMessageIdUnique()) {
                stmt.setString(++parPos, messageId);
                stmt.setString(++parPos, slotId);
            }
            stmt.execute();
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                return rs.getString(1);
            } else {
                return null;
            }
        }
        if (isOnlyStoreWhenMessageIdUnique()) {
            stmt.setString(++parPos, messageId);
            stmt.setString(++parPos, slotId);
        }
        stmt.execute();
        int updateCount = stmt.getUpdateCount();
        if (log.isDebugEnabled())
            log.debug("update count for insert statement: " + updateCount);
        if (updateCount > 0) {
            if (log.isDebugEnabled())
                log.debug("preparing select statement [" + selectKeyQuery + "]");
            stmt = conn.prepareStatement(selectKeyQuery);
            ResultSet rs = null;
            try {
                // retrieve the key
                rs = stmt.executeQuery();
                if (!rs.next()) {
                    throw new SenderException("could not retrieve key of stored message");
                }
                String newKey = rs.getString(1);
                rs.close();

                // and update the blob
                if (log.isDebugEnabled())
                    log.debug("preparing update statement [" + updateBlobQuery + "]");
                stmt = conn.prepareStatement(updateBlobQuery);
                stmt.clearParameters();
                stmt.setString(1, newKey);

                rs = stmt.executeQuery();
                if (!rs.next()) {
                    throw new SenderException("could not retrieve row for stored message [" + messageId + "]");
                }
                //                  String newKey = rs.getString(1);
                //                  BLOB blob = (BLOB)rs.getBlob(2);
                Object blobHandle = dbmsSupport.getBlobUpdateHandle(rs, 1);
                OutputStream out = dbmsSupport.getBlobOutputStream(rs, 1, blobHandle);
                //               OutputStream out = JdbcUtil.getBlobUpdateOutputStream(rs,1);
                if (isBlobsCompressed()) {
                    DeflaterOutputStream dos = new DeflaterOutputStream(out);
                    ObjectOutputStream oos = new ObjectOutputStream(dos);
                    oos.writeObject(message);
                    oos.close();
                    dos.close();
                } else {
                    ObjectOutputStream oos = new ObjectOutputStream(out);
                    oos.writeObject(message);
                    oos.close();
                }
                out.close();
                dbmsSupport.updateBlob(rs, 1, blobHandle);
                return newKey;

            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        } else {
            if (isOnlyStoreWhenMessageIdUnique()) {
                return "already there";
            } else {
                throw new SenderException(
                        "update count for update statement not greater than 0 [" + updateCount + "]");
            }
        }

    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static void putStringAsBlob(IDbmsSupport dbmsSupport, final ResultSet rs, int columnIndex,
        String content, String charset, boolean compressBlob) throws IOException, JdbcException, SQLException {
    if (content != null) {
        Object blobHandle = dbmsSupport.getBlobUpdateHandle(rs, columnIndex);
        OutputStream out = dbmsSupport.getBlobOutputStream(rs, columnIndex, blobHandle);
        if (charset == null) {
            charset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
        }/*  w ww .j ava2 s  .c o  m*/
        if (compressBlob) {
            DeflaterOutputStream dos = new DeflaterOutputStream(out);
            dos.write(content.getBytes(charset));
            dos.close();
        } else {
            out.write(content.getBytes(charset));
        }
        out.close();
        dbmsSupport.updateBlob(rs, columnIndex, blobHandle);
    } else {
        log.warn("content to store in blob was null");
    }
}