⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exportimageservlet.java

📁 esri的ArcGIS Server超级学习模板程序(for java)
💻 JAVA
字号:
package com.esri.solutions.jitk.web.tasks.export.image;

import com.esri.adf.web.data.WebContext;
import com.esri.adf.web.data.WebMap;
import com.esri.adf.web.util.ImageUtil;

import com.esri.solutions.jitk.common.export.image.WebMapNASBImageExporter;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

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

import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * MVS-049: Export Image Servlet. This servlet returns the map image;
 */
@SuppressWarnings("serial")
public class ExportImageServlet extends HttpServlet {
    private static Logger _logger = LogManager.getLogger(ExportImageServlet.class.getName());
    private static final String WEBCONTEXT_INIT_PARAM_NAME = "WebContext";
    private static String CONTENT_TYPE = "application/download";
    private static String CONTENT_DISPOSITION = "Content-disposition";
    private static final String EXPORT_NORTHARROW_PARAM = "northArrow";
    private static final String EXPORT_SCALEBAR_PARAM = "scaleBar";
    private static final String EXPORT_GRAPHICRESOURCES_PARAM = "graphicResources";
    private static final String IMAGE_FORMAT = "PNG";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        WebContext webContext = null;
        WebMap webMap = null;
        String mwidth = null;
        String mheight = null;
        String format = null;
        WebMapNASBImageExporter exporter = null;
        FacesContext fc = null;
        String webContextName = null;
        boolean exportNorthArrowParam = true;
        boolean exportScalebarParam = true;
        boolean exportGraphicResources = true;

        if (request.getParameter(EXPORT_NORTHARROW_PARAM) != null) {
            String param = request.getParameter(EXPORT_NORTHARROW_PARAM);

            exportNorthArrowParam = Boolean.valueOf(param);
        }

        if (request.getParameter(EXPORT_SCALEBAR_PARAM) != null) {
            String param = request.getParameter(EXPORT_SCALEBAR_PARAM);

            exportScalebarParam = Boolean.valueOf(param);
        }

        if (request.getParameter(EXPORT_GRAPHICRESOURCES_PARAM) != null) {
            String param = request.getParameter(EXPORT_GRAPHICRESOURCES_PARAM);

            exportGraphicResources = Boolean.valueOf(param);
        }

        webContextName = getServletConfig()
                             .getInitParameter(WEBCONTEXT_INIT_PARAM_NAME);

        if (webContextName == null) {
            response.getWriter()
                    .write(generateErrorHtml(
                    "An error has occurred exporting map image.  Possible configuration problem."));

            _logger.debug("Missing servlet initialization parameter '" +
                WEBCONTEXT_INIT_PARAM_NAME + "' for servlet: " +
                getServletConfig().getServletName() +
                " - cannot export map image");

            response.getWriter().flush();
            response.getWriter().close();

            return;
        }

        fc = this.getFacesContext(request, response);

        if (!(fc.getApplication().getVariableResolver()
                    .resolveVariable(fc, webContextName) instanceof WebContext)) {
            response.getWriter()
                    .write(generateErrorHtml(
                    "An error has occurred exporting map image.  Possible configuration problem."));

            _logger.debug("WebContext bean is not of type '" +
                WebContext.class.getName() + "' - cannot export map image");

            response.getWriter().flush();
            response.getWriter().close();

            return;
        }

        webContext = (WebContext) fc.getApplication().getVariableResolver()
                                    .resolveVariable(fc, webContextName);

        webMap = webContext.getWebMap();

        mwidth = request.getParameter("width");

        if (mwidth == null) {
            mwidth = String.valueOf(webMap.getWidth());
        }

        mheight = request.getParameter("height");

        if (mheight == null) {
            mheight = String.valueOf(webMap.getHeight());
        }

        format = request.getParameter("format");

        if (format == null) {
            format = webMap.getImageFormat();
        }

        try {
            exporter = new WebMapNASBImageExporter(webContext);
            exporter.setExportNorthArrow(exportNorthArrowParam);
            exporter.setExportScalebar(exportScalebarParam);
            exporter.setDpi(webMap.getDpi());
            exporter.setImageHeight(Integer.parseInt(mheight));
            exporter.setImageWidth(Integer.parseInt(mwidth));
            exporter.setImageFormatAsString(IMAGE_FORMAT);
            exporter.setWebMap(webMap);
            exporter.setExportGraphicsResources(exportGraphicResources);

            response.setContentType(CONTENT_TYPE);
            response.setHeader(CONTENT_DISPOSITION,
                "attachment; filename=ExportMapImage" +
                this.getImageExtension(format));

            byte[] finalImage = this.convertImage(exporter.exportImageToBytes(),
                    IMAGE_FORMAT, format);

            OutputStream out = response.getOutputStream();

            out.write(finalImage);
            out.flush();
            out.close();
        } catch (Exception ex) {
            _logger.warn("An exception has occurred exporting map image", ex);
        }
    }

    private byte[] convertImage(byte[] image, String inFormat, String outFormat) {
        byte[] finalImage = null;
        InputStream imageIn = null;
        InputStream[] images = null;
        double[] transparencies = null;

        if (image == null) {
            throw new NullPointerException("image can not be null");
        }

        if (inFormat == null) {
            throw new NullPointerException("In format can not be null");
        }

        if (outFormat == null) {
            throw new NullPointerException("Out format can not be null");
        }

        imageIn = new ByteArrayInputStream(image);
        images = new InputStream[1];

        images[0] = imageIn;

        transparencies = new double[1];
        transparencies[0] = 0D;

        finalImage = ImageUtil.mergeImages(images, transparencies, inFormat,
                outFormat);

        return finalImage;
    }

    private String getImageExtension(String format) {
        try {
            if (format.toUpperCase().indexOf("BMP") >= 0) {
                return ".bmp";
            }

            if (format.toUpperCase().indexOf("GIF") >= 0) {
                return ".gif";
            }

            if (format.toUpperCase().indexOf("JPG") >= 0) {
                return ".jpg";
            }

            if (format.toUpperCase().indexOf("PNG") >= 0) {
                return ".png";
            }

            if (format.toUpperCase().indexOf("PNM") >= 0) {
                return ".pnm";
            }

            if (format.toUpperCase().indexOf("TIF") >= 0) {
                return ".tif";
            }
        } catch (Exception e) {
            _logger.warn("Unable to check content type", e);
        }

        return null;
    }

    /**
     * Utility method to get the {@link FacesContext} object via
     * the {@link FacesContextFactory#getFacesContext(Object, Object, Object, Lifecycle)}.
     *
     * @param request Reference to the {@link HttpServletRequest} needed for getting the
     *                 {@link FacesContext}.
     * @param response Reference to the {@link HttpServletResponse} needed for getting the
     *                 {@link FacesContext}.
     * @return {@link FacesContext} reference.
     */
    private FacesContext getFacesContext(HttpServletRequest request,
        HttpServletResponse response) {
        FacesContext facesContext = FacesContext.getCurrentInstance();

        if (facesContext == null) {
            FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
            LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
            Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

            facesContext = contextFactory.getFacesContext(getServletContext(),
                    request, response, lifecycle);
        }

        return facesContext;
    }

    /**
     * Utility method to generate an HTML message that can be
     * sent back to the client.
     *
     * @param message {@link String} message.
     * @return HTML message that can be viewed in a browser.
     */
    private String generateErrorHtml(String message) {
        StringBuilder errorHtml = null;

        errorHtml = new StringBuilder();

        errorHtml.append("<html>");
        errorHtml.append("<head>");
        errorHtml.append("<title>");
        errorHtml.append("Error Exporting CS/W Query");
        errorHtml.append("</title>");
        errorHtml.append("</head>");
        errorHtml.append("<body>");
        errorHtml.append(message);
        errorHtml.append("</body>");
        errorHtml.append("</html>");

        return errorHtml.toString();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -