Java tutorial
/* * Copyright 2015 Kaiserpfalz EDV-Service Roland Lichti * * 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. */ package de.kaiserpfalzEdv.commons.encoding; import de.kaiserpfalzEdv.commons.exceptions.EncodingException; import org.apache.commons.lang3.SerializationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.Base64; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * This small class encodes/decodes serializable Objects into/from Strings * using BASE64 encoding. * * @author klenkes * @since 1.0.0 */ public final class EncodingHelper { /** Default logger. */ private static final Logger LOG = LoggerFactory.getLogger(EncodingHelper.class); /** * Only an utility class. No need to instantiate. */ private EncodingHelper() { } /** * Encodes the serializable object into a BASE64 encoded string. * * @param obj The object to be serialized * @return The BASE64 encoded string containing the object. * @throws EncodingException If an {@link IOException} has been thrown. */ public static String encode(final Serializable obj) { LOG.trace("Trying to encode: {}", obj); checkArgument(obj != null, "Can't encode a null!"); String out = Base64.getEncoder().encodeToString(SerializationUtils.serialize(obj)); LOG.debug("Encoded serializable object. Now returning string containing BASE64 encoded object ..."); return out; } /** * Decodes the Object stream into an object. * * @param objectString the BASE64 encoded string containing a serialized object. * @return the object itself. * @throws EncodingException If an {@link IOException} or * {@link ClassNotFoundException} was thrown. */ public static Object decode(final String objectString) { LOG.trace("Trying to decode string: {}", objectString); checkArgument(isNotBlank(objectString), "Can't decode NULL or empty String!"); Object out = SerializationUtils.deserialize(Base64.getDecoder().decode(objectString)); LOG.debug("Decoded BASE64 encoded object from string. Now returning object."); return out; } }