Example usage for java.awt Dimension getHeight

List of usage examples for java.awt Dimension getHeight

Introduction

In this page you can find the example usage for java.awt Dimension getHeight.

Prototype

public double getHeight() 

Source Link

Usage

From source file:es.darkhogg.hazelnutt.EditorFrame.java

private void actionExit() {
    logger.trace("Program exit requested...");

    boolean close = true;
    if (!checkRomModified()) {
        close = false;/*  w  w  w  .j  a v a 2s. c  o m*/
    }

    if (close && config.getBoolean("Hazelnutt.gui.confirmExit", true)) {
        int res = JOptionPane.showConfirmDialog(this, "Do you really want to close Hazelnutt?", "Confirm",
                JOptionPane.YES_NO_OPTION);
        close = (res == JOptionPane.OK_OPTION);
    }

    if (close) {
        logger.info("Saving configuration values...");

        boolean maximum = (getExtendedState() & JFrame.MAXIMIZED_BOTH) != 0;
        config.setProperty("Hazelnutt.gui.maximum", maximum);

        Point loc = getLocation();
        Dimension size = getSize();
        config.setProperty("Hazelnutt.gui.location.x", (int) loc.getX());
        config.setProperty("Hazelnutt.gui.location.y", (int) loc.getY());
        config.setProperty("Hazelnutt.gui.size.width", (int) size.getWidth());
        config.setProperty("Hazelnutt.gui.size.height", (int) size.getHeight());

        logger.debug("Saving the last opened directory: '" + fileChooser.getCurrentDirectory() + "'");
        config.setProperty("Hazelnutt.gui.lastDirectory", fileChooser.getCurrentDirectory());

        logger.debug("Saving the recently opened files");
        config.clearProperty("Hazelnutt.gui.recentFiles");
        for (String str : recentFiles) {
            config.addProperty("Hazelnutt.gui.recentFiles", str);
        }

        logger.trace("Closing program...");
        dispose();

        //memoryMonitor.cancel( true );
    }
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private void setJFXSize(Dimension size) {
    double width = size.getWidth();

    hiddenSidesPane.setPrefSize(width, size.getHeight());

    setTitledPaneWidth(sliderControlPane, width);
    setTitledPaneWidth(animations, width);
    setTitledPaneWidth(shimmerOptions, width);
    setTitledPaneWidth(neuralizer, width);
    setTitledPaneWidth(pictures, width);

    setShimmerSizes();/*from w  w  w .j  av  a2 s  .  c o m*/

    background.setDimension(size.getWidth(), size.getHeight());
}

From source file:org.kalypsodeegree_impl.graphics.displayelements.LabelFactory.java

/**
 * Determines positions on the given <tt>GM_Curve</tt> where a caption could be drawn. For each of this positons,
 * three candidates are produced; one on the line, one above of it and one below.
 * //ww  w . j av a2  s . c o m
 * @param curve
 * @param element
 * @param g
 * @param projection
 * @return ArrayList containing Arrays of Label-objects
 * @throws FilterEvaluationException
 */
private Label[] createCurveLabels(final Feature feature, final String caption, final GM_Curve curve,
        final Font font, final Color color, final LineMetrics metrics, final Dimension size)
        throws FilterEvaluationException, GM_Exception {
    final double radius = getLineRadius(feature);

    // determine the placement type and parameters from the TextSymbolizer
    final double perpendicularOffset;
    final PlacementType placementType;
    final double lineWidth;
    final int gap;

    final LinePlacement linePlacement = getLinePlacement();
    if (linePlacement != null) {
        placementType = linePlacement.getPlacementType(feature);
        perpendicularOffset = linePlacement.getPerpendicularOffset(feature);
        lineWidth = linePlacement.getLineWidth(feature);
        gap = linePlacement.getGap(feature);
    } else {
        placementType = PlacementType.absolute;
        perpendicularOffset = 0.0;
        lineWidth = 3.0;
        gap = 6;
    }

    // get screen coordinates of the line
    final int[][] pos = LabelUtils.calcScreenCoordinates(m_projection, curve);

    // get width & height of the caption
    final double labelWidth = size.getWidth() + 2 * radius;
    final double labelHeight = size.getHeight() + 2 * radius;

    // ideal distance from the line
    final double delta = labelHeight / 2.0 + lineWidth / 2.0;

    // walk along the linestring and "collect" possible placement positions
    final int w = (int) labelWidth;
    int lastX = pos[0][0];
    int lastY = pos[1][0];
    int boxStartX = lastX;
    int boxStartY = lastY;

    final List<Label> labels = new ArrayList<>(MAX_CURVE_LABELS_COUNT);
    final List<int[]> eCandidates = new ArrayList<>(MAX_CURVE_LABELS_COUNT);

    int i = 0;
    for (int kk = 0; kk < MAX_CURVE_LABELS_COUNT && kk < pos[2][0]; kk++) {
        final int screenX = pos[0][i];
        final int screenY = pos[1][i];

        // segment found where endpoint of box should be located?
        if (getDistance(boxStartX, boxStartY, screenX, screenY) >= w) {
            final int[] boxStart = new int[] { boxStartX, boxStartY };
            final int[] last = new int[] { lastX, lastY };
            final int[] current = new int[] { screenX, screenY };

            final int[] p = findPointWithDistance(boxStart, last, current, w);

            lastX = p[0];
            lastY = p[1];

            int boxEndX = p[0];
            int boxEndY = p[1];

            // does the linesegment run from right to left?
            if (boxEndX < boxStartX) {
                final int helpX = boxStartX;
                final int helpY = boxStartY;

                boxStartX = boxEndX;
                boxStartY = boxEndY;

                boxEndX = helpX;
                boxEndY = helpY;
            }

            final double rotation = getRotation(boxStartX, boxStartY, boxEndX, boxEndY);
            final double[] deviation = calcDeviation(new int[] { boxStartX, boxStartY },
                    new int[] { boxEndX, boxEndY }, eCandidates);

            final double[] displacement = calculateDisplacement(placementType, 0.0, perpendicularOffset, delta,
                    deviation);
            final double[] anchorPoint = DEFAULT_POINT_ANCHOR;

            final Label label = createLabel(caption, font, color, metrics, feature, (int) (boxStartX + radius),
                    boxStartY, size, rotation, anchorPoint, displacement);
            labels.add(label);

            boxStartX = lastX;
            boxStartY = lastY;

            eCandidates.clear();
        } else {
            eCandidates.add(new int[] { screenX, screenY });
            lastX = screenX;
            lastY = screenY;
            i++;
        }
    }

    // pick lists of boxes on the linestring
    // FIXME: strange: is the gap really the number of labels? shouldn't it be the minimum gap in pixels betwen to
    // labels?
    final List<Label> pick = new ArrayList<>(100);

    final int n = labels.size();
    for (int j = n / 2; j < n; j += gap + 1)
        pick.add(labels.get(j));

    for (int j = n / 2 - (gap + 1); j > 0; j -= gap + 1)
        pick.add(labels.get(j));

    return pick.toArray(new Label[pick.size()]);
}

From source file:ome.services.RenderingBean.java

@RolesAllowed("user")
public int[] getTileSize() {
    rwl.writeLock().lock();// w  w w.ja va2s . c o m

    try {
        errorIfInvalidState();
        Dimension tileSize = renderer.getTileSize();
        return new int[] { (int) tileSize.getWidth(), (int) tileSize.getHeight() };
    } finally {
        rwl.writeLock().unlock();
    }
}

From source file:display.containers.FileManager.java

public Container getPane() {
    //if (gui==null) {

    fileSystemView = FileSystemView.getFileSystemView();
    desktop = Desktop.getDesktop();

    JPanel detailView = new JPanel(new BorderLayout(3, 3));
    //fileTableModel = new FileTableModel();

    table = new JTable();
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    table.setAutoCreateRowSorter(true);/*ww  w.ja v a  2 s  .  co  m*/
    table.setShowVerticalLines(false);
    table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                Point p = e.getPoint();
                int row = table.convertRowIndexToModel(table.rowAtPoint(p));
                int column = table.convertColumnIndexToModel(table.columnAtPoint(p));
                if (row >= 0 && column >= 0) {
                    mouseDblClicked(row, column);
                }
            }
        }
    });
    table.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            if (KeyEvent.VK_DELETE == arg0.getKeyCode()) {
                if (mode != 2) {
                    parentFrame.setLock(true);
                    parentFrame.getProgressBarPanel().setVisible(true);
                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                deleteSelectedFiles();
                            } catch (IOException e) {
                                JOptionPane.showMessageDialog(parentFrame, "Error during the deletion.",
                                        "Deletion error", JOptionPane.ERROR_MESSAGE);
                                WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.", e);
                            } finally {
                                parentFrame.setLock(false);
                                refresh();
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        }
                    });
                    t.start();

                } else {
                    if (UserProfile.CURRENT_USER.getLevel() == 3) {
                        parentFrame.setLock(true);
                        parentFrame.getProgressBarPanel().setVisible(true);
                        Thread delThread = new Thread(new Runnable() {

                            @Override
                            public void run() {
                                int[] rows = table.getSelectedRows();
                                int[] columns = table.getSelectedColumns();
                                for (int i = 0; i < rows.length; i++) {
                                    if (!continueAction) {
                                        continueAction = true;
                                        return;
                                    }
                                    int row = table.convertRowIndexToModel(rows[i]);
                                    try {
                                        deleteServerFile(row);
                                    } catch (Exception e) {
                                        WindowManager.mwLogger.log(Level.SEVERE, "Error during the deletion.",
                                                e);
                                    }
                                }
                                refresh();
                                parentFrame.setLock(false);
                                parentFrame.getProgressBarPanel().setVisible(false);
                            }
                        });
                        delThread.start();

                    }
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });
    table.getSelectionModel().addListSelectionListener(listSelectionListener);
    JScrollPane tableScroll = new JScrollPane(table);
    Dimension d = tableScroll.getPreferredSize();
    tableScroll.setPreferredSize(new Dimension((int) d.getWidth(), (int) d.getHeight() / 2));
    detailView.add(tableScroll, BorderLayout.CENTER);

    // the File tree
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    treeModel = new DefaultTreeModel(root);
    table.getRowSorter().addRowSorterListener(new RowSorterListener() {

        @Override
        public void sorterChanged(RowSorterEvent e) {
            ((FileTableModel) table.getModel()).fireTableDataChanged();
        }
    });

    // show the file system roots.
    File[] roots = fileSystemView.getRoots();
    for (File fileSystemRoot : roots) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
        root.add(node);
        //showChildren(node);
        //
        File[] files = fileSystemView.getFiles(fileSystemRoot, true);
        for (File file : files) {
            if (file.isDirectory()) {
                node.add(new DefaultMutableTreeNode(file));
            }
        }
        //
    }
    JScrollPane treeScroll = new JScrollPane();

    Dimension preferredSize = treeScroll.getPreferredSize();
    Dimension widePreferred = new Dimension(200, (int) preferredSize.getHeight());
    treeScroll.setPreferredSize(widePreferred);

    JPanel fileView = new JPanel(new BorderLayout(3, 3));

    detailView.add(fileView, BorderLayout.SOUTH);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroll, detailView);

    JPanel simpleOutput = new JPanel(new BorderLayout(3, 3));
    progressBar = new JProgressBar();
    simpleOutput.add(progressBar, BorderLayout.EAST);
    progressBar.setVisible(false);
    showChildren(getCurrentDir().toPath());
    //table.setDragEnabled(true);
    table.setColumnSelectionAllowed(false);

    // Menu popup
    Pmenu = new JPopupMenu();
    changeProjectitem = new JMenuItem("Reassign");
    renameProjectitem = new JMenuItem("Rename");
    twitem = new JMenuItem("To workspace");
    tlitem = new JMenuItem("To local");
    processitem = new JMenuItem("Select for process");
    switch (mode) {
    case 0:
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnlocalTowork().doClick();
            }
        });
        break;
    case 1:
        Pmenu.add(tlitem);
        Pmenu.add(processitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtnWorkTolocal().doClick();
            }
        });
        processitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        // Recupere les lignes selectionnees
                        int[] indices = table.getSelectedRows();
                        // On recupere les fichiers correspondants
                        ArrayList<File> files = new ArrayList<File>();
                        for (int i = 0; i < indices.length; i++) {
                            int row = table.convertRowIndexToModel(indices[i]);
                            File fi = ((FileTableModel) table.getModel()).getFile(row);
                            if (fi.isDirectory())
                                files.add(fi);
                        }
                        ImageProcessingFrame imf = new ImageProcessingFrame(files);
                    }
                });

            }
        });
        break;
    case 2:
        if (UserProfile.CURRENT_USER.getLevel() == 3) {
            Pmenu.add(changeProjectitem);
            Pmenu.add(renameProjectitem);
        }
        Pmenu.add(twitem);
        twitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToWorkspace().doClick();
            }
        });
        Pmenu.add(tlitem);
        tlitem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                parentFrame.getBtndistToLocal().doClick();
            }
        });
        break;
    }
    changeProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));

            ReassignProjectPanel reas = new ReassignProjectPanel(from.toPath()); // mode creation de liens
            Popup popup = PopupFactory.getSharedInstance().getPopup(WindowManager.MAINWINDOW, reas,
                    (int) WindowManager.MAINWINDOW.getX() + 200, (int) WindowManager.MAINWINDOW.getY() + 150);
            reas.setPopupWindow(popup);
            popup.show();
            table.setEnabled(true);
        }
    });
    renameProjectitem.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            table.setEnabled(false);
            final File from = ((FileTableModel) table.getModel())
                    .getFile(table.convertRowIndexToModel(table.getSelectedRows()[0]));
            JDialog.setDefaultLookAndFeelDecorated(true);
            String s = (String) JOptionPane.showInputDialog(WindowManager.MAINWINDOW, "New project name ?",
                    "Rename project", JOptionPane.PLAIN_MESSAGE, null, null, from.getName());

            //If a string was returned, say so.
            if ((s != null) && (s.length() > 0)) {
                ProjectDAO pdao = new MySQLProjectDAO();
                if (new File(from.getParent() + File.separator + s).exists()) {
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            JDialog.setDefaultLookAndFeelDecorated(true);
                            JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                    "Couldn't rename " + from.getName()
                                            + " (A file with this filename already exists)",
                                    "Renaming error", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                    WindowManager.mwLogger.log(Level.SEVERE,
                            "Error during file project renaming (" + from.getName() + "). [Duplication error]");
                } else {
                    try {
                        boolean succeed = pdao.renameProject(from.getName(), s);
                        if (!succeed) {
                            SwingUtilities.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    JDialog.setDefaultLookAndFeelDecorated(true);
                                    JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                            "Couldn't rename " + from.getName()
                                                    + " (no project with this name)",
                                            "Renaming error", JOptionPane.ERROR_MESSAGE);
                                }
                            });
                        } else {
                            from.renameTo(new File(from.getParent() + File.separator + s));
                            // on renomme le repertoire nifti ou dicom correspondant si il existe
                            switch (from.getParentFile().getName()) {
                            case ServerInfo.NRI_ANALYSE_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_ANALYSE_NAME,
                                        ServerInfo.NRI_DICOM_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)),
                                                Paths.get(from.getParent().replaceAll(
                                                        ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)
                                                        + File.separator + s));
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_ANALYSE_NAME, ServerInfo.NRI_DICOM_NAME)+File.separator+s));
                                break;
                            case ServerInfo.NRI_DICOM_NAME:
                                if (new File(from.getAbsolutePath().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                        ServerInfo.NRI_ANALYSE_NAME)).exists())
                                    try {
                                        Files.move(Paths.get(from.getAbsolutePath().replaceAll(
                                                ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)),
                                                Paths.get(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME,
                                                        ServerInfo.NRI_ANALYSE_NAME) + File.separator + s));
                                    } catch (IOException e) {
                                        SwingUtilities.invokeLater(new Runnable() {

                                            @Override
                                            public void run() {
                                                JDialog.setDefaultLookAndFeelDecorated(true);
                                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                                        "Couldn't rename " + from.getName()
                                                                + " (error with file system)",
                                                        "Renaming error", JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                        e.printStackTrace();
                                        WindowManager.mwLogger.log(Level.SEVERE,
                                                "Error during file project renaming (" + from.getName() + ")",
                                                e);
                                    } //from.renameTo(new File(from.getParent().replaceAll(ServerInfo.NRI_DICOM_NAME, ServerInfo.NRI_ANALYSE_NAME)+File.separator+s));
                                break;
                            }
                            refresh();
                        }
                    } catch (final SQLException e) {
                        WindowManager.mwLogger.log(Level.SEVERE, "Error during SQL project renaming", e);
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                JDialog.setDefaultLookAndFeelDecorated(true);
                                JOptionPane.showMessageDialog(WindowManager.MAINWINDOW,
                                        "Exception : " + e.toString(), "Openning error",
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        });
                    }
                }
            }
            table.setEnabled(true);
        }
    });
    table.addMouseListener(new MouseListener() {

        public void mouseClicked(MouseEvent me) {

        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent me) {
            if (me.getButton() == 3 && table.getSelectedRowCount() > 0) {
                int row = table.convertRowIndexToModel(table.rowAtPoint(me.getPoint()));
                changeProjectitem.setVisible(isPatient(((FileTableModel) table.getModel()).getFile(row)));
                renameProjectitem.setVisible(isProject(((FileTableModel) table.getModel()).getFile(row)));
                Pmenu.show(me.getComponent(), me.getX(), me.getY());
            }
        }
    });
    //

    //}
    return tableScroll;
}

From source file:mondrian.gui.Workbench.java

private void tileMenuItemActionPerformed(ActionEvent evt) {
    final Dimension dsize = desktopPane.getSize();
    final int desktopW = (int) dsize.getWidth();
    final int desktopH = (int) dsize.getHeight();
    final int darea = desktopW * desktopH;
    final double eacharea = darea / (schemaWindowMap.size() + mdxWindows.size() + jdbcWindows.size());
    final int wh = (int) Math.sqrt(eacharea);

    try {//from   ww  w. j  av  a  2 s. c  o  m
        int x = 0, y = 0;
        for (JInternalFrame sf : getAllFrames()) {
            if (sf != null && !sf.isIcon()) {
                sf.setMaximum(false);
                sf.moveToFront();
                if (x >= desktopW || (desktopW - x) * wh < eacharea / 2) {
                    // move to next row of windows
                    y += wh;
                    x = 0;
                }
                int sfwidth = ((x + wh) < desktopW ? wh : desktopW - x);
                int sfheight = ((y + wh) < desktopH ? wh : desktopH - y);
                sf.setBounds(x, y, sfwidth, sfheight);
                x += sfwidth;
            }
        }
    } catch (Exception ex) {
        LOGGER.error("tileMenuItemActionPerformed", ex);
        // do nothing
    }
}

From source file:org.mwc.cmap.xyplot.views.XYPlotView.java

private void rtfToClipboard(final String fName, final Dimension dim) {
    // Issue #520 - Copy WMF embedded in RTF
    ByteArrayOutputStream os = null;
    DataInputStream dis = null;//from   w  ww . ja v a  2  s.  co m
    try {
        os = new ByteArrayOutputStream();
        RTFWriter writer = new RTFWriter(os);
        File file = new File(fName);
        byte[] data = new byte[(int) file.length()];
        dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(data);
        writer.writeHeader();
        writer.writeEmfPicture(data, dim.getWidth(), dim.getHeight());
        writer.writeTail();

        RTFTransfer rtfTransfer = RTFTransfer.getInstance();
        Clipboard clipboard = new Clipboard(Display.getDefault());
        Object[] rtfData = new Object[] { os.toString() };
        clipboard.setContents(rtfData, new Transfer[] { rtfTransfer });
    } catch (final Exception e1) {
        IStatus status = new Status(IStatus.ERROR, PlotViewerPlugin.PLUGIN_ID, e1.getLocalizedMessage(), e1);
        XYPlotPlugin.getDefault().getLog().log(status);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e1) {
                // ignore
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e1) {
                // ignore
            }
        }
    }

}

From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java

/**
 * This method loads the granules which overlap the requested
 * {@link GeneralEnvelope} using the provided values for alpha and input
 * ROI./* w  w  w .j  a  v  a  2  s  . c  o m*/
 * @return
 * @throws DataSourceException
 */
private RenderedImage prepareResponse() throws DataSourceException {

    try {

        //
        // prepare the params for executing a mosaic operation.
        //
        // It might important to set the mosaic type to blend otherwise
        // sometimes strange results jump in.

        // select the relevant overview, notice that at this time we have
        // relaxed a bit the requirement to have the same exact resolution
        // for all the overviews, but still we do not allow for reading the
        // various grid to world transform directly from the input files,
        // therefore we are assuming that each granuleDescriptor has a scale and
        // translate only grid to world that can be deduced from its base
        // level dimension and envelope. The grid to world transforms for
        // the other levels can be computed accordingly knowing the scale
        // factors.
        if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null
                && !request.isHeterogeneousGranules())
            imageChoice = ReadParamsController.setReadParams(request.getRequestedResolution(),
                    request.getOverviewPolicy(), request.getDecimationPolicy(), baseReadParameters,
                    request.rasterManager, request.rasterManager.overviewsController); // use general overviews controller
        else
            imageChoice = 0;
        assert imageChoice >= 0;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(new StringBuffer("Loading level ").append(imageChoice)
                    .append(" with subsampling factors ").append(baseReadParameters.getSourceXSubsampling())
                    .append(" ").append(baseReadParameters.getSourceYSubsampling()).toString());

        // ok we got something to return, let's load records from the index
        final BoundingBox cropBBOX = request.getCropBBox();
        if (cropBBOX != null)
            mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
        else
            mosaicBBox = new ReferencedEnvelope(coverageEnvelope);

        //compute final world to grid
        // base grid to world for the center of pixels
        final AffineTransform g2w;
        final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels.get(0);
        final OverviewLevel selectedLevel = rasterManager.overviewsController.resolutionsLevels
                .get(imageChoice);
        final double resX = baseLevel.resolutionX;
        final double resY = baseLevel.resolutionY;
        final double[] requestRes = request.getRequestedResolution();

        g2w = new AffineTransform((AffineTransform) baseGridToWorld);
        g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if ((requestRes[0] < resX || requestRes[1] < resY)) {
            // Using the best available resolution
            oversampledRequest = true;
        } else {

            // SG going back to working on a per level basis to do the composition
            // g2w = new AffineTransform(request.getRequestedGridToWorld());
            g2w.concatenate(
                    AffineTransform.getScaleInstance(selectedLevel.scaleFactor, selectedLevel.scaleFactor));
            g2w.concatenate(AffineTransform.getScaleInstance(baseReadParameters.getSourceXSubsampling(),
                    baseReadParameters.getSourceYSubsampling()));
        }

        // move it to the corner
        finalGridToWorldCorner = new AffineTransform2D(g2w);
        finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
        final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
        rasterBounds = tempRasterBounds.toRectangle2D().getBounds();

        //          SG using the above may lead to problems since the reason is that  may be a little (1 px) bigger
        //          than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
        //          Javadoc)
        //         rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
        if (rasterBounds.width == 0)
            rasterBounds.width++;
        if (rasterBounds.height == 0)
            rasterBounds.height++;
        if (oversampledRequest)
            rasterBounds.grow(2, 2);

        // make sure we do not go beyond the raster dimensions for this layer
        final GeneralEnvelope levelRasterArea_ = CRS.transform(finalWorldToGridCorner,
                rasterManager.spatialDomainManager.coverageBBox);
        final GridEnvelope2D levelRasterArea = new GridEnvelope2D(new Envelope2D(levelRasterArea_),
                PixelInCell.CELL_CORNER);
        XRectangle2D.intersect(levelRasterArea, rasterBounds, rasterBounds);

        // create the index visitor and visit the feature
        final MosaicBuilder visitor = new MosaicBuilder(request);
        final List times = request.getRequestedTimes();
        final List elevations = request.getElevation();
        final Map<String, List> additionalDomains = request.getRequestedAdditionalDomains();
        final Filter filter = request.getFilter();
        final boolean hasTime = (times != null && times.size() > 0);
        final boolean hasElevation = (elevations != null && elevations.size() > 0);
        final boolean hasAdditionalDomains = additionalDomains.size() > 0;
        final boolean hasFilter = filter != null && !Filter.INCLUDE.equals(filter);

        // create query
        final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
        Query query = null;
        Filter bbox = null;
        if (type != null) {
            query = new Query(rasterManager.granuleCatalog.getType().getTypeName());
            bbox = FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(
                    FeatureUtilities.DEFAULT_FILTER_FACTORY
                            .property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),
                    mosaicBBox);
            query.setFilter(bbox);
        } else {
            throw new IllegalStateException("GranuleCatalog feature type was null!!!");
        }

        // prepare eventual filter for filtering granules
        // handle elevation indexing first since we then combine this with the max in case we are asking for current in time
        if (hasElevation) {

            final Filter elevationF = rasterManager.parent.elevationDomainManager
                    .createFilter(ImageMosaicReader.ELEVATION_DOMAIN, elevations);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), elevationF));
        }

        // handle generic filter since we then combine this with the max in case we are asking for current in time
        if (hasFilter) {
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), filter));
        }

        // fuse time query with the bbox query
        if (hasTime) {
            final Filter timeFilter = this.rasterManager.parent.timeDomainManager
                    .createFilter(ImageMosaicReader.TIME_DOMAIN, times);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), timeFilter));
        }

        if (hasAdditionalDomains) {
            final List<Filter> additionalFilter = new ArrayList<Filter>();
            for (Entry<String, List> entry : additionalDomains.entrySet()) {

                // build a filter for each dimension
                final String domainName = entry.getKey() + DomainDescriptor.DOMAIN_SUFFIX;
                additionalFilter.add(
                        rasterManager.parent.domainsManager.createFilter(domainName, (List) entry.getValue()));

            }
            // merge with existing ones
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(),
                    FeatureUtilities.DEFAULT_FILTER_FACTORY.and(additionalFilter)));
        }

        //
        // handle secondary query parameters
        //

        // max number of elements
        if (request.getMaximumNumberOfGranules() > 0) {
            query.setMaxFeatures(request.getMaximumNumberOfGranules());
        }

        // sort by clause
        final String sortByClause = request.getSortClause();
        if (sortByClause != null && sortByClause.length() > 0) {
            final String[] elements = sortByClause.split(",");
            if (elements != null && elements.length > 0) {
                final List<SortBy> clauses = new ArrayList<SortBy>(elements.length);
                for (String element : elements) {
                    // check
                    if (element == null || element.length() <= 0) {
                        continue;// next, please!
                    }
                    try {
                        // which clause?
                        // ASCENDING
                        element = element.trim();
                        if (element.endsWith(Utils.ASCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.ASCENDING));
                        } else
                        // DESCENDING
                        if (element.contains(Utils.DESCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.DESCENDING));
                        }
                        //                        if(element.startsWith(Utils.ASCENDING_ORDER_IDENTIFIER)){
                        //                           String attribute=element.substring(Utils.ASCENDING_ORDER_IDENTIFIER.length()+1);
                        //                           attribute=attribute.substring(0, attribute.length()-1);
                        //                           clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.ASCENDING));
                        //                        } else 
                        //                           // DESCENDING
                        //                           if(element.startsWith(Utils.DESCENDING_ORDER_IDENTIFIER)){
                        //                               String attribute=element.substring(Utils.DESCENDING_ORDER_IDENTIFIER.length()+1);
                        //                               attribute=attribute.substring(0, attribute.length()-1);
                        //                               clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.DESCENDING));
                        //                        } else {
                        else {
                            if (LOGGER.isLoggable(Level.FINE)) {
                                LOGGER.fine("Ignoring sort clause :" + element);
                            }
                        }
                    } catch (Exception e) {
                        if (LOGGER.isLoggable(Level.INFO)) {
                            LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
                        }
                    }
                }

                // assign to query if sorting is supported!
                final SortBy[] sb = clauses.toArray(new SortBy[] {});
                if (rasterManager.granuleCatalog.getQueryCapabilities().supportsSorting(sb)) {
                    query.setSortBy(sb);
                }
            }
        }

        // collect granules
        rasterManager.getGranules(query, visitor);

        // get those granules
        visitor.produce();

        //
        // Did we actually load anything?? Notice that it might happen that
        // either we have holes inside the definition area for the mosaic
        // or we had some problem with missing tiles, therefore it might
        // happen that for some bboxes we don't have anything to load.
        //
        RenderedImage returnValue = null;
        if (visitor.granulesNumber >= 1) {

            //
            // Create the mosaic image by doing a crop if necessary and also
            // managing the transparent color if applicable. Be aware that
            // management of the transparent color involves removing
            // transparency information from the input images.
            //          
            returnValue = buildMosaic(visitor);
            if (returnValue != null) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Loaded bbox " + mosaicBBox.toString() + " while crop bbox "
                            + request.getCropBBox().toString());
                return returnValue;
            }

        }

        // Redo the query without filter to check whether we got no granules due
        // to a filter. In that case we need to return null
        if (hasTime || hasElevation || hasFilter || hasAdditionalDomains) {
            query.setFilter(bbox);
            rasterManager.getGranules(query, visitor);
            // get those granules
            visitor.produce();
            if (visitor.granulesNumber >= 1) {
                // It means the previous lack of granule was due to a filter excluding all the results. Then we return null
                return null;
            }
        }

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Creating constant image for area with no data");

        // if we get here that means that we do not have anything to load
        // but still we are inside the definition area for the mosaic,
        // therefore we create a fake coverage using the background values,
        // if provided (defaulting to 0), as well as the compute raster
        // bounds, envelope and grid to world.

        final Number[] values = ImageUtilities.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
        // create a constant image with a proper layout
        RenderedImage finalImage = ConstantDescriptor.create(Float.valueOf(rasterBounds.width),
                Float.valueOf(rasterBounds.height), values, null);
        if (rasterBounds.x != 0 || rasterBounds.y != 0) {
            finalImage = TranslateDescriptor.create(finalImage, Float.valueOf(rasterBounds.x),
                    Float.valueOf(rasterBounds.y), Interpolation.getInstance(Interpolation.INTERP_NEAREST),
                    null);
        }
        if (rasterManager.defaultCM != null) {
            final ImageLayout2 il = new ImageLayout2();
            il.setColorModel(rasterManager.defaultCM);
            Dimension tileSize = request.getTileDimensions();
            if (tileSize == null) {
                tileSize = JAI.getDefaultTileSize();
            }
            il.setSampleModel(
                    rasterManager.defaultCM.createCompatibleSampleModel(tileSize.width, tileSize.height));
            il.setTileGridXOffset(0).setTileGridYOffset(0).setTileWidth((int) tileSize.getWidth())
                    .setTileHeight((int) tileSize.getHeight());
            return FormatDescriptor.create(finalImage, Integer.valueOf(il.getSampleModel(null).getDataType()),
                    new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il));
        }
        return finalImage;

    } catch (Exception e) {
        throw new DataSourceException("Unable to create this mosaic", e);
    }
}

From source file:org.processmining.analysis.performance.dottedchart.ui.DottedChartPanel.java

/**
 * adjusts the viewable are of the log (zoom)
 *//*from  w ww .java2 s.  c o  m*/
public void setViewportZoomIn() {
    Dimension d = dca.getViewportSize();
    int width = Math.abs(p1.x - p2.x);
    int height = Math.abs(p1.y - p2.y);

    int value = (int) (Math.log10(
            (double) this.getWidth() * (d.getWidth() / width) / (double) dca.getViewportSize().getWidth())
            * 1000.0);
    if (value > 3000)
        return;
    value = (int) (Math.log10(
            (double) this.getHeight() * (d.getHeight() / height) / (double) dca.getViewportSize().getHeight())
            * 1000.0);
    if (value > 3000)
        return;

    updWidth = (int) ((double) this.getWidth() * (d.getWidth() / width));
    updHight = (int) ((double) this.getHeight() * (d.getHeight() / height));
    Dimension dim = new Dimension(updWidth, updHight);
    int pos_x = Math.min(p1.x, p2.x);
    int pos_y = Math.min(p1.y, p2.y);

    Point p = new Point((int) (pos_x * d.getWidth() / width), (int) (pos_y * d.getHeight() / height));
    this.setPreferredSize(dim);
    updateMilli2pixelsRatio();
    this.revalidate();
    dca.setScrollBarPosition(p);
    p1 = null;
    p2 = null;
    adjustSlideBar();
}

From source file:org.processmining.analysis.performance.dottedchart.ui.DottedChartPanel.java

/**
 * adjusts the viewable are of the log (zoom)
 *//*from  www . jav a2 s . com*/
public Point zoomInViewPort() {
    if (p1 == null || p2 == null)
        return null;
    Dimension d = dca.getViewportSize();
    int width = Math.abs(p1.x - p2.x);
    int height = Math.abs(p1.y - p2.y);

    int value = (int) (Math.log10(
            (double) this.getWidth() * (d.getWidth() / width) / (double) dca.getViewportSize().getWidth())
            * 1000.0);
    if (value > 3000)
        return null;
    value = (int) (Math.log10(
            (double) this.getHeight() * (d.getHeight() / height) / (double) dca.getViewportSize().getHeight())
            * 1000.0);
    if (value > 3000)
        return null;

    updWidth = (int) ((double) this.getWidth() * (d.getWidth() / width));
    updHight = (int) ((double) this.getHeight() * (d.getHeight() / height));

    Dimension dim = new Dimension(updWidth, updHight);
    int pos_x = Math.min(p1.x, p2.x);
    int pos_y = Math.min(p1.y, p2.y);

    this.setPreferredSize(dim);
    updateMilli2pixelsRatio();
    this.revalidate();
    p1 = null;
    p2 = null;
    adjustSlideBar();
    return new Point((int) (pos_x * d.getWidth() / width), (int) (pos_y * d.getHeight() / height));
}