Example usage for java.util.zip GZIPOutputStream finish

List of usage examples for java.util.zip GZIPOutputStream finish

Introduction

In this page you can find the example usage for java.util.zip GZIPOutputStream finish.

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing compressed data to the output stream without closing the underlying stream.

Usage

From source file:org.mule.util.Base64.java

/**
 * Serializes an object and returns the Base64-encoded version of that serialized
 * object. If the object cannot be serialized or there is another error, the
 * method will return <tt>null</tt>.
 * <p>//from  www.j  a v a 2  s  .  c  o  m
 * Valid options:
 * 
 * <pre>
 *              GZIP: gzip-compresses object before encoding it.
 *              DONT_BREAK_LINES: don't break lines at 76 characters
 *                &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
 * </pre>
 * 
 * <p>
 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
 * <p>
 * Example:
 * <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
 * 
 * @param serializableObject The object to encode
 * @param options Specified options
 * @return The Base64-encoded object
 * @see Base64#GZIP
 * @see Base64#DONT_BREAK_LINES
 * @since 2.0
 */
public static String encodeObject(Serializable serializableObject, int options) throws IOException {
    // Streams
    ByteArrayOutputStream baos = null;
    OutputStream b64os = null;
    ObjectOutputStream oos = null;
    GZIPOutputStream gzos = null;

    // Isolate options
    int gzip = (options & GZIP);
    int dontBreakLines = (options & DONT_BREAK_LINES);

    try {
        // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
        baos = new ByteArrayOutputStream(4096);
        b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);

        // GZip?
        if (gzip == GZIP) {
            gzos = new GZIPOutputStream(b64os);
            oos = new ObjectOutputStream(gzos);
        } // end if: gzip
        else {
            oos = new ObjectOutputStream(b64os);
        }

        oos.writeObject(serializableObject);

        if (gzos != null) {
            gzos.finish();
            gzos.close();
        }

        oos.close();
    } // end try
    catch (IOException e) {
        return null;
    } // end catch
    finally {
        IOUtils.closeQuietly(oos);
        IOUtils.closeQuietly(gzos);
        IOUtils.closeQuietly(b64os);
        IOUtils.closeQuietly(baos);
    } // end finally

    // Return value according to relevant encoding.
    try {
        return new String(baos.toByteArray(), PREFERRED_ENCODING);
    } // end try
    catch (UnsupportedEncodingException uue) {
        return new String(baos.toByteArray());
    } // end catch

}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Compress the content according to the RFC1952 GZip algorithm. Since 
 * compression produces binary output, to fit
 * into an XML document the output has to be base64 encoded, which results 
 * in a 33% increase in size. So the compressed form is only "accepted" if
 * the attempt results in an overall reduction in size.
 * // ww w .  j ava2  s  .c  om
 * @param content
 * @throws Exception 
 */
private void compressIfViable(byte[] content) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzOut = new GZIPOutputStream(out, UNCOMPRESSBUFFERSIZE);
    gzOut.write(content, 0, content.length);
    gzOut.finish();
    byte[] comp = out.toByteArray();
    double ratio = (double) content.length / (double) comp.length;
    if (ratio > 1.34) {
        Base64 b64 = new Base64();
        comp = b64.encode(comp);
        payloadBody = new String(comp);
        compressed = true;
    } else {
        compressed = false;
        if (payloadBody != null) {
            return;
        }
        Base64 b64 = new Base64();
        comp = b64.encode(content);
        payloadBody = new String(comp);
        base64 = true;
    }
}

From source file:org.intermine.web.search.ClassAttributes.java

private static void writeObjectToDB(ObjectStore os, String key, Object object)
        throws IOException, SQLException {
    LOG.info("Saving stream to database...");
    Database db = ((ObjectStoreInterMineImpl) os).getDatabase();
    LargeObjectOutputStream streamOut = MetadataManager.storeLargeBinary(db, key);

    GZIPOutputStream gzipStream = new GZIPOutputStream(new BufferedOutputStream(streamOut));
    ObjectOutputStream objectStream = new ObjectOutputStream(gzipStream);

    LOG.info("GZipping and serializing object...");
    objectStream.writeObject(object);//from w w  w .  j  a  v a 2s .  c om

    objectStream.flush();
    gzipStream.finish();
    gzipStream.flush();

    streamOut.close();
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();//  ww  w .  java  2s  .  com
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java

/**
 * Save as zip file the given XML Document using a given file name 
 * @param fileName the name of the generated zip file
 * @param doc the XML document to store in the zip file 
 *//* w w w  . j a  va  2 s.c om*/
protected void saveZipFile(String fileName, Document doc) {
    String outfileName = fileName + zipFileExtension;
    if (outputDir != null && !outputDir.isEmpty())
        outfileName = outputDir + outfileName;

    try {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Source xmlSource = new DOMSource(doc);

        Result outputTarget = new StreamResult(new OutputStreamWriter(outputStream, DEFAULT_ENCODING));
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute(xmlAttributeIdentNumber, new Integer(4));

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
        transformer.setOutputProperty("{http://xml. customer .org/xslt}indent-amount", "4");
        transformer.transform(xmlSource, outputTarget);

        InputStream in = new ByteArrayInputStream(outputStream.toString(DEFAULT_ENCODING).getBytes());

        byte[] buf = new byte[1024];
        //create the zip file
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outfileName));

        //Transfer bytes from the inputstream to the ZIP
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        //Complete the entry
        in.close();

        //complete the zip file
        out.finish();
        out.close();
    } catch (FileNotFoundException e) {
        logger.debug("FileNotFoundException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    } catch (IOException e) {
        logger.debug("IOException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    } catch (TransformerConfigurationException e) {
        logger.debug("TransformerConfigurationException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    } catch (TransformerException e) {
        logger.debug("TransformerException ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    } catch (TransformerFactoryConfigurationError e) {
        logger.debug("TransformerFactoryConfigurationError ", e);
        System.err.println(e.getMessage());
        System.exit(3);
    }
}

From source file:org.dspace.EDMExport.controller.homeController.java

/**
 * Controller para la url /viewXml.htm con mtodo GET y sin parmetros.
 * Se recogen los datos del formulario con la configuracin de elementos EDM para mostrar el xml de los tems seleccionados.
 * Si hay errores se redirige a la lista de tems seleccionados, si no se muestra el xml con los datos en EDM.
 * Si el xml a mostrar excede los 2MB y no se comprime con el servlet se comprime el contenido y se enva tambin.
 * /*from   w w w  .  j  ava  2s.c  o  m*/
 * @param edmExportBOFormEDMData objeto que recoge los datos pasados del formulario {@link EDMExportBOFormEDMData}
 * @param result objeto con el que se une la peticin y se valida {@link BindingResult}
 * @param model objeto de Spring Model con la peticin {@link Model}
 * @param request objeto de la peticin http para recoger los datos del objeto flash (como la sesin pero dura una peticin)
 * @return cadena con la vista a renderizar y mostrar
 */
@RequestMapping(value = "/viewXml.htm", method = RequestMethod.GET)
public String getViewXML(@ModelAttribute(value = "FormEDMData") EDMExportBOFormEDMData edmExportBOFormEDMData,
        BindingResult result, Model model, HttpServletRequest request) {
    logger.debug("homeController.getViewXML");
    Map<String, ?> map = RequestContextUtils.getInputFlashMap(request);
    if (map == null) {
        logger.debug("No FlashMap");
        return "redirect:selectedItems.htm";
    }
    if (result.hasErrors()) {
        logErrorValid(result);
        return "redirect:selectedItems.htm";
    } else {
        edmExportServiceXML.setEdmExportServiceListItems(edmExportServiceListItems);
        String edmXML = edmExportServiceXML.showEDMXML(edmExportBOFormEDMData, servletContext.getRealPath(""));
        logger.debug(edmXML);
        String edmXMLEncoded = "";
        String encoding = request.getHeader("Content-Encoding");
        //while (edmXML.length() <= 1500000) edmXML += edmXML;
        if (edmXML.length() > 1500000 && (encoding == null || (encoding != null && encoding.isEmpty()))) {
            ByteArrayOutputStream output = null;
            GZIPOutputStream gzOut = null;
            try {
                output = new ByteArrayOutputStream();
                gzOut = new GZIPOutputStream(output);
                gzOut.write(edmXML.getBytes("UTF-8"));
                gzOut.finish();
                byte[] encoded = Base64.encodeBase64(output.toByteArray());
                edmXMLEncoded = new String(encoded, "UTF-8");
            } catch (IOException e) {
                logger.debug("IOException", e);
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (gzOut != null)
                        gzOut.close();
                } catch (IOException e) {
                    logger.debug("IOException", e);
                }

            }
        }
        logger.debug(edmXMLEncoded);
        model.addAttribute("formatXML", edmExportBOFormEDMData.getXmlFormat());
        model.addAttribute("edmXML", edmXML);
        model.addAttribute("edmXMLEncoded", edmXMLEncoded);
        model.addAttribute("listElementsFilled", edmExportServiceXML.getListElementsFilled());
        return returnView("viewXml", model);
    }
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private void sendResponse(Request baseRequest, HttpServletResponse servletResponse,
        DispatchResult dispatchResult) throws Exception {
    ContentType contentType = ContentType
            .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult));
    if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) {
        /*/*  w  w w  .  j  a va 2s  . c om*/
         * If text mode is used and a specific charset isn't already defined, use the one from
         * the connector properties. We can't use ContentType.withCharset here because it
         * doesn't preserve other parameters, like boundary definitions
         */
        contentType = ContentType.parse(contentType.toString() + "; charset="
                + CharsetUtils.getEncoding(connectorProperties.getCharset()));
    }
    servletResponse.setContentType(contentType.toString());

    // set the response headers
    for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult));
        }
    }

    // set the status code
    int statusCode = NumberUtils
            .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1);

    /*
     * set the response body and status code (if we choose a response from the drop-down)
     */
    if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
        dispatchResult.setAttemptedResponse(true);

        Response selectedResponse = dispatchResult.getSelectedResponse();
        Status newMessageStatus = selectedResponse.getStatus();

        /*
         * If the status code is custom, use the entered/replaced string If is is not a
         * variable, use the status of the destination's response (success = 200, failure = 500)
         * Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) {
            servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }

        String message = selectedResponse.getMessage();

        if (message != null) {
            OutputStream responseOutputStream = servletResponse.getOutputStream();
            byte[] responseBytes;
            if (connectorProperties.isResponseDataTypeBinary()) {
                responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII"));
            } else {
                responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset()));
            }

            // If the client accepts GZIP compression, compress the content
            boolean gzipResponse = false;
            for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) {
                String acceptEncoding = en.nextElement();

                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                    gzipResponse = true;
                    break;
                }
            }

            if (gzipResponse) {
                servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip");
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream);
                gzipOutputStream.write(responseBytes);
                gzipOutputStream.finish();
            } else {
                responseOutputStream.write(responseBytes);
            }

            // TODO include full HTTP payload in sentResponse
        }
    } else {
        /*
         * If the status code is custom, use the entered/replaced string Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }
    }
}

From source file:it.drwolf.ridire.session.async.Mapper.java

private void createArchivedResource(File f, CrawledResource cr, EntityManager entityManager) {
    // System.out.println(System.getProperty("java.io.tmpdir"));
    String posEnabled = this.em.find(Parameter.class, Parameter.POS_ENABLED.getKey()).getValue();
    File resourceDir;//from w  w w.j  a va 2 s  .  c  om
    int status = Parameter.FINISHED;
    try {
        resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", ""))
                + JobMapperMonitor.RESOURCESDIR);
        if (!resourceDir.exists()) {
            FileUtils.forceMkdir(resourceDir);
        }
        ArchiveReader reader = ArchiveReaderFactory.get(f);
        ARCRecord record = (ARCRecord) reader.get(cr.getOffset());
        record.skipHttpHeader();
        byte[] buf = new byte[Mapper.BUFLENGTH];
        int count = 0;
        String resourceFile = cr.getDigest() + ".gz";
        GZIPOutputStream baos = new GZIPOutputStream(new FileOutputStream(new File(resourceDir, resourceFile)));
        while ((count = record.read(buf)) != -1) {
            baos.write(buf, 0, count);
        }
        baos.finish();
        baos.close();
        reader.close();
        // long t1 = System.currentTimeMillis();
        StringWithEncoding cleanText = this.createPlainTextResource(f, cr, entityManager);
        this.removeGZippedResource(resourceDir, resourceFile);
        // long t2 = System.currentTimeMillis();
        // System.out.println("Creazione plain text: " + (t2 - t1));
        String plainTextFileName = cr.getDigest() + ".txt";
        if (cleanText != null && cleanText.getString() != null && cleanText.getString().trim().length() > 0
                && cleanText.getCleaner() != null && (cleanText.getCleaner().equals(Mapper.ALCHEMY)
                        || cleanText.getCleaner().equals(Mapper.READABILITY))) {
            cr.setCleaner(cleanText.getCleaner());
            File plainTextFile = new File(resourceDir, plainTextFileName);
            FileUtils.writeStringToFile(plainTextFile, cleanText.getString(), cleanText.getEncoding());
            cr.setExtractedTextHash(MD5DigestCreator.getMD5Digest(plainTextFile));
            // language detection
            // t1 = System.currentTimeMillis();
            String language = this.detectLanguage(cleanText.getString());
            // t2 = System.currentTimeMillis();
            // System.out.println("Language detection: " + (t2 - t1));
            cr.setLanguage(language);
            if (language != null && language.equalsIgnoreCase(Mapper.ITALIAN) && posEnabled != null
                    && posEnabled.equalsIgnoreCase("true")) {
                // PoS tag if it's an italian text
                // t1 = System.currentTimeMillis();
                String posTagResourceFileName = this.createPoSTagResource(plainTextFile, entityManager,
                        cleanText.getEncoding());
                // t2 = System.currentTimeMillis();
                // System.out.println("PoS tagging: " + (t2 - t1));
                if (posTagResourceFileName != null) {
                    Integer wordsNumber = Mapper.countWordsFromPoSTagResource(posTagResourceFileName);
                    cr.setWordsNumber(wordsNumber);
                }
            }
        }
    } catch (Exception e) {
        status = Parameter.PROCESSING_ERROR;
        e.printStackTrace();
    }
    cr.setProcessed(status);
}

From source file:savant.file.Project.java

public static void saveToFile(File f) throws IOException, SavantEmptySessionException, XMLStreamException {
    GZIPOutputStream output = new GZIPOutputStream(new FileOutputStream(f));
    writer = XMLOutputFactory.newInstance().createXMLStreamWriter(output, "UTF-8");
    writer.writeStartDocument();//  w  ww. j a va2s.com
    writeStartElement(XMLElement.savant, "");
    writeAttribute(XMLAttribute.version, Integer.toString(FILE_VERSION));

    LocationController locationController = LocationController.getInstance();
    Range r = locationController.getRange();
    writeAttribute(XMLAttribute.range,
            String.format("%s:%d-%d", locationController.getReferenceName(), r.getFrom(), r.getTo()));

    writeStartElement(XMLElement.genome, "  ");
    Genome g = GenomeController.getInstance().getGenome();
    writeAttribute(XMLAttribute.name, g.getName());
    URI cytobandURI = g.getCytobandURI();
    if (cytobandURI != null) {
        writeAttribute(XMLAttribute.cytoband, cytobandURI.toString());
    }

    if (g.isSequenceSet()) {
        writeAttribute(XMLAttribute.uri, NetworkUtils.getNeatPathFromURI(g.getDataSource().getURI()));
    } else {
        for (String ref : g.getReferenceNames()) {
            writeEmptyElement(XMLElement.reference, "    ");
            writeAttribute(XMLAttribute.name, ref);
            writeAttribute(XMLAttribute.length, Integer.toString(g.getLength(ref)));
        }
    }
    writer.writeCharacters("\r\n  ");
    writer.writeEndElement();

    for (FrameAdapter fr : FrameController.getInstance().getOrderedFrames()) {
        // Frame may have zero-length track array  if user saves while the "Creating track\u2026 progress-bar is up.
        TrackAdapter[] tracks = fr.getTracks();
        if (tracks.length > 0) {
            TrackAdapter t0 = tracks[0];
            URI uri = t0.getDataSource().getURI();
            if (uri != null) {
                writeEmptyElement(XMLElement.track, "  ");
                writeAttribute(XMLAttribute.uri, NetworkUtils.getNeatPathFromURI(uri));
                writeAttribute(XMLAttribute.mode, t0.getDrawingMode().toString());
            }
        }
    }

    for (Bookmark b : BookmarkController.getInstance().getBookmarks()) {
        writeStartElement(XMLElement.bookmark, "  ");
        writeAttribute(XMLAttribute.range, b.getLocationText());
        writer.writeCharacters(b.getAnnotation());
        writer.writeEndElement();
    }

    for (String p : VariationController.getInstance().getControls()) {
        writeStartElement(XMLElement.control, "   ");
        writer.writeCharacters(p);
        writer.writeEndElement();
    }
    writer.writeCharacters("\r\n");
    writer.writeEndElement();
    writer.writeEndDocument();
    output.finish();
    writer.close();
}

From source file:com.meetup.memcached.MemcachedClient.java

/** 
 * Stores data to cache./*ww  w.  j a  v  a  2s  .co  m*/
 *
 * If data does not already exist for this key on the server, or if the key is being<br/>
 * deleted, the specified value will not be stored.<br/>
 * The server will automatically delete the value when the expiration time has been reached.<br/>
 * <br/>
 * If compression is enabled, and the data is longer than the compression threshold<br/>
 * the data will be stored in compressed form.<br/>
 * <br/>
 * As of the current release, all objects stored will use java serialization.
 * 
 * @param cmdname action to take (set, add, replace)
 * @param key key to store cache under
 * @param value object to cache
 * @param expiry expiration
 * @param hashCode if not null, then the int hashcode to use
 * @param asString store this object as a string?
 * @return true/false indicating success
 */
private boolean set(String cmdname, String key, Object value, Date expiry, Integer hashCode, boolean asString) {

    if (cmdname == null || cmdname.trim().equals("") || key == null) {
        log.error("key is null or cmd is null/empty for set()");
        return false;
    }

    try {
        key = sanitizeKey(key);
    } catch (UnsupportedEncodingException e) {

        // if we have an errorHandler, use its hook
        if (errorHandler != null)
            errorHandler.handleErrorOnSet(this, e, key);

        log.error("failed to sanitize your key!", e);
        return false;
    }

    if (value == null) {
        log.warn("trying to store a null value to cache: " + key);
        return false;
    }

    // get SockIO obj
    SockIOPool.SockIO sock = pool.getSock(key, hashCode);

    if (sock == null) {
        if (errorHandler != null)
            errorHandler.handleErrorOnSet(this, new IOException("no socket to server available"), key);
        return false;
    }

    if (expiry == null)
        expiry = new Date(0);

    // store flags
    int flags = 0;

    // byte array to hold data
    byte[] val;

    if (NativeHandler.isHandled(value)) {

        if (asString) {
            // useful for sharing data between java and non-java
            // and also for storing ints for the increment method
            try {
                if (log.isInfoEnabled())
                    log.info("++++ storing data as a string for key: " + key + " for class: "
                            + value.getClass().getName());
                val = value.toString().getBytes(defaultEncoding);
            } catch (UnsupportedEncodingException ue) {

                // if we have an errorHandler, use its hook
                if (errorHandler != null)
                    errorHandler.handleErrorOnSet(this, ue, key);

                log.error("invalid encoding type used: " + defaultEncoding, ue);
                sock.close();
                sock = null;
                return false;
            }
        } else {
            try {
                if (log.isInfoEnabled())
                    log.info("Storing with native handler...");
                flags |= NativeHandler.getMarkerFlag(value);
                val = NativeHandler.encode(value);
            } catch (Exception e) {

                // if we have an errorHandler, use its hook
                if (errorHandler != null)
                    errorHandler.handleErrorOnSet(this, e, key);

                log.error("Failed to native handle obj", e);

                sock.close();
                sock = null;
                return false;
            }
        }
    } else {
        // always serialize for non-primitive types
        try {
            if (log.isInfoEnabled())
                log.info("++++ serializing for key: " + key + " for class: " + value.getClass().getName());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            (new ObjectOutputStream(bos)).writeObject(value);
            val = bos.toByteArray();
            flags |= F_SERIALIZED;
        } catch (IOException e) {

            // if we have an errorHandler, use its hook
            if (errorHandler != null)
                errorHandler.handleErrorOnSet(this, e, key);

            // if we fail to serialize, then
            // we bail
            log.error("failed to serialize obj", e);
            log.error(value.toString());

            // return socket to pool and bail
            sock.close();
            sock = null;
            return false;
        }
    }

    // now try to compress if we want to
    // and if the length is over the threshold 
    if (compressEnable && val.length > compressThreshold) {

        try {
            if (log.isInfoEnabled()) {
                log.info("++++ trying to compress data");
                log.info("++++ size prior to compression: " + val.length);
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);
            GZIPOutputStream gos = new GZIPOutputStream(bos);
            gos.write(val, 0, val.length);
            gos.finish();

            // store it and set compression flag
            val = bos.toByteArray();
            flags |= F_COMPRESSED;

            if (log.isInfoEnabled())
                log.info("++++ compression succeeded, size after: " + val.length);
        } catch (IOException e) {

            // if we have an errorHandler, use its hook
            if (errorHandler != null)
                errorHandler.handleErrorOnSet(this, e, key);

            log.error("IOException while compressing stream: " + e.getMessage());
            log.error("storing data uncompressed");
        }
    }

    // now write the data to the cache server
    try {
        String cmd = String.format("%s %s %d %d %d\r\n", cmdname, key, flags, (expiry.getTime() / 1000),
                val.length);
        sock.write(cmd.getBytes());
        sock.write(val);
        sock.write("\r\n".getBytes());
        sock.flush();

        // get result code
        String line = sock.readLine();
        if (log.isInfoEnabled())
            log.info("++++ memcache cmd (result code): " + cmd + " (" + line + ")");

        if (STORED.equals(line)) {
            if (log.isInfoEnabled())
                log.info("++++ data successfully stored for key: " + key);
            sock.close();
            sock = null;
            return true;
        } else if (NOTSTORED.equals(line)) {
            if (log.isInfoEnabled())
                log.info("++++ data not stored in cache for key: " + key);
        } else {
            log.error("++++ error storing data in cache for key: " + key + " -- length: " + val.length);
            log.error("++++ server response: " + line);
        }
    } catch (IOException e) {

        // if we have an errorHandler, use its hook
        if (errorHandler != null)
            errorHandler.handleErrorOnSet(this, e, key);

        // exception thrown
        log.error("++++ exception thrown while writing bytes to server on set");
        log.error(e.getMessage(), e);

        try {
            sock.trueClose();
        } catch (IOException ioe) {
            log.error("++++ failed to close socket : " + sock.toString());
        }

        sock = null;
    }

    if (sock != null) {
        sock.close();
        sock = null;
    }

    return false;
}