Example usage for java.awt.image BufferedImage TYPE_INT_ARGB

List of usage examples for java.awt.image BufferedImage TYPE_INT_ARGB

Introduction

In this page you can find the example usage for java.awt.image BufferedImage TYPE_INT_ARGB.

Prototype

int TYPE_INT_ARGB

To view the source code for java.awt.image BufferedImage TYPE_INT_ARGB.

Click Source Link

Document

Represents an image with 8-bit RGBA color components packed into integer pixels.

Usage

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

/**
 * Draw the stretch and content area defined by the {@link NinePatch} around the given image
 * @param is/*from   ww  w.  ja  v  a2 s.c  o m*/
 * @param finalName
 * @param ninePatch
 * @param ratio
 * @throws IOException
 */
private void toNinePatch(final InputStream is, final String finalName, final NinePatch ninePatch,
        final double ratio) throws IOException {
    BufferedImage image = ImageIO.read(is);
    final int w = image.getWidth();
    final int h = image.getHeight();
    BufferedImage ninePatchImage = new BufferedImage(w + 2, h + 2, BufferedImage.TYPE_INT_ARGB);
    Graphics g = ninePatchImage.getGraphics();
    g.drawImage(image, 1, 1, null);

    // draw patch
    g.setColor(Color.BLACK);

    Zone stretch = ninePatch.getStretch();
    Zone content = ninePatch.getContent();

    if (stretch.getX() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch stretch(x) [start=0 - size=" + w + "]");
        }
        g.fillRect(1, 0, w, 1);
    } else {
        for (int[] seg : stretch.getX()) {
            final int start = NinePatch.start(seg[0], seg[1], w, ratio);
            final int size = NinePatch.size(seg[0], seg[1], w, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch stretch(x) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(start + 1, 0, size, 1);
        }
    }

    if (stretch.getY() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch stretch(y) [start=0 - size=" + h + "]");
        }
        g.fillRect(0, 1, 1, h);
    } else {
        for (int[] seg : stretch.getY()) {
            final int start = NinePatch.start(seg[0], seg[1], h, ratio);
            final int size = NinePatch.size(seg[0], seg[1], h, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch stretch(y) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(0, start + 1, 1, size);
        }
    }

    if (content.getX() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch content(x) [start=0 - size=" + w + "]");
        }
        g.fillRect(1, h + 1, w, 1);
    } else {
        for (int[] seg : content.getX()) {
            final int start = NinePatch.start(seg[0], seg[1], w, ratio);
            final int size = NinePatch.size(seg[0], seg[1], w, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch content(x) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(start + 1, h + 1, size, 1);
        }
    }

    if (content.getY() == null) {
        if (getLog().isDebugEnabled()) {
            getLog().debug("+ ninepatch content(y) [start=0 - size=" + h + "]");
        }
        g.fillRect(w + 1, 1, 1, h);
    } else {
        for (int[] seg : content.getY()) {
            final int start = NinePatch.start(seg[0], seg[1], h, ratio);
            final int size = NinePatch.size(seg[0], seg[1], h, ratio);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ ninepatch content(y) [start=" + start + " - size=" + size + "]");
            }
            g.fillRect(w + 1, start + 1, 1, size);
        }
    }

    ImageIO.write(ninePatchImage, "png", new File(finalName));
}

From source file:edu.ku.brc.ui.GraphicsUtils.java

/**
 * @param name//from w  ww  .j av a2s.c om
 * @param imgIcon
 * @return
 */
public static String uuencodeImage(final String name, final ImageIcon imgIcon) {
    try {
        BufferedImage tmp = new BufferedImage(imgIcon.getIconWidth(), imgIcon.getIconWidth(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = tmp.createGraphics();
        //g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(imgIcon.getImage(), 0, 0, imgIcon.getIconWidth(), imgIcon.getIconWidth(), null);
        g2.dispose();

        ByteArrayOutputStream output = new ByteArrayOutputStream(8192);
        ImageIO.write(tmp, "PNG", output);
        byte[] outputBytes = output.toByteArray();
        output.close();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        UUEncoder uuencode = new UUEncoder(name);
        uuencode.encode(new ByteArrayInputStream(outputBytes), bos);
        return bos.toString();

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(GraphicsUtils.class, ex);
        ex.printStackTrace();
    }
    return "";
}

From source file:com.lizardtech.expresszip.model.Job.java

private void exportTile(TileExport t, String jobName, String format, int counter) throws Exception {

    if (shutdown)
        throw new RuntimeException("Cancelled");

    ReferencedEnvelope tileBounds = null;
    Rectangle imageBounds = null;

    double minx = Math.min(t.bounds.getLeft(), t.bounds.getRight());
    double maxx = Math.max(t.bounds.getLeft(), t.bounds.getRight());
    double miny = Math.min(t.bounds.getTop(), t.bounds.getBottom());
    double maxy = Math.max(t.bounds.getTop(), t.bounds.getBottom());
    logger.info(String.format("Adding tile %d x: %f - %f, y: %f - %f", counter, minx, maxx, miny, maxy));
    if (jobParams.isProjectedCRS(CRS.decode(jobParams.getMapProjection()))) {
        tileBounds = new ReferencedEnvelope(t.bounds.getLeft(), t.bounds.getRight(), t.bounds.getTop(),
                t.bounds.getBottom(), CRS.decode(jobParams.getMapProjection()));

    } else {//from  www .j a va  2s.c o m
        tileBounds = new ReferencedEnvelope(minx, maxx, miny, maxy, CRS.decode(jobParams.getMapProjection()));
    }

    // Set view point on map
    MapViewport viewport = new MapViewport(tileBounds);
    viewport.setCoordinateReferenceSystem(CRS.decode(jobParams.getMapProjection()));

    // Create the bound for the image
    imageBounds = new Rectangle(0, 0, t.width, t.height);

    // Set up an ImageBuffer to write image to
    logger.info(
            String.format("Allocating BufferedImage of size %d x %d", imageBounds.width, imageBounds.height));
    int bufferType = BufferedImage.TYPE_INT_RGB;
    if (extensions.valueOf(format) == extensions.png)
        bufferType = BufferedImage.TYPE_INT_ARGB;

    BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, bufferType);
    Graphics2D graphics = image.createGraphics();

    // Render the unclipped image
    MapContent map = new MapContent();
    map.setViewport(viewport);

    WebMapServer wms = new WebMapServer(MapModel.getPrivateServerURL(), getWMSTimeOut());
    WMSLayer wmsLayer = null;
    for (ExpressZipLayer l : jobParams.getEnabledLayers()) {
        if (l instanceof RasterLayer && l.projectionIsSupported(jobParams.getMapProjection())) {
            if (wmsLayer == null)
                wmsLayer = new WMSLayer(wms, l.getGeoToolsLayer());
            else
                wmsLayer.addLayer(l.getGeoToolsLayer());
        }
    }
    if (wmsLayer != null)
        map.addLayer(wmsLayer);

    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(map);
    renderer.addRenderListener(new RenderListener() {

        @Override
        public void featureRenderer(SimpleFeature feature) {
        }

        @Override
        public void errorOccurred(Exception e) {
            logger.error("Streaming Renderer for tile failed (" + e.getMessage() + ")");
            throw new RuntimeException(e);
        }
    });

    try {
        renderer.paint(graphics, imageBounds, tileBounds);
    } finally {

        try {
            // clean up
            graphics.dispose();
        } catch (Exception e) {
        }

        try {
            map.dispose();
        } catch (Exception e) {
        }
    }

    // Clip the image to the shapefile
    if (cropFile != null) {
        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = getFeatureSource(cropFile);
        GridCoverage2D clippedCoverage = (GridCoverage2D) clipImageToFeatureSource(image, tileBounds,
                featureSource);
        if (null == clippedCoverage) {
            logger.info("Tile does not intersect shapefile. Skipping.");
            return;
        }
        BufferedImage matted = mattCroppedImage(image, clippedCoverage, bufferType);
        image = matted;
    }

    // Save the image
    String fileBase = "";
    File fileToSave = null;
    try {
        do {
            fileBase = jobName;
            if (counter > 0)
                fileBase = fileBase + "_" + counter;
            fileToSave = new File(exportDir, fileBase + "." + format);
            counter++;
        } while (!fileToSave.createNewFile());

        logger.info(String.format("Writing image %s", fileToSave.getAbsolutePath()));

        GridCoverageFactory factory = new GridCoverageFactory();
        GridCoverage2D coverage = factory.create("LT", image, tileBounds);
        AbstractGridCoverageWriter coverageWriter = null;
        GeneralParameterValue[] formatParam = null;
        if (format.equals(extensions.tif.toString())) {
            ParameterValueGroup params = new GeoTiffFormat().getWriteParameters();
            params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString())
                    .setValue(geoTiffWPs);
            coverageWriter = new GeoTiffWriter(fileToSave);
            formatParam = (GeneralParameterValue[]) params.values().toArray(new GeneralParameterValue[1]);
        } else {
            ParameterValueGroup params = new WorldImageFormat().getWriteParameters();
            params.parameter(WorldImageFormat.FORMAT.getName().toString()).setValue(format);
            formatParam = new GeneralParameterValue[] {
                    params.parameter(WorldImageFormat.FORMAT.getName().toString()) };
            coverageWriter = new WorldImageWriter(fileToSave);
        }
        try {
            coverageWriter.write(coverage, formatParam);
        } finally {
            try {
                coverageWriter.dispose();
            } catch (Exception e) {
            }

            try {
                coverage.dispose(true);
            } catch (Exception e) {
            }
        }
    } catch (Exception e) {
        logger.error(
                String.format("FAILED writing image %s (%s)", fileToSave.getAbsolutePath(), e.getMessage()));
        throw new RuntimeException(e);
    }

    // Gather up fileBase.* (include world and prj filenames) for zip file
    for (File child : exportDir.listFiles()) {
        String childName = child.getName();
        String baseName = FilenameUtils.getBaseName(childName);
        if (child.isFile() && baseName.equals(fileBase)) {
            String extension = FilenameUtils.getExtension(childName);
            extension.toLowerCase();
            if (extension.length() == 4 && extension.endsWith("w")) {
                extension = extension.substring(0, 1) + extension.substring(2);
                File renamedChild = new File(exportDir, baseName + "." + extension);
                child.renameTo(renamedChild);
                child = renamedChild;
            }

            outputTiles.add(child.getName());
        }
    }
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java

private void prepareScaleBar(Map<String, Object> params, String scalebarKey, XMLAdapter jrxmlAdapter,
        List<OrderedDatasource<?>> datasources, String type, Envelope bbox, double mapWidth)
        throws ProcessletException {

    OMElement sbRep = jrxmlAdapter.getElement(jrxmlAdapter.getRootElement(), new XPath(
            ".//jasper:image[jasper:imageExpression/text()='$P{" + scalebarKey + "}']/jasper:reportElement",
            nsContext));//from   w w  w.j a v a 2 s  .c  om

    if (sbRep != null) {
        // TODO: rework this!
        LOG.debug("Found scalebar with key '" + scalebarKey + "'.");
        int w = jrxmlAdapter.getRequiredNodeAsInteger(sbRep, new XPath("@width", nsContext));
        int h = jrxmlAdapter.getRequiredNodeAsInteger(sbRep, new XPath("@height", nsContext));
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();

        String fontName = null;
        int fontSize = 8;
        int desiredWidth = w - 30;
        // calculate scale bar max scale and size
        int length = 0;
        double lx = 0;
        double scale = 0;
        for (int i = 0; i < 100; i++) {
            double k = 0;
            double dec = 30 * Math.pow(10, i);
            for (int j = 0; j < 9; j++) {
                k += dec;
                double tx = -k * (mapWidth / bbox.getSpan0());
                if (Math.abs(tx - lx) < desiredWidth) {
                    length = (int) Math.round(Math.abs(tx - lx));
                    scale = k;
                } else {
                    break;
                }
            }
        }
        // draw scale bar base line
        g.setStroke(new BasicStroke((desiredWidth + 30) / 250));
        g.setColor(Color.black);
        g.drawLine(10, 30, length + 10, 30);
        double dx = length / 3d;
        double vdx = scale / 3;
        double div = 1;
        String uom = "m";
        if (scale > 1000) {
            div = 1000;
            uom = "km";
        }
        // draw scale bar scales
        if (fontName == null) {
            fontName = "SANS SERIF";
        }
        g.setFont(new Font(fontName, Font.PLAIN, fontSize));
        DecimalFormat df = new DecimalFormat("##.# ");
        DecimalFormat dfWithUom = new DecimalFormat("##.# " + uom);
        for (int i = 0; i < 4; i++) {
            String label = i < 3 ? df.format((vdx * i) / div) : dfWithUom.format((vdx * i) / div);
            g.drawString(label, (int) Math.round(10 + i * dx) - 8, 10);
            g.drawLine((int) Math.round(10 + i * dx), 30, (int) Math.round(10 + i * dx), 20);
        }
        for (int i = 0; i < 7; i++) {
            g.drawLine((int) Math.round(10 + i * dx / 2d), 30, (int) Math.round(10 + i * dx / 2d), 25);
        }
        g.dispose();
        params.put(scalebarKey, convertImageToReportFormat(type, img));
        LOG.debug("added scalebar");
    }
}

From source file:edu.umn.cs.spatialHadoop.operations.Plot.java

public static <S extends Shape> void plotLocal(Path inFile, Path outFile, S shape, int width, int height,
        Color color, boolean showBorders, boolean showBlockCount, boolean showRecordCount) throws IOException {
    FileSystem inFs = inFile.getFileSystem(new Configuration());
    Rectangle fileMbr = FileMBR.fileMBRLocal(inFs, inFile, shape);
    LOG.info("FileMBR: " + fileMbr);

    // Adjust width and height to maintain aspect ratio
    if ((fileMbr.x2 - fileMbr.x1) / (fileMbr.y2 - fileMbr.y1) > (double) width / height) {
        // Fix width and change height
        height = (int) ((fileMbr.y2 - fileMbr.y1) * width / (fileMbr.x2 - fileMbr.x1));
    } else {/*w w w .  ja va  2s  .co m*/
        width = (int) ((fileMbr.x2 - fileMbr.x1) * height / (fileMbr.y2 - fileMbr.y1));
    }

    double scale2 = (double) width * height / ((double) (fileMbr.x2 - fileMbr.x1) * (fileMbr.y2 - fileMbr.y1));

    // Create an image
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    Color bg_color = new Color(0, 0, 0, 0);
    graphics.setBackground(bg_color);
    graphics.clearRect(0, 0, width, height);
    graphics.setColor(color);

    long fileLength = inFs.getFileStatus(inFile).getLen();
    ShapeRecordReader<S> reader = new ShapeRecordReader<S>(inFs.open(inFile), 0, fileLength);

    Rectangle cell = reader.createKey();
    while (reader.next(cell, shape)) {
        drawShape(graphics, shape, fileMbr, width, height, scale2);
    }

    reader.close();
    graphics.dispose();
    FileSystem outFs = outFile.getFileSystem(new Configuration());
    OutputStream out = outFs.create(outFile, true);
    ImageIO.write(image, "png", out);
    out.close();
}

From source file:au.org.ala.layers.web.UserDataService.java

@RequestMapping(value = WS_USERDATA_WMS, method = RequestMethod.GET)
public void getPointsMap(
        @RequestParam(value = "CQL_FILTER", required = false, defaultValue = "") String cql_filter,
        @RequestParam(value = "ENV", required = false, defaultValue = "") String env,
        @RequestParam(value = "BBOX", required = false, defaultValue = "") String bboxString,
        @RequestParam(value = "WIDTH", required = false, defaultValue = "") String widthString,
        @RequestParam(value = "HEIGHT", required = false, defaultValue = "") String heightString,
        HttpServletRequest request, HttpServletResponse response) {
    RecordsLookup.setUserDataDao(userDataDao);

    response.setHeader("Cache-Control", "max-age=86400"); //age == 1 day
    response.setContentType("image/png"); //only png images generated

    int width = 256, height = 256;
    try {/*from w w w.  j a va2s.co m*/
        width = Integer.parseInt(widthString);
        height = Integer.parseInt(heightString);
    } catch (Exception e) {
        logger.error("error parsing to int: " + widthString + " or " + heightString, e);
    }

    try {
        env = URLDecoder.decode(env, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.error("error decoding env from UTF-8: " + env, e);
    }
    int red = 0, green = 0, blue = 0, alpha = 0;
    String name = "circle";
    int size = 4;
    boolean uncertainty = false;
    String highlight = null;
    String colourMode = null;
    for (String s : env.split(";")) {
        String[] pair = s.split(":");
        if (pair[0].equals("color")) {
            while (pair[1].length() < 6) {
                pair[1] = "0" + pair[1];
            }
            red = Integer.parseInt(pair[1].substring(0, 2), 16);
            green = Integer.parseInt(pair[1].substring(2, 4), 16);
            blue = Integer.parseInt(pair[1].substring(4), 16);
        } else if (pair[0].equals("name")) {
            name = pair[1];
        } else if (pair[0].equals("size")) {
            size = Integer.parseInt(pair[1]);
        } else if (pair[0].equals("opacity")) {
            alpha = (int) (255 * Double.parseDouble(pair[1]));
            //            } else if (pair[0].equals("uncertainty")) {
            //                uncertainty = true;
        } else if (pair[0].equals("sel")) {
            try {
                highlight = URLDecoder.decode(s.substring(4), "UTF-8").replace("%3B", ";");
            } catch (Exception e) {
            }
        } else if (pair[0].equals("colormode")) {
            colourMode = pair[1];
        }
    }

    double[] bbox = new double[4];
    int i;
    i = 0;
    for (String s : bboxString.split(",")) {
        try {
            bbox[i] = Double.parseDouble(s);
            i++;
        } catch (Exception e) {
            logger.error("error converting bounding box value to double: " + s, e);
        }
    }
    try {

        //adjust bbox extents with half pixel width/height
        double pixelWidth = (bbox[2] - bbox[0]) / width;
        double pixelHeight = (bbox[3] - bbox[1]) / height;
        bbox[0] += pixelWidth / 2;
        bbox[2] -= pixelWidth / 2;
        bbox[1] += pixelHeight / 2;
        bbox[3] -= pixelHeight / 2;

        //offset for points bounding box by size
        double xoffset = (bbox[2] - bbox[0]) / (double) width
                * (size + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5);
        double yoffset = (bbox[3] - bbox[1]) / (double) height
                * (size + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5);

        //check offset for points bb by maximum uncertainty (?? 30k ??)
        if (uncertainty) {
            double xuoffset = 30000;
            double yuoffset = 30000;
            if (xoffset < xuoffset) {
                xoffset = xuoffset;
            }
            if (yoffset < yuoffset) {
                yoffset = yuoffset;
            }
        }

        //adjust offset for pixel height/width
        xoffset += pixelWidth;
        yoffset += pixelHeight;

        double[][] bb = {
                { SpatialUtils.convertMetersToLng(bbox[0] - xoffset),
                        SpatialUtils.convertMetersToLat(bbox[1] - yoffset) },
                { SpatialUtils.convertMetersToLng(bbox[2] + xoffset),
                        SpatialUtils.convertMetersToLat(bbox[3] + yoffset) } };

        double[] pbbox = new double[4]; //pixel bounding box
        pbbox[0] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[0]));
        pbbox[1] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[1]));
        pbbox[2] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[2]));
        pbbox[3] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[3]));

        String lsid = null;
        int p1 = 0;
        int p2 = cql_filter.indexOf('&', p1 + 1);
        if (p2 < 0) {
            p2 = cql_filter.indexOf(';', p1 + 1);
        }
        if (p2 < 0) {
            p2 = cql_filter.length();
        }
        if (p1 >= 0) {
            lsid = cql_filter.substring(0, p2);
        }

        double[] points = null;
        ArrayList<QueryField> listHighlight = null;
        QueryField colours = null;
        double[] pointsBB = null;
        Facet facet = null;
        String[] facetFields = null;
        if (highlight != null && !(colourMode != null && colourMode.equals("grid"))) {
            facet = Facet.parseFacet(highlight);
            facetFields = facet.getFields();
            listHighlight = new ArrayList<QueryField>();
        }

        int[] idx = null;
        if (lsid != null) {
            Object[] data = (Object[]) RecordsLookup.getData(lsid);
            points = (double[]) data[1];
            pointsBB = (double[]) data[4];
            idx = (int[]) data[5];

            if (points == null || points.length == 0 || pointsBB[0] > bb[1][0] || pointsBB[2] < bb[0][0]
                    || pointsBB[1] > bb[1][1] || pointsBB[3] < bb[0][1]) {
                setImageBlank(response);
                return;
            }

            ArrayList<QueryField> fields = (ArrayList<QueryField>) data[2];

            for (int j = 0; j < fields.size(); j++) {
                if (facet != null) {
                    for (int k = 0; k < facetFields.length; k++) {
                        if (facetFields[k].equals(fields.get(j).getName())) {
                            listHighlight.add(fields.get(j));
                        }
                    }
                }
                if (colourMode != null) {
                    if (fields.get(j).getName().equals(colourMode)) {
                        synchronized (fields.get(j)) {
                            //need to resize 'colours' facet to the correct length and store as new QueryField
                            for (int k = 0; k < fields.size(); k++) {
                                if (fields.get(k).getName().equals(colourMode + " resized")) {
                                    colours = fields.get(k);
                                }
                            }

                            if (colours == null) {
                                colours = fields.get(j);

                                //does it need to be rebuilt to the correct length?
                                int count = colours.getIntData() != null ? colours.getIntData().length
                                        : colours.getLongData() != null ? colours.getLongData().length
                                                : colours.getFloatData() != null ? colours.getFloatData().length
                                                        : colours.getDoubleData() != null
                                                                ? colours.getDoubleData().length
                                                                : 0;
                                if (count != points.length / 2) {
                                    QueryField qf = new QueryField();
                                    qf.setDisplayName(colours.getDisplayName());
                                    qf.setName(colours.getName() + " resized");
                                    for (int k = 0; k < idx.length; k++) {
                                        qf.add(colours.getAsString(idx[k]));
                                    }
                                    qf.store();

                                    fields.add(qf);

                                    colours = qf;
                                }
                            }
                        }
                    }
                }
            }
        }

        /* TODO: make this a copy instead of create */
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, width, height);

        g.setColor(new Color(red, green, blue, alpha));
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        int x, y;
        int pointWidth = size * 2 + 1;
        double width_mult = (width / (pbbox[2] - pbbox[0]));
        double height_mult = (height / (pbbox[1] - pbbox[3]));

        if (colourMode != null && colourMode.equals("grid")) {
            int divs = 16;
            double grid_width_mult = (width / (pbbox[2] - pbbox[0])) / (256 / divs);
            double grid_height_mult = (height / (pbbox[1] - pbbox[3])) / (256 / divs);
            int[][] gridCounts = new int[divs][divs];
            for (i = 0; i < points.length; i += 2) {
                x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * grid_width_mult);
                y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * grid_height_mult);
                if (x >= 0 && x < divs && y >= 0 && y < divs) {
                    gridCounts[x][y]++;
                }
            }
            int xstep = 256 / divs;
            int ystep = 256 / divs;
            for (x = 0; x < divs; x++) {
                for (y = 0; y < divs; y++) {
                    int v = gridCounts[x][y];
                    if (v > 0) {
                        if (v > 500) {
                            v = 500;
                        }
                        int colour = Legend.getLinearColour(v, 0, 500, 0xFFFFFF00, 0xFFFF0000);
                        g.setColor(new Color(colour));
                        g.fillRect(x * xstep, y * ystep, xstep, ystep);
                    }
                }
            }
        } else {
            //circle type
            if (name.equals("circle")) {
                if (colours == null) {
                    for (i = 0; i < points.length; i += 2) {
                        if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                                && points[i + 1] <= bb[1][1]) {
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.fillOval(x - size, y - size, pointWidth, pointWidth);
                        }
                    }
                } else {
                    int prevColour = -1; //!= colours[0]
                    g.setColor(new Color(prevColour));
                    for (i = 0; i < points.length; i += 2) {
                        if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                                && points[i + 1] <= bb[1][1]) {
                            //colours is made the correct length, see above
                            int thisColour = colours.getColour(i / 2);
                            if (thisColour != prevColour) {
                                g.setColor(new Color(thisColour));
                                prevColour = thisColour;
                            }
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.fillOval(x - size, y - size, pointWidth, pointWidth);
                        }
                    }
                }
            }

            if (highlight != null && facet != null) {
                g.setStroke(new BasicStroke(2));
                g.setColor(new Color(255, 0, 0, 255));
                int sz = size + HIGHLIGHT_RADIUS;
                int w = sz * 2 + 1;

                for (i = 0; i < points.length; i += 2) {
                    if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1]
                            && points[i + 1] <= bb[1][1]) {

                        if (facet.isValid(listHighlight, idx[i / 2])) {
                            x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult);
                            y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3])
                                    * height_mult);
                            g.drawOval(x - sz, y - sz, w, w);
                        }
                    }
                }
            }
        }

        g.dispose();

        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(img, "png", os);
            os.flush();
            os.close();
        } catch (IOException e) {
            logger.error("error in outputting wms/reflect image as png", e);
        }
    } catch (Exception e) {
        logger.error("error generating wms/reflect tile", e);
    }

    //logger.debug("[wms tile: " + (System.currentTimeMillis() - start) + "ms]");
}

From source file:com.ah.ui.actions.monitor.MapsAction.java

public String execute() throws Exception {
    Date start = new Date();
    String forward = globalForward();
    if (forward != null) {
        return forward;
    }//from  w w  w  .j a  v  a  2s .co m

    try {
        planToolConfig = PlanToolAction.getPlanToolConfig(domainId);
        MapContainerNode mapContainerNode = id == null ? null
                : (MapContainerNode) findBoById(MapNode.class, id, this);
        if ("mapClient".equals(operation)) {
            log.info("execute", "locate client: " + clientId + ", circle: " + ch1);
            if (clientId != null) {
                // AhClientSession client = QueryUtil.findBoById(
                // AhClientSession.class, clientId);
                AhClientSession client = DBOperationUtil.findBoById(AhClientSession.class, clientId);
                if (client != null) {
                    bssid = client.getClientMac();
                    bssidType = BSSID_TYPE_CLIENT;
                    if (ch1 == 1) {
                        bssid = '|' + bssid;
                    }
                }
            }
            return mapPage(start);
        } else if ("mapRogue".equals(operation)) {
            log.info("execute", "locate rogue: " + clientId);
            if (clientId != null) {
                Idp rogue = QueryUtil.findBoById(Idp.class, clientId);
                if (rogue != null) {
                    bssid = rogue.getIfMacAddress();
                    bssidType = BSSID_TYPE_ROGUE;
                }
            }
            return mapPage(start);
        } else if ("mapDetails".equals(operation)) {
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            mapAlarmsCache.setMapId(id, pageId);
            mapAlarmsCache.setTreeNodeExpanded(id, true);
            prepareMapNode(mapContainerNode);
            if (null != HmBeTopoUtil.getPollingController()) {
                // put this map container into polling list.
                HmBeTopoUtil.getPollingController().addContainer(this.request.getSession(), id);
            }
            // save the selected map id into session
            setSelectedMapId(id);
            return "json";
        } else if ("nodes".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", apLabels: " + apLabels);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonObject = prepareNodes(mapAlarmsCache.getMapNodes(id, pageId), pageId, scale);
            Map<Short, Short> ch1IndexMap = createChIndexMap(null, null);
            Map<Short, Short> ch2IndexMap = createChIndexMap(null, null);
            List<MapContainerNode> floors = BoMgmt.getLocationTracking().assignChannels(mapContainerNode,
                    planToolConfig, ch1IndexMap, ch2IndexMap);
            if (mapContainerNode.getMapType() == MapContainerNode.MAP_TYPE_FLOOR) {
                // Resetting floor cache
                FloorCache cache = new FloorCache(id);
                saveChannelAssignments(mapContainerNode, floors, cache, ch1IndexMap, ch2IndexMap, false);
                log.info("Resetting floor cache.");
                setFloorCache(cache);
            } else {
                removeFloorCache();
            }
            jsonObject.put("pageId", pageId);
            jsonObject.put("planned",
                    preparePlannedAPs(mapContainerNode, false, scale, null, ch1IndexMap, ch2IndexMap));
            jsonObject.put("perim", preparePerimeter(mapContainerNode.getPerimeter(), scale));
            jsonObject.put("walls", prepareWalls(mapContainerNode.getWalls(), scale));
            log.debug("execute", "Prepared nodes: " + jsonObject.toString());
            log.info_ln("maps.action nodes: " + (new Date().getTime() - start.getTime()) + " ms.");
            return "json";
        } else if ("links".equals(operation)) {
            log.info("execute", "Scale: " + scale);
            jsonObject = prepareLinks(mapContainerNode.getChildLinks().values(), pageId, getShowRssi());
            log.debug("execute", "Prepared links: " + jsonObject.toString());
            log.info_ln("maps.action links: " + (new Date().getTime() - start.getTime()) + " ms.");
            return "json";
        } else if ("alarms".equals(operation)) {
            log.info("execute", "Polling for new alarms, scale: " + scale + ", rogueChecked?" + rogueChecked
                    + ", clientChecked?" + clientChecked + ", summaryChecked?" + summaryChecked);
            prepareAlarms(id);
            log.info("execute", "Returning alarms:" + jsonObject.toString());
            return "json";
        } else if ("saveNode".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", nodeId: " + bssid + ", x: " + pwr1 + ", y: " + ch1);
            MgrUtil.removeSessionAttribute(SessionKeys.MR_HEAT_MAP);
            saveNode(Long.parseLong(bssid.substring(1)), pwr1, ch1);
            return "json";
        } else if ("saveNodes".equals(operation)) {
            log.info("execute", "Scale: " + scale);
            MgrUtil.removeSessionAttribute(SessionKeys.MR_HEAT_MAP);
            if (selectedIds != null) {
                for (int i = 0; i < selectedIds.size(); i++) {
                    saveNode(selectedIds.get(i), xs.get(i), ys.get(i));
                }
            }
            return null;
        } else if ("validatePerimeter".equals(operation)) {
            log.info("execute", "Scale: " + scale);
            Point2D[] walls = null;
            if (xs != null) {
                walls = new Point2D[xs.size()];
                for (int i = 0; i < xs.size(); i++) {
                    walls[i] = new Point2D.Double(xs.get(i), ys.get(i));
                    log.info("execute", "Perimeter node: " + walls[i].toString());
                }
            }
            jsonArray = new JSONArray(validatePerimeter(walls, mapContainerNode.getPerimeter(), scale));
            return "json";
        } else if ("clients".equals(operation)) {
            log.info("execute", "Scale: " + scale);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonObject = prepareClients(mapContainerNode, mapAlarmsCache.getMapNodes(id, pageId), pageId,
                    scale);
            log.debug("execute", "Prepared clients: " + jsonObject.toString());
            return "json";
        } else if ("rogues".equals(operation)) {
            log.info("execute", "Scale: " + scale);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonObject = prepareRogues(mapContainerNode, mapAlarmsCache.getMapNodes(id, pageId), pageId, scale);
            log.debug("execute", "Prepared rogues: " + jsonObject.toString());
            return "json";
        } else if ("acspNbrRssi".equals(operation)) {
            log.info("execute",
                    "acspNbrRssi Scale: " + scale + ", frequency: " + frequency + ", leafNodeId: " + acspId);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonObject = BoMgmt.getLocationTracking().acspNbrRssi(mapContainerNode,
                    mapAlarmsCache.getMapNodes(id, pageId), pageId, scale, acspId, (frequency & 1) > 0);
            return "json";
        } else if ("clientRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonArray = new JSONArray(BoMgmt.getLocationTracking().clientRssi(mapContainerNode,
                    mapAlarmsCache.getMapNodes(id, pageId), pageId, scale, bssid));
            log.debug("execute", "Prepared rssi: " + jsonArray.toString());
            return "json";
        } else if ("clientRssiArea".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid + ", canvas: (" + canvasWidth + ", "
                    + canvasHeight + ")");
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            BoMgmt.getLocationTracking().clientRssi(mapContainerNode, mapAlarmsCache.getMapNodes(id, pageId),
                    pageId, scale, bssid);
            streamImage(BoMgmt.getLocationTracking().drawRssiArea(mapContainerNode, canvasWidth, canvasHeight));
            return null;
        } else if ("rogueRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            jsonArray = new JSONArray(BoMgmt.getLocationTracking().rogueRssi(mapContainerNode,
                    mapAlarmsCache.getMapNodes(id, pageId), pageId, scale, bssid));
            log.debug("execute", "Prepared rssi: " + jsonArray.toString());
            return "json";
        } else if ("rogueRssiArea".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid + ", canvas: (" + canvasWidth + ", "
                    + canvasHeight + ")");
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            BoMgmt.getLocationTracking().rogueRssi(mapContainerNode, mapAlarmsCache.getMapNodes(id, pageId),
                    pageId, scale, bssid);
            streamImage(BoMgmt.getLocationTracking().drawRssiArea(mapContainerNode, canvasWidth, canvasHeight));
            return null;
        } else if ("calibrateClientRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            log.info("execute", "x: " + xs + ", y: " + ys);
            int added = 0;
            if (xs != null && ys != null) {
                double x = reverseScale(xs.get(0));
                double y = reverseScale(ys.get(0));
                log.info("execute", "x: " + x + ", y: " + y);
                added = BoMgmt.getLocationTracking().calibrateClient(mapContainerNode,
                        mapAlarmsCache.getMapNodes(id, pageId), pageId, scale, bssid, x, y);
            }
            jsonObject = new JSONObject();
            jsonObject.put("added", added);
            jsonObject.put("mac", bssid);
            log.debug("execute", "calibrate rssi: " + jsonObject.toString());
            return "json";
        } else if ("uncalibrateClientRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MgrUtil.removeSessionAttribute(SessionKeys.MR_HEAT_MAP);
            int removed = QueryUtil.bulkRemoveBos(Trex.class, new FilterParams("tid", bssid),
                    mapContainerNode.getOwner().getId());
            log.info("execute", removed + " measurements removed.");
            jsonObject = new JSONObject();
            jsonObject.put("removed", removed);
            jsonObject.put("mac", bssid);
            log.debug("execute", "uncalibrate rssi: " + jsonObject.toString());
            return "json";
        } else if ("calibrateRogueRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            log.info("execute", "x: " + xs + ", y: " + ys);
            int added = 0;
            if (xs != null && ys != null) {
                double x = reverseScale(xs.get(0));
                double y = reverseScale(ys.get(0));
                log.info("execute", "x: " + x + ", y: " + y);
                added = BoMgmt.getLocationTracking().calibrateRogue(mapContainerNode,
                        mapAlarmsCache.getMapNodes(id, pageId), pageId, scale, bssid, x, y);
            }
            jsonObject = new JSONObject();
            jsonObject.put("added", added);
            log.debug("execute", "calibrate rssi: " + jsonObject.toString());
            return "json";
        } else if ("uncalibrateRogueRssi".equals(operation)) {
            log.info("execute", "Scale: " + scale + ", bssid: " + bssid);
            MgrUtil.removeSessionAttribute(SessionKeys.MR_HEAT_MAP);
            int removed = QueryUtil.bulkRemoveBos(Trex.class, new FilterParams("tid", bssid),
                    mapContainerNode.getOwner().getId());
            log.info("execute", removed + " measurements removed.");
            jsonObject = new JSONObject();
            jsonObject.put("removed", removed);
            log.debug("execute", "uncalibrate rssi: " + jsonObject.toString());
            return "json";
        } else if ("locateClient".equals(operation)) {
            log.info("execute", "Locating client: " + clientId + ", circle: " + ch1);
            jsonObject = BoMgmt.getLocationTracking().validateClientLocation(getDomain(), clientId, ch1 == 1);
            log.debug("execute", "locate client result: " + jsonObject.toString());
            return "json";
        } else if ("locateRogue".equals(operation)) {
            log.info("execute", "Locating rogue: " + clientId);
            jsonObject = BoMgmt.getLocationTracking().validateRogueLocation(getDomain(), clientId);
            log.debug("execute", "locate rogue result: " + jsonObject.toString());
            return "json";
        } else if ("heatMapHr".equals(operation)) {
            log.info("execute", "HR version of latchId: " + latchId + ", frequency: " + frequency);
            if (BoMgmt.getLocationTracking().estimateRssiHr(mapContainerNode, latchId)) {
                streamMapImage(mapContainerNode, MapSettings.HEATMAP_RESOLUTION_HIGH, frequency, layers,
                        (short) -1, 1, null, (short) 0, 0, 0);
            }
            return null;
        } else if ("heatMap".equals(operation)) {
            log.info("execute", "scale: " + scale);
            log.info("execute", "rssiThreshold: -" + rssiThreshold);
            if (scale > 0) {
                log.info("execute",
                        "canvas: (" + canvasWidth + ", " + canvasHeight + "), layers: " + layers + ", mac: "
                                + bssid + ", acspNbr: " + acspId + ", nextId: " + nextId + ", position (" + xs
                                + ", " + ys + ")" + ", actualWidth: " + mapContainerNode.getActualWidth());
                MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
                Set<MapNode> nodes = mapAlarmsCache.getMapNodes(id, pageId);
                log.info("execute", "Preparing heat map, latch ID: " + latchId);
                if (nodes.size() > 0 && mapContainerNode != null && canvasWidth > 0 && canvasHeight > 0
                        && mapContainerNode.getActualWidth() > 0) {
                    log.info("execute", "# nodes: " + nodes.size());
                    double x = 0, y = 0;
                    if (xs != null && ys != null) {
                        x = reverseScale(xs.get(0));
                        y = reverseScale(ys.get(0));
                    }
                    log.info("execute", "x: " + x + ", y: " + y);
                    int heatmapResolution = BoMgmt.getLocationTracking().computeRssi(mapContainerNode, nodes,
                            canvasWidth, canvasHeight, bssid, acspId, nextId, x, y, (frequency & 1) > 0,
                            (frequency & 2) > 0, getShadesPerColor(), latchId);
                    mapAlarmsCache.createHeatMapLatch(latchId, heatmapResolution);
                    log.info("execute", "Create channels latch ID: " + latchId);
                    if (heatmapResolution < 0) {
                        // No measurements or calibration failed (clbrb_w)
                        streamImage(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB));
                    } else {
                        streamMapImage(mapContainerNode, heatmapResolution, frequency, layers, (short) -1, 1,
                                null, (short) 0, 0, 0);
                    }
                }
            }
            return null;
        } else if ("channels".equals(operation)) {
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            Set<MapNode> nodes = mapAlarmsCache.getMapNodes(id, pageId);
            log.info("execute", "Get channels latch ID: " + latchId);
            int heatmapResolution = MapSettings.HEATMAP_RESOLUTION_HIGH;
            if (nodes.size() > 0 && mapContainerNode != null) {
                if (latchId == null) {
                    BoMgmt.getLocationTracking().fetchRadioAttributes(nodes);
                } else {
                    Integer hmr = mapAlarmsCache.getHeatMapLatch(latchId);
                    if (hmr == null) {
                        log.info("execute", "This is an obsoleted channel request, just return empty array.");
                        jsonArray = new JSONArray();
                        return "json";
                    } else {
                        heatmapResolution = hmr;
                    }
                }
            }
            log.info("execute", "Preparing node labels.");
            jsonArray = new JSONArray(prepareNodeChannels(nodes, pageId, (frequency & 1) > 0));
            if (jsonArray.length() > 0) {
                JSONObject fo = ((JSONObject) jsonArray.get(0));
                fo.put("latchId", latchId);
                fo.put("hmr", heatmapResolution);
            } else if (heatmapResolution < 0) {
                JSONObject fo = new JSONObject();
                fo.put("pageId", 0);
                fo.put("latchId", latchId);
                fo.put("hmr", heatmapResolution);
                Collection<JSONObject> jsonNodes = new Vector<JSONObject>();
                jsonNodes.add(fo);
                jsonArray = new JSONArray(jsonNodes);
            }
            log.debug("execute", "Prepared node labels: " + jsonArray.toString());
            return "json";
        } else if ("nextIds".equals(operation)) {
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            Set<MapNode> nodes = mapAlarmsCache.getMapNodes(id, pageId);
            log.info("execute", "Get next IDs for: " + latchId + ", frequency: " + frequency);
            jsonObject = new JSONObject();
            int heatmapResolution = BoMgmt.getLocationTracking().fetchActiveNbrs(mapContainerNode, nodes,
                    (frequency & 1) > 0, latchId, jsonObject);
            log.info("execute", "Preparing node labels.");
            jsonObject.put("latchId", latchId);
            jsonObject.put("hmr", heatmapResolution);
            jsonObject.put("pageId", pageId);
            jsonObject.put("channels", new JSONArray(prepareNodeChannels(nodes, pageId, (frequency & 1) > 0)));
            return "json";
        } else if ("rssiRange".equals(operation)) {
            log.info("execute", "rssiThreshold: -" + rssiThreshold);
            setSelectedRSSIThreshold(rssiThreshold);
            jsonArray = new JSONArray(BoMgmt.getLocationTracking().getRssiRange(getShadesPerColor()));
            log.debug("execute", "RSSI range: " + jsonArray.toString());
            return "json";
        } else if ("addSimAp".equals(operation)) {
            log.info("execute", "addSimAp, scale: " + scale + ", rssiThreshold: -" + rssiThreshold
                    + ", snrThreshold: " + snrThreshold + ", rateThreshold: " + rateThreshold);
            if (scale > 0 && mapContainerNode != null && canvasWidth > 0
                    && mapContainerNode.getActualWidth() > 0) {
                log.info("execute",
                        "canvas width: " + canvasWidth + ", frequency: " + frequency + ", layers: " + layers
                                + ", hwModel: " + hwModel + ", pwr (" + pwr1 + ", " + pwr2 + "), ch (" + ch1
                                + ", " + ch2 + "), all ch (" + ch1s + ", " + ch2s + "), all chi (" + ch1is
                                + ", " + ch2is + ", actualWidth: " + mapContainerNode.getActualWidth()
                                + ", locate X:" + latchId);
                // disable a radio which has one radio.
                if (hwModel == HiveAp.HIVEAP_MODEL_110 || hwModel == HiveAp.HIVEAP_MODEL_BR200_WP
                        || hwModel == HiveAp.HIVEAP_MODEL_BR200_LTE_VZ) {
                    planToolConfig.setWifi0Enabled((frequency & 1) > 0 ? false : true);
                    planToolConfig.setWifi1Enabled((frequency & 1) > 0 ? true : false);
                } else {
                    planToolConfig.setWifi0Enabled(true);
                    planToolConfig.setWifi1Enabled(hwModel != HiveAp.HIVEAP_MODEL_BR100);
                }
                planToolConfig.setDefaultApType(hwModel);
                planToolConfig.setWifi0Channel(ch1);
                planToolConfig.setWifi0Power(pwr1);
                planToolConfig.setWifi1Channel(ch2);
                planToolConfig.setWifi1Power(pwr2);
                PlanToolAction.savePlanToolConfig(planToolConfig, getDomain());
                addSimulatedAP(mapContainerNode, planToolConfig, latchId);
            }
            return "json";
        } else if ("autoSimAps".equals(operation)) {
            log.info("execute",
                    "Auto Sim APs, rssiThreshold: -" + rssiThreshold + ", frequency: " + frequency
                            + ", canvas (" + canvasWidth + ", " + canvasHeight + "), hwModel: " + hwModel
                            + ", pwr (" + pwr1 + ", " + pwr2 + "), ch (" + ch1 + ", " + ch2 + ")");
            if (mapContainerNode.getEnvironment() == EnumConstUtil.MAP_ENV_AUTO) {
                mapContainerNode.setEnvironment(EnumConstUtil.MAP_ENV_ENTERPRISE);
                QueryUtil.updateBo(mapContainerNode);
            }
            // disable a radio which has one radio.
            if (hwModel == HiveAp.HIVEAP_MODEL_110 || hwModel == HiveAp.HIVEAP_MODEL_BR200_WP
                    || hwModel == HiveAp.HIVEAP_MODEL_BR200_LTE_VZ) {
                planToolConfig.setWifi0Enabled((frequency & 1) > 0 ? false : true);
                planToolConfig.setWifi1Enabled((frequency & 1) > 0 ? true : false);
            } else {
                planToolConfig.setWifi0Enabled(true);
                planToolConfig.setWifi1Enabled(hwModel != HiveAp.HIVEAP_MODEL_BR100);
            }
            planToolConfig.setDefaultApType(hwModel);
            planToolConfig.setWifi0Channel(ch1);
            planToolConfig.setWifi0Power(pwr1);
            planToolConfig.setWifi1Channel(ch2);
            planToolConfig.setWifi1Power(pwr2);
            PlanToolAction.savePlanToolConfig(planToolConfig, getDomain());
            createAutoSimAps(mapContainerNode, planToolConfig,
                    BoMgmt.getLocationTracking().autoSimAps(mapContainerNode, planToolConfig, canvasWidth,
                            canvasHeight, (frequency & 1) > 0, getShadesPerColor(), 95.5));
            return "json";
        } else if ("updateSimApLaps".equals(operation)) {
            if (scale > 0 && mapContainerNode != null && canvasWidth > 0
                    && mapContainerNode.getActualWidth() > 0) {
                log.info("execute", "updateSimApLaps, canvas (" + canvasWidth + ", " + canvasHeight
                        + "), plannedId: " + bssid + ", hostName: " + hostName + ", pwr (" + pwr1 + ", " + pwr2
                        + "), ch (" + ch1 + ", " + ch2 + "), all ch (" + ch1s + ", " + ch2s + "), all chi ("
                        + ch1is + ", " + ch2is + "), x: " + pwr2 + ", y: " + ch2 + ", frequency: " + frequency
                        + ", channel width: " + channelWidth + ", fadeMargin: " + fadeMargin + ", layers: "
                        + layers + ", rssiThreshold: -" + rssiThreshold + ", snrThreshold: " + snrThreshold
                        + ", rateThreshold: " + rateThreshold + ", radio: " + radio);
                boolean useA = (frequency & 1) > 0;
                PlannedAP plannedAP = null;
                Map<Short, Short> ch1IndexMap = null;
                Map<Short, Short> ch2IndexMap = null;
                if (bssid.length() > 0) {
                    /*
                     * Update a single Planned AP, either its position
                     * (drag-n-drop), or the radio attributes (update AP
                     * details).
                     */
                    long plannedId = Long.parseLong(bssid.substring(1));
                    if (pwr1 > 0) {
                        /*
                         * Update planned AP
                         */
                        plannedAP = BoMgmt.getPlannedApMgmt().updatePlannedAP(mapContainerNode, plannedId,
                                hostName, hwModel, (short) ch1, (short) ch2, (short) pwr1, (short) pwr2, radio);
                    } else {
                        /*
                         * Move planned AP
                         */
                        plannedAP = BoMgmt.getPlannedApMgmt().movePlannedAP(mapContainerNode, plannedId,
                                reverseScale(pwr2), reverseScale(ch2));
                    }
                    FloorCache cache = clearNbrAps(mapContainerNode, plannedAP, plannedAP.getId(),
                            getFloorCache(id));
                    for (PlannedAP ap : mapContainerNode.getPlannedAPs()) {
                        if (ap.getId().equals(plannedAP.getId())) {
                            ap.apModel = plannedAP.apModel;
                            ap.hostName = plannedAP.hostName;
                            ap.countryCode = plannedAP.countryCode;
                            ap.wifi0Enabled = plannedAP.wifi0Enabled;
                            ap.wifi1Enabled = plannedAP.wifi1Enabled;
                            ap.wifi0Channel = plannedAP.wifi0Channel;
                            ap.wifi1Channel = plannedAP.wifi1Channel;
                            ap.wifi0Power = plannedAP.wifi0Power;
                            ap.wifi1Power = plannedAP.wifi1Power;
                            ap.x = plannedAP.x;
                            ap.y = plannedAP.y;
                        }
                    }
                    ch1IndexMap = createChIndexMap(ch1s, ch1is);
                    ch2IndexMap = createChIndexMap(ch2s, ch2is);
                    List<MapContainerNode> floors = BoMgmt.getLocationTracking()
                            .assignChannels(mapContainerNode, planToolConfig, ch1IndexMap, ch2IndexMap);
                    saveChannelAssignments(mapContainerNode, floors, cache, ch1IndexMap, ch2IndexMap, true);

                } else {
                    setSelectedLayers(layers);
                }
                Collection<JSONObject> jsonNodes = getPredictedLap(mapContainerNode, useA, plannedAP, (short) 0,
                        channelWidth, fadeMargin, false);
                if (plannedAP != null && jsonNodes.size() > 0) {
                    JSONObject jo = jsonNodes.iterator().next();
                    jo.put("planned",
                            preparePlannedAPs(mapContainerNode, true, scale, null, ch1IndexMap, ch2IndexMap));
                }
                jsonArray = new JSONArray(jsonNodes);
            }
            return "json";
        } else if ("predictedLap".equals(operation)) {
            if (scale > 0 && mapContainerNode != null && canvasWidth > 0
                    && mapContainerNode.getActualWidth() > 0) {
                log.info("execute",
                        "predictedLap: canvas (" + canvasWidth + ", " + canvasHeight + "), layers: " + layers
                                + ", power: " + pwr1 + ", chi: " + ch1 + ", channel width: " + channelWidth
                                + ", fadeMargin: " + fadeMargin + ", plannedId: " + bssid + ", rssiThreshold: -"
                                + rssiThreshold + ", snrThreshold: " + snrThreshold + ", rateThreshold: "
                                + rateThreshold);
                long plannedId = Long.parseLong(bssid.substring(1));
                PlannedAP plannedAP = BoMgmt.getPlannedApMgmt().findPlannedAP(plannedId);
                if (plannedAP != null) {
                    getPredictedLap(mapContainerNode, (frequency & 1) > 0, plannedAP, (short) ch1, channelWidth,
                            fadeMargin, true);
                }
            }
            return null;
        } else if ("cacheSpill".equals(operation)) {
            jsonObject = new JSONObject();
            FloorCache cache = getFloorCache(mapContainerNode.getId());
            if (cache == null || cache.mapChannels == null) {
                jsonObject.put("success", false);
                return "json";
            }
            jsonObject.put("w", cache.mapChannels.length * cache.imgScale);
            jsonObject.put("h", cache.mapChannels[0].length * cache.imgScale);
            cacheDoubleBuffer(mapContainerNode, cache, false);
            return "json";
        } else if ("updateSpillCache".equals(operation)) {
            log.info("execute", "updateSpillCache frequency: " + frequency + ", rssiThreshold: -"
                    + rssiThreshold + ", spillOnly: " + showSpill + ", channel width: " + channelWidth);
            jsonObject = new JSONObject();
            FloorCache cache = getFloorCache(mapContainerNode.getId());
            if (cache == null || cache.mapChannels == null) {
                jsonObject.put("success", false);
                return "json";
            }
            if (!showSpill) {
                cache.useA = (frequency & 1) > 0;
                cache.channelWidth = channelWidth;
                cache.shadesPerColor = getShadesPerColor();
            }
            int imageWidth = cache.spillRssi.length;
            int imageHeight = cache.spillRssi[0].length;
            cache.spillRssi = new float[imageWidth][imageHeight];
            cache.spillChannels = new short[imageWidth][imageHeight];
            if (!showSpill) {
                // Don't recalculate these
                cache.mapRssi = new float[imageWidth][imageHeight];
                cache.mapChannels = new short[imageWidth][imageHeight];
            }
            cacheDoubleBuffer(mapContainerNode, cache, showSpill);
            return "json";
        } else if ("planHeatMap".equals(operation)) {
            log.info("execute", "scale: " + scale);
            if (scale > 0 && mapContainerNode != null && canvasWidth > 0
                    && mapContainerNode.getActualWidth() > 0) {
                log.info("execute",
                        "canvas (" + canvasWidth + ", " + canvasHeight + "), rssiThreshold: -" + rssiThreshold);
                int resolution = BoMgmt.getLocationTracking().simApCoverage(mapContainerNode, planToolConfig,
                        canvasWidth, canvasHeight, (frequency & 1) > 0, getShadesPerColor());
                streamMapImage(mapContainerNode, resolution, frequency, 1, (short) -1, 1, null, (short) 0, 0,
                        0);
            }
            return null;
        } else if ("updateSnrThreshold".equals(operation)) {
            log.info("execute", "Updating SNR threshold to: " + snrThreshold);
            jsonObject = new JSONObject();
            setSelectedSNRThreshold(snrThreshold);
            jsonObject.put("success", true);
            return "json";
        } else if ("updateFadeMargin".equals(operation)) {
            log.info("execute", "Updating fade margin to: " + fadeMargin);
            jsonObject = new JSONObject();
            planToolConfig.setFadeMargin(fadeMargin);
            PlanToolAction.savePlanToolConfig(planToolConfig, getDomain());
            jsonObject.put("success", true);
            return "json";
        } else if ("updateChannelWidth".equals(operation)) {
            log.info("execute", "New channel width: " + channelWidth + ", model: " + hwModel);
            jsonObject = new JSONObject();
            planToolConfig.setChannelWidth(channelWidth);
            PlanToolAction.savePlanToolConfig(planToolConfig, getDomain());
            jsonObject.put("channels", new JSONArray(getChannelNaType(hwModel)));
            Map<Short, Short> ch1IndexMap = createChIndexMap(null, null);
            Map<Short, Short> ch2IndexMap = createChIndexMap(null, null);
            List<MapContainerNode> floors = BoMgmt.getLocationTracking().assignChannels(mapContainerNode,
                    planToolConfig, ch1IndexMap, ch2IndexMap);
            saveChannelAssignments(mapContainerNode, floors, getFloorCache(id), ch1IndexMap, ch2IndexMap, true);
            jsonObject.put("pageId", pageId);
            jsonObject.put("planned",
                    preparePlannedAPs(mapContainerNode, false, scale, null, ch1IndexMap, ch2IndexMap));
            return "json";
        } else if ("stopMapRefreshing".equals(operation)) {
            log.info("execute", "stop map refreshing for user:" + getUserContext().getUserName());
            if (null != HmBeTopoUtil.getPollingController()) {
                HmBeTopoUtil.getPollingController().removeContainer(request.getSession());
            }
            return null;
        } else if ("expandMapNode".equals(operation)) {
            log.info("execute", "operation:" + operation + ", map node:" + id + ", mapExpanded:" + mapExpanded);
            MapAlarmsCache<?> mapAlarmsCache = getMapAlarmsCache();
            mapAlarmsCache.setTreeNodeExpanded(id, mapExpanded);
            return "json";
        } else if ("createDownloadData".equals(operation)) {
            log.info("execute-createDownloadData",
                    "frequency: " + frequency + ", rssiThreshold: -" + rssiThreshold + ", rateThreshold: -"
                            + rateThreshold + ", channelWidth: -" + channelWidth + ", snrThreshold: "
                            + snrThreshold + ", layers: " + layers + ", gridChecked: " + gridChecked);
            jsonObject = new JSONObject();
            String pdfCreateFlagName = getDomain().getDomainName() + "_createingFlag";
            String pdfCreateSuccessFlagName = getDomain().getDomainName() + "_createSuccessFlag";
            String pdfCreateMapName = getDomain().getDomainName() + "_createingMapName";
            if (!"T".equals(MgrUtil.getSessionAttribute(pdfCreateFlagName))) {
                MgrUtil.setSessionAttribute(pdfCreateFlagName, "T");
                MgrUtil.setSessionAttribute(pdfCreateMapName, mapContainerNode.getMapName());
            } else {
                jsonObject.put("result", false);
                String msg = "The map of '" + MgrUtil.getSessionAttribute(pdfCreateMapName)
                        + "' is creating PDF report, please wait a moment.";
                jsonObject.put("message", msg);
                return "json";
            }

            MgrUtil.setSessionAttribute(pdfCreateSuccessFlagName, "F");

            TopoPdfReport report = new TopoPdfReport(this);

            String reportFile = "/tmp/report_" + getDomain().getDomainName() + ".pdf";
            boolean result = report.createPdf(mapContainerNode.getId(), reportFile, gridChecked, channelWidth,
                    acspId, planToolConfig);

            jsonObject.put("result", result);

            if (!result) {
                jsonObject.put("message", MgrUtil.getUserMessage("export.pdf.report.message"));
            } else {
                MgrUtil.setSessionAttribute(pdfCreateSuccessFlagName, "T");
            }
            MgrUtil.setSessionAttribute(pdfCreateFlagName, "F");
            return "json";
        } else if ("getPdfCreateFlag".equals(operation)) {
            String pdfCreateFlagName = getDomain().getDomainName() + "_createingFlag";
            String pdfCreateFlag = (String) MgrUtil.getSessionAttribute(pdfCreateFlagName);
            boolean flag = false;
            if ("T".equals(pdfCreateFlag)) {
                flag = true;
            }

            boolean success = false;
            String pdfCreateSuccessFlagName = getDomain().getDomainName() + "_createSuccessFlag";
            String pdfCreateSuccessFlag = (String) MgrUtil.getSessionAttribute(pdfCreateSuccessFlagName);
            if ("T".equals(pdfCreateSuccessFlag)) {
                success = true;
            }
            jsonObject = new JSONObject();
            jsonObject.put("pdfCreatingFlag", flag);
            jsonObject.put("pdfCreatSuccessFlag", success);
            return "json";
        } else if ("download".equals(operation)) {
            // check the file if under the allowed folder
            // StringUtils.isBlank(fileName) export pdf file
            boolean fileAllowed = true;
            if (!StringUtils.isBlank(fileName)) {
                fileAllowed = checkFileExistUnderDirectoryAllowed("/tmp/fdData/" + getDomain().getDomainName(),
                        fileName);
            }
            File file = new File(getInputPath());
            if (!fileAllowed || !file.exists()) {
                log.warn("No this file: " + getInputPath());
                addActionError(MgrUtil.getUserMessage("action.error.cannot.find.file"));
                return null;
            }
            return "download";
        } else if ("createPlanningData".equals(operation)) {
            jsonObject = new JSONObject();
            if (null != mapContainerNode.getId()) {
                final String time_suffix = "" + new Date().getTime();
                String fileName = mapContainerNode.getMapName() + "_" + time_suffix + ".xml";
                String destFilePath = getFolderDataFileRealPath(fileName);
                TopoXMLConvertor convertor = new TopoXMLConvertor(true);
                MapContainerNode container = (MapContainerNode) QueryUtil.findBoById(MapNode.class,
                        mapContainerNode.getId(), convertor.getLazyBoLoader());
                BooleanMsgPair result = convertor.convert2XML(container, destFilePath);

                String name = makeXMLBgImages2Tar(mapContainerNode.getMapName(), time_suffix, destFilePath,
                        convertor.getBackgroundImageNames());
                if (null != name) {
                    fileName = name;
                }

                jsonObject.put("succ", result.getValue());
                jsonObject.put("msg", result.getDesc());
                jsonObject.put("fileName", fileName);
            }
            return "json";
        } else if ("uploadPlanningData".equals(operation)) {
            // TODO limit the size of file
            jsonObject = new JSONObject();
            if (StringUtils.isBlank(uploadXmlFileName) || null == uploadXml) {
                jsonObject.put("msg", MgrUtil.getUserMessage("error.topo.import.xml.invalid.param"));
            } else {
                if (uploadXmlFileName.endsWith(".xml")) {
                    // normal
                    parseDataFromXML(uploadXml);
                } else {
                    // tarball
                    final String time_suffix = "" + new Date().getTime();
                    final String destPath = getTarFolderPath() + "/" + time_suffix;
                    if (new TarArchive().extract(uploadXml.getAbsolutePath(), destPath)) {
                        File folder = new File(destPath);
                        File[] files = folder.listFiles();

                        File[] imageFiles = null;
                        boolean parseSucc = false;

                        for (File file : files) {
                            if (file.isFile()) {
                                parseSucc = parseDataFromXML(file);
                            } else {
                                // copy map background images
                                imageFiles = file.listFiles();
                            }
                        }
                        if (parseSucc && null != imageFiles) {
                            String imagepath = BeTopoModuleUtil
                                    .getRealTopoBgImagePath(getDomain().getDomainName());
                            if (overrideBg) {
                                for (File imageFile : imageFiles) {
                                    FileUtils.copyFileToDirectory(imageFile, new File(imagepath));
                                }
                            } else {
                                for (File imageFile : imageFiles) {
                                    if (!new File(imagepath, imageFile.getName()).exists()) {
                                        FileUtils.copyFileToDirectory(imageFile, new File(imagepath));
                                    }
                                }

                            }
                        }
                    } else {
                        jsonObject.put("msg", "Unable to extra the file: " + uploadXmlFileName);
                    }
                }

            }
            return "json";
        } else if ("viewFloor".equals(operation)) {
            log.info_ln("View floor: " + id);
            setSelectedMapId(id);
            return mapPage(start);
        } else {
            return mapPage(start);
        }
    } catch (Exception e) {
        log.error("execute", "execute error. operation:" + operation, e);
        addActionError(MgrUtil.getUserMessage(e));
        return mapPage(start);
    }
}

From source file:net.pms.util.UMSUtils.java

/**
 * Creates a black background with the exact dimensions specified, then
 * centers the image on the background, preserving the aspect ratio.
 *
 * @param image//from w w w.j av a  2 s  . co m
 * @param width
 * @param height
 * @param outputBlank whether to return null or a black image when the
 *                    image parameter is null
 * @param renderer
 *
 * @return the scaled image
 */
public static byte[] scaleImage(byte[] image, int width, int height, boolean outputBlank,
        RendererConfiguration renderer) {
    ByteArrayInputStream in = null;
    if (image == null && !outputBlank) {
        return null;
    } else if (image != null) {
        in = new ByteArrayInputStream(image);
    }

    try {
        BufferedImage img;
        if (in != null) {
            img = ImageIO.read(in);
        } else {
            img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        if (renderer != null && renderer.isThumbnailPadding()) {
            Thumbnails.of(img).size(width, height)
                    .addFilter(new Canvas(width, height, Positions.CENTER, Color.BLACK)).outputFormat("JPEG")
                    .outputQuality(1.0f).toOutputStream(out);
        } else {
            Thumbnails.of(img).size(width, height).outputFormat("JPEG").outputQuality(1.0f).toOutputStream(out);
        }

        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.debug("Failed to resize image: {}", e.getMessage());
        LOGGER.trace("", e);
    }

    return null;
}

From source file:com.android.hierarchyviewerlib.device.DeviceBridge.java

private static boolean readLayer(DataInputStream in, PsdFile psd) {
    try {/*  ww  w . ja  va 2 s .co  m*/
        if (in.read() == 2) {
            return false;
        }
        String name = in.readUTF();
        boolean visible = in.read() == 1;
        int x = in.readInt();
        int y = in.readInt();
        int dataSize = in.readInt();

        byte[] data = new byte[dataSize];
        int read = 0;
        while (read < dataSize) {
            read += in.read(data, read, dataSize - read);
        }

        ByteArrayInputStream arrayIn = new ByteArrayInputStream(data);
        BufferedImage chunk = ImageIO.read(arrayIn);

        // Ensure the image is in the right format
        BufferedImage image = new BufferedImage(chunk.getWidth(), chunk.getHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        g.drawImage(chunk, null, 0, 0);
        g.dispose();

        psd.addLayer(name, image, new Point(x, y), visible);

        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.zacwolf.commons.email.Email.java

public static BufferedImage makeRoundedBanner(BufferedImage image, int cornerRadius) {
    int w = image.getWidth();
    int h = image.getHeight() + 10;
    BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = output.createGraphics();
    g2.setComposite(AlphaComposite.Src);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(Color.WHITE);//from w w  w  .ja v  a 2 s  .c o m
    g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
    g2.setComposite(AlphaComposite.SrcAtop);
    g2.drawImage(image, 0, 0, null);
    g2.setComposite(AlphaComposite.SrcOver);
    //               g2.setColor(new Color(153,153,153));//slight grey border
    //               g2.drawRoundRect(0, 0, w-1, h, cornerRadius, cornerRadius);
    g2.dispose();
    return output.getSubimage(0, 0, image.getWidth(), image.getHeight());
}