net.sf.ginp.util.GinpUtil.java Source code

Java tutorial

Introduction

Here is the source code for net.sf.ginp.util.GinpUtil.java

Source

/*
 *  ginp - Java Web Application for Viewing Photo Collections
 *  Copyright (C) 2004  Douglas John Culnane <doug@culnane.net>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA  02110-1301  USA
 */
package net.sf.ginp.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import net.sf.ginp.GinpPictureServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.dom4j.Document;

import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.text.MessageFormat;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

/**
 * Internationalization stuff
 * These are for server side messages that won't go out to the client
 * so we can use whatever the JVM's locale is.
 *
 * @author Justin Sher
 */
public final class GinpUtil {
    /**
     * apache Commons Logger specific to this class.
     */
    private static Log log = LogFactory.getLog(GinpPictureServlet.class);

    /**
     * <code>CREATE_CONFIG_ERROR</code> - if there's an error creating
     * the config.
     */
    public static final String CREATE_CONFIG_ERROR = "createConfigError";
    private static ResourceBundle bundle = ResourceBundle.getBundle("net.sf.ginp.Ginp");

    /**
     *   Utility class with only static methods so define
     *   a private constructor.
     */
    private GinpUtil() {
    };

    /**
     * Get an Internationalized Message encoded with a Message Format.
     * @param key the message key
     * @param args keys for messageformat
     * @return the i18n message
     */
    public static String message(final String key, final Object[] args) {
        String format = bundle.getString(key);
        MessageFormat msg = new MessageFormat(format);
        String formatted = msg.format(args);

        return formatted;
    }

    /**
     * Get a normal internationalied message.
     * @param key the key
     * @return the i18n message
     */
    public static String message(final String key) {
        return bundle.getString(key);
    }

    /**
     * Reads the input stream into memory.
     * @param stream the stream
     * @return a reader for the string represeting the data read
     * from the input stream
     * @throws IOException
     */
    public static String readBufferIntoMemory(final InputStream stream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferIn = new byte[4096];
        int readIn = 0;

        while ((readIn = stream.read(bufferIn)) >= 0) {
            baos.write(bufferIn, 0, readIn);
        }

        return baos.toString();
    }

    /**
     *
     * @param stylePath the classpath resource name of the transforming xsl doc
     * @param visitDoc the doc to transform
     * @return the transformed document
     * @throws TransformerException
     */
    public static Document transform(final String stylePath, final Document visitDoc) throws TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory
                .newTransformer(new StreamSource(GinpUtil.class.getResourceAsStream(stylePath)));
        DocumentResult result = new DocumentResult();
        transformer.transform(new DocumentSource(visitDoc), result);

        return result.getDocument();
    }

    /**
     * @param adminPassword a string
     * @return whether a string is empty
     */
    public static boolean empty(final String adminPassword) {
        return (adminPassword == null) || (adminPassword.length() == 0);
    }

    /**
     * Parse an integer from a string and handle exceptions gracefully.
     * @param req the servlet request to get the parameter from
     * @param param the name of the parameter
     * @param defaultVal the default value if parsing fails
     * @return the parsed value or the default if parsing failed
     */
    public static int parseInteger(final HttpServletRequest req, final String param, final int defaultVal) {
        if (req.getParameter(param) == null) {
            return defaultVal;
        }

        try {
            return new Integer(req.getParameter(param)).intValue();
        } catch (Exception ex) {
            log.error("An error occurred trying to parse the http parameter " + param
                    + " to an int in the requested url " + req.getRequestURL());
        }

        return defaultVal;
    }

    public static int parseInteger(final String value, final int defaultVal) {
        if (value == null) {
            return defaultVal;
        }

        if (value.trim().equals("")) {
            return defaultVal;
        }

        try {
            return new Integer(value).intValue();
        } catch (Exception ex) {
            log.error("An error occurred trying to parse the http parameter " + value + " to an int.");
        }

        return defaultVal;
    }

    /**
     * Take a jpeg from an input stream and write it to an output.
     * stream with a scaled width and height
     * @param sos output stream for image
     * @param is input stream for image
     * @param width width
     * @param height height
     * @throws IOException if there is an error writing or reading
     */
    public static void writeScaledImageToStream(final OutputStream sos, final InputStream is, final int width,
            final int height) throws IOException {
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
        BufferedImage origImage = decoder.decodeAsBufferedImage();
        int origHeight = origImage.getHeight(null);
        int origWidth = origImage.getWidth(null);
        int scaledW = 0;
        int scaledH = 0;
        double scaleW = 1.0;
        double scaleH = 1.0;

        // close input stream
        is.close();

        // Calculate scale factors
        if (width == 0) {
            scaleW = (double) height / (double) origHeight;
            scaleH = (double) height / (double) origHeight;
        } else if (height == 0) {
            scaleW = (double) width / (double) origWidth;
            scaleH = (double) width / (double) origWidth;
        } else {
            scaleW = (double) width / (double) origWidth;
            scaleH = (double) height / (double) origHeight;
        }

        scaledW = (int) (scaleW * origWidth);
        scaledH = (int) (scaleH * origHeight);

        BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
        AffineTransform tx = new AffineTransform();

        tx.scale(scaleW, scaleH);

        AffineTransformOp af = new AffineTransformOp(tx, null);

        af.filter(origImage, outImage);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

        encoder.encode(outImage);
    }

    /**
     * Writes the entire input stream to the output stream
     * then closes the input stream.
     * @param sos output stream
     * @param is input stream
     * @throws IOException if there is an error reading or writing
     */
    public static void writeInputStreamToOutputStream(final OutputStream sos, final InputStream is)
            throws IOException {
        BufferedInputStream in = new BufferedInputStream(is);
        int data;

        while ((data = in.read()) != -1) {
            sos.write(data);
        }

        is.close();
    }

    public static String getConfigFileRealPath() {
        //net.sf.ginp.GinpServlet.getServletConfig().getServletContext().
        //getRealPath("/WEB-INF/ginp.xml")
        return "todo";
    }
}