Java XML Data Type Converter serializeURLSafe(String string)

Here you can find the source of serializeURLSafe(String string)

Description

Serialize the given string to the short possible unique URL-safe representation.

License

Apache License

Parameter

Parameter Description
string The string to be serialized.

Return

The serialized URL-safe string, or null when the given string is itself null.

Declaration

public static String serializeURLSafe(String string) 

Method Source Code

//package com.java2s;
/*//w  w w  .j  av  a2  s . c  o m
 * Copyright 2013 OmniFaces.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;

import javax.xml.bind.DatatypeConverter;

public class Main {
    private static final int DEFAULT_STREAM_BUFFER_SIZE = 10240;

    /**
     * Serialize the given string to the short possible unique URL-safe representation. The current implementation will
     * decode the given string with UTF-8 and then compress it with ZLIB using "best compression" algorithm and then
     * Base64-encode the resulting bytes whereafter the Base64 characters <code>/</code>, <code>+</code> and
     * <code>=</code> are been replaced by respectively <code>~</code>, <code>-</code> and <code>_</code> to make it
     * URL-safe (so that no platform-sensitive URL-encoding needs to be done when used in URLs).
     * @param string The string to be serialized.
     * @return The serialized URL-safe string, or <code>null</code> when the given string is itself <code>null</code>.
     * @since 1.2
     */
    public static String serializeURLSafe(String string) {
        if (string == null) {
            return null;
        }

        try {
            InputStream raw = new ByteArrayInputStream(
                    string.getBytes("UTF-8"));
            ByteArrayOutputStream deflated = new ByteArrayOutputStream();
            stream(raw, new DeflaterOutputStream(deflated, new Deflater(
                    Deflater.BEST_COMPRESSION)));
            String base64 = DatatypeConverter.printBase64Binary(deflated
                    .toByteArray());
            return base64.replace('/', '~').replace('+', '-')
                    .replace('=', '_');
        } catch (IOException e) {
            // This will occur when ZLIB and/or UTF-8 are not supported, but this is not to be expected these days.
            throw new RuntimeException(e);
        }
    }

    /**
     * Stream the given input to the given output by NIO {@link ByteBuffer}. Both the input and output streams will
     * implicitly be closed after streaming, regardless of whether an exception is been thrown or not.
     * @param input The input stream.
     * @param output The output stream.
     * @return The length of the written bytes.
     * @throws IOException When an I/O error occurs.
     */
    public static long stream(InputStream input, OutputStream output)
            throws IOException {
        ReadableByteChannel inputChannel = null;
        WritableByteChannel outputChannel = null;

        try {
            inputChannel = Channels.newChannel(input);
            outputChannel = Channels.newChannel(output);
            ByteBuffer buffer = ByteBuffer
                    .allocateDirect(DEFAULT_STREAM_BUFFER_SIZE);
            long size = 0;

            while (inputChannel.read(buffer) != -1) {
                buffer.flip();
                size += outputChannel.write(buffer);
                buffer.clear();
            }

            return size;
        } finally {
            close(outputChannel);
            close(inputChannel);
        }
    }

    /**
     * Check if the given resource is not <code>null</code> and then close it, whereby any caught {@link IOException}
     * is been returned instead of thrown, so that the caller can if necessary handle (log) or just ignore it without
     * the need to put another try-catch.
     * @param resource The closeable resource to be closed.
     * @return The caught {@link IOException}, or <code>null</code> if none is been thrown.
     */
    public static IOException close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                return e;
            }
        }

        return null;
    }
}

Related

  1. printZimmeranzahl(BigDecimal value)
  2. readKey(Reader reader, String algorithm)
  3. sendJson(URL url, String method, String data, String user, String password)
  4. serializeLogic(Serializable logic)
  5. serializeToString(Object object)
  6. stringToCalendar(String value)
  7. stringToData(String data)
  8. toBinaryKeyId(String keyId)
  9. toPlaintext(String encryptedText, String password)