Example usage for java.awt Container Container

List of usage examples for java.awt Container Container

Introduction

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

Prototype

public Container() 

Source Link

Document

Constructs a new Container.

Usage

From source file:econtroller.gui.ControllerGUI.java

private void createNrInstanceSection() {
    maxNrInstancesLbl = new JLabel("# of Instances");
    minInstanceText = new IntegerTextField("2");
    maxInstanceText = new IntegerTextField("8");
    instanceLayout = new Container();
    instanceLayout.setLayout(new GridLayout(1, 2));
    instanceLayout.add(minInstanceText);
    instanceLayout.add(maxInstanceText);
}

From source file:econtroller.gui.ControllerGUI.java

private void createSamplingAndNodeOrderingSection() {
    orderedEnabled = new JCheckBox("Ordering enabled");
    orderedEnabled.setSelected(true);/*from w  ww.  j  ava 2  s .com*/
    samplingOrderLbl = new JLabel("Sampling & Ordering (s)");
    samplingText = new IntegerTextField("10");
    orderingText = new IntegerTextField("90");
    sampleOrderLayout = new Container();
    sampleOrderLayout.setLayout(new GridLayout(1, 2));
    sampleOrderLayout.add(samplingText);
    sampleOrderLayout.add(orderingText);
}

From source file:com.pingtel.sipviewer.SIPViewerFrame.java

protected void layoutComponents() {
    Container rootPane = this.getContentPane();

    // this is the vertical container to which all the
    // windows are added
    Container verticalContainer = new Container();
    verticalContainer.setLayout(new GridBagLayout());

    m_scrollPaneTimeIndex.setMinimumSize(new Dimension(150, 50));
    m_scrollPaneTimeIndexSecond.setMinimumSize(new Dimension(150, 50));

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 0;// w  ww . j av  a2s .co  m
    gbc.weighty = 1.0;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridwidth = 1;

    verticalContainer.add(m_scrollPaneTimeIndex, gbc);
    gbc.gridx = 1;
    verticalContainer.add(m_scrollPane, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    verticalContainer.add(m_scrollPaneTimeIndexSecond, gbc);

    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.gridx = 1;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    verticalContainer.add(m_scrollPaneSecond, gbc);

    gbc.weightx = 1.0;
    gbc.weighty = 0.0;
    gbc.gridwidth = 2;
    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    verticalContainer.add(m_infoPanel, gbc);

    rootPane.add(verticalContainer, BorderLayout.CENTER);
}

From source file:snapshot.java

public static Object respond(final RequestHeader header, serverObjects post, final serverSwitch env) {
    final Switchboard sb = (Switchboard) env;

    final serverObjects defaultResponse = new serverObjects();

    final boolean authenticated = sb.adminAuthenticated(header) >= 2;
    final String ext = header.get(HeaderFramework.CONNECTION_PROP_EXT, "");

    if (ext.isEmpty()) {
        throw new TemplateProcessingException(
                "Missing extension. Try with rss, xml, json, pdf, png or jpg." + ext,
                HttpStatus.SC_BAD_REQUEST);
    }/* ww  w  .j  a va  2  s. c o  m*/

    if (ext.equals("rss")) {
        // create a report about the content of the snapshot directory
        if (!authenticated) {
            defaultResponse.authenticationRequired();
            return defaultResponse;
        }
        int maxcount = post == null ? 10 : post.getInt("maxcount", 10);
        int depthx = post == null ? -1 : post.getInt("depth", -1);
        Integer depth = depthx == -1 ? null : depthx;
        String orderx = post == null ? "ANY" : post.get("order", "ANY");
        Snapshots.Order order = Snapshots.Order.valueOf(orderx);
        String statex = post == null ? Transactions.State.INVENTORY.name()
                : post.get("state", Transactions.State.INVENTORY.name());
        Transactions.State state = Transactions.State.valueOf(statex);
        String host = post == null ? null : post.get("host");
        Map<String, Revisions> iddate = Transactions.select(host, depth, order, maxcount, state);
        // now select the URL from the index for these ids in iddate and make an RSS feed
        RSSFeed rssfeed = new RSSFeed(Integer.MAX_VALUE);
        rssfeed.setChannel(new RSSMessage("Snapshot list for host = " + host + ", depth = " + depth
                + ", order = " + order + ", maxcount = " + maxcount, "", ""));
        for (Map.Entry<String, Revisions> e : iddate.entrySet()) {
            try {
                DigestURL u = e.getValue().url == null ? sb.index.fulltext().getURL(e.getKey())
                        : new DigestURL(e.getValue().url);
                if (u == null)
                    continue;
                RSSMessage message = new RSSMessage(u.toNormalform(true), "", u, e.getKey());
                message.setPubDate(e.getValue().dates[0]);
                rssfeed.addMessage(message);
            } catch (IOException ee) {
                ConcurrentLog.logException(ee);
            }
        }
        byte[] rssBinary = UTF8.getBytes(rssfeed.toString());
        return new ByteArrayInputStream(rssBinary);
    }

    // for the following methods we (mostly) need an url or a url hash
    if (post == null)
        post = new serverObjects();
    final boolean xml = ext.equals("xml");
    final boolean pdf = ext.equals("pdf");
    if (pdf && !authenticated) {
        defaultResponse.authenticationRequired();
        return defaultResponse;
    }
    final boolean pngjpg = ext.equals("png") || ext.equals(DEFAULT_EXT);
    String urlhash = post.get("urlhash", "");
    String url = post.get("url", "");
    DigestURL durl = null;
    if (urlhash.length() == 0 && url.length() > 0) {
        try {
            durl = new DigestURL(url);
            urlhash = ASCII.String(durl.hash());
        } catch (MalformedURLException e) {
        }
    }
    if (durl == null && urlhash.length() > 0) {
        try {
            durl = sb.index.fulltext().getURL(urlhash);
        } catch (IOException e) {
            ConcurrentLog.logException(e);
        }
    }

    if (ext.equals("json")) {
        // command interface: view and change a transaction state, get metadata about transactions in the past
        String command = post.get("command", "metadata");
        String statename = post.get("state");
        JSONObject result = new JSONObject();
        try {
            if (command.equals("status")) {
                // return a status of the transaction archive
                JSONObject sizes = new JSONObject();
                for (Map.Entry<String, Integer> state : Transactions.sizes().entrySet())
                    sizes.put(state.getKey(), state.getValue());
                result.put("size", sizes);
            } else if (command.equals("list")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                // return a status of the transaction archive
                String host = post.get("host");
                String depth = post.get("depth");
                int depthi = depth == null ? -1 : Integer.parseInt(depth);
                for (Transactions.State state : statename == null
                        ? new Transactions.State[] { Transactions.State.INVENTORY, Transactions.State.ARCHIVE }
                        : new Transactions.State[] { Transactions.State.valueOf(statename) }) {
                    if (host == null) {
                        JSONObject hostCountInventory = new JSONObject();
                        for (String h : Transactions.listHosts(state)) {
                            int size = Transactions.listIDsSize(h, depthi, state);
                            if (size > 0)
                                hostCountInventory.put(h, size);
                        }
                        result.put("count." + state.name(), hostCountInventory);
                    } else {
                        TreeMap<Integer, Collection<Revisions>> ids = Transactions.listIDs(host, depthi, state);
                        if (ids == null) {
                            result.put("result", "fail");
                            result.put("comment", "no entries for host " + host + " found");
                        } else {
                            for (Map.Entry<Integer, Collection<Revisions>> entry : ids.entrySet()) {
                                for (Revisions r : entry.getValue()) {
                                    try {
                                        JSONObject metadata = new JSONObject();
                                        DigestURL u = r.url != null ? new DigestURL(r.url)
                                                : sb.index.fulltext().getURL(r.urlhash);
                                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                                        metadata.put("dates", r.dates);
                                        assert r.depth == entry.getKey().intValue();
                                        metadata.put("depth", entry.getKey().intValue());
                                        result.put(r.urlhash, metadata);
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (command.equals("commit")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.commit(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("rollback")) {
                if (!authenticated) {
                    defaultResponse.authenticationRequired();
                    return defaultResponse;
                }
                Revisions r = Transactions.rollback(urlhash);
                if (r != null) {
                    result.put("result", "success");
                    result.put("depth", r.depth);
                    result.put("url", r.url);
                    result.put("dates", r.dates);
                } else {
                    result.put("result", "fail");
                }
                result.put("urlhash", urlhash);
            } else if (command.equals("metadata")) {
                try {
                    Revisions r;
                    Transactions.State state = statename == null || statename.length() == 0 ? null
                            : Transactions.State.valueOf(statename);
                    if (state == null) {
                        r = Transactions.getRevisions(Transactions.State.INVENTORY, urlhash);
                        if (r != null)
                            state = Transactions.State.INVENTORY;
                        r = Transactions.getRevisions(Transactions.State.ARCHIVE, urlhash);
                        if (r != null)
                            state = Transactions.State.ARCHIVE;
                    } else {
                        r = Transactions.getRevisions(state, urlhash);
                    }
                    if (r != null) {
                        JSONObject metadata = new JSONObject();
                        DigestURL u;
                        u = r.url != null ? new DigestURL(r.url) : sb.index.fulltext().getURL(r.urlhash);
                        metadata.put("url", u == null ? "unknown" : u.toNormalform(true));
                        metadata.put("dates", r.dates);
                        metadata.put("depth", r.depth);
                        metadata.put("state", state.name());
                        result.put(r.urlhash, metadata);
                    }
                } catch (IOException | IllegalArgumentException e) {
                }
            }
        } catch (JSONException e) {
            ConcurrentLog.logException(e);
        }
        String json = result.toString();
        if (post.containsKey("callback"))
            json = post.get("callback") + "([" + json + "]);";
        return new ByteArrayInputStream(UTF8.getBytes(json));
    }

    // for the following methods we always need the durl to fetch data
    if (durl == null) {
        throw new TemplateMissingParameterException("Missing valid url or urlhash parameter");
    }

    if (xml) {
        Collection<File> xmlSnapshots = Transactions.findPaths(durl, "xml", Transactions.State.ANY);
        File xmlFile = null;
        if (xmlSnapshots.isEmpty()) {
            throw new TemplateProcessingException("Could not find the xml snapshot file.",
                    HttpStatus.SC_NOT_FOUND);
        }
        xmlFile = xmlSnapshots.iterator().next();
        try {
            byte[] xmlBinary = FileUtils.read(xmlFile);
            return new ByteArrayInputStream(xmlBinary);
        } catch (final IOException e) {
            ConcurrentLog.logException(e);
            throw new TemplateProcessingException("Could not read the xml snapshot file.");
        }
    }

    if (pdf || pngjpg) {
        Collection<File> pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.INVENTORY);
        File pdfFile = null;
        if (pdfSnapshots.isEmpty()) {
            // if the client is authenticated, we create the pdf on the fly!
            if (!authenticated) {
                throw new TemplateProcessingException(
                        "Could not find the pdf snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            SolrDocument sd = sb.index.fulltext().getMetadata(durl.hash());
            boolean success = false;
            if (sd == null) {
                success = Transactions.store(durl, new Date(), 99, false, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            } else {
                SolrInputDocument sid = sb.index.fulltext().getDefaultConfiguration().toSolrInputDocument(sd);
                success = Transactions.store(sid, false, true, true,
                        sb.getConfigBool(SwitchboardConstants.PROXY_TRANSPARENT_PROXY, false)
                                ? "http://127.0.0.1:" + sb.getConfigInt(SwitchboardConstants.SERVER_PORT, 8090)
                                : null,
                        sb.getConfig("crawler.http.acceptLanguage", null));
            }
            if (success) {
                pdfSnapshots = Transactions.findPaths(durl, "pdf", Transactions.State.ANY);
                if (!pdfSnapshots.isEmpty()) {
                    pdfFile = pdfSnapshots.iterator().next();
                }
            }
        } else {
            pdfFile = pdfSnapshots.iterator().next();
        }
        if (pdfFile == null) {
            throw new TemplateProcessingException(
                    "Could not find the pdf snapshot file and could not generate one on the fly.",
                    HttpStatus.SC_NOT_FOUND);
        }
        if (pdf) {
            try {
                byte[] pdfBinary = FileUtils.read(pdfFile);
                return new ByteArrayInputStream(pdfBinary);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not read the pdf snapshot file.");
            }
        }

        if (pngjpg) {
            int width = Math.min(post.getInt("width", DEFAULT_WIDTH), DEFAULT_WIDTH);
            int height = Math.min(post.getInt("height", DEFAULT_HEIGHT), DEFAULT_HEIGHT);
            String imageFileStub = pdfFile.getAbsolutePath();
            imageFileStub = imageFileStub.substring(0, imageFileStub.length() - 3); // cut off extension
            File imageFile = new File(imageFileStub + DEFAULT_WIDTH + "." + DEFAULT_HEIGHT + "." + ext);
            if (!imageFile.exists() && authenticated) {
                if (!Html2Image.pdf2image(pdfFile, imageFile, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_DENSITY,
                        DEFAULT_QUALITY)) {
                    throw new TemplateProcessingException(
                            "Could not generate the " + ext + " image snapshot file.");
                }
            }
            if (!imageFile.exists()) {
                throw new TemplateProcessingException(
                        "Could not find the " + ext
                                + " image snapshot file. You must be authenticated to generate one on the fly.",
                        HttpStatus.SC_NOT_FOUND);
            }
            if (width == DEFAULT_WIDTH && height == DEFAULT_HEIGHT) {
                try {
                    byte[] imageBinary = FileUtils.read(imageFile);
                    return new ByteArrayInputStream(imageBinary);
                } catch (final IOException e) {
                    ConcurrentLog.logException(e);
                    throw new TemplateProcessingException(
                            "Could not read the " + ext + " image snapshot file.");
                }
            }
            // lets read the file and scale
            Image image;
            try {
                image = ImageParser.parse(imageFile.getAbsolutePath(), FileUtils.read(imageFile));
                if (image == null) {
                    throw new TemplateProcessingException(
                            "Could not parse the " + ext + " image snapshot file.");
                }
                final Image scaled = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
                final MediaTracker mediaTracker = new MediaTracker(new Container());
                mediaTracker.addImage(scaled, 0);
                try {
                    mediaTracker.waitForID(0);
                } catch (final InterruptedException e) {
                }

                /*
                 * Ensure there is no alpha component on the ouput image, as it is pointless
                 * here and it is not well supported by the JPEGImageWriter from OpenJDK
                 */
                BufferedImage scaledBufferedImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                scaledBufferedImg.createGraphics().drawImage(scaled, 0, 0, width, height, null);
                return new EncodedImage(scaledBufferedImg, ext, true);
            } catch (final IOException e) {
                ConcurrentLog.logException(e);
                throw new TemplateProcessingException("Could not scale the " + ext + " image snapshot file.");
            }

        }
    }

    throw new TemplateProcessingException(
            "Unsupported extension : " + ext + ". Try with rss, xml, json, pdf, png or jpg.",
            HttpStatus.SC_BAD_REQUEST);
}

From source file:net.panthema.BispanningGame.GamePanel.java

public void writePdf() throws FileNotFoundException, DocumentException {

    // Query user for filename
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Specify PDF file to save");
    chooser.setCurrentDirectory(new File("."));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Documents", "pdf");
    chooser.setFileFilter(filter);/* www  .j  a v  a 2s  .c  om*/

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;

    File outfile = chooser.getSelectedFile();
    if (!outfile.getAbsolutePath().endsWith(".pdf")) {
        outfile = new File(outfile.getAbsolutePath() + ".pdf");
    }

    // Calculate page size rectangle
    Dimension size = mVV.getSize();
    Rectangle rsize = new Rectangle(size.width, size.height);

    // Open the PDF file for writing - and create a Graphics2D object
    Document document = new Document(rsize);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outfile));
    document.open();

    PdfContentByte contentByte = writer.getDirectContent();
    PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, size.width, size.height, new DefaultFontMapper());

    // Create a container to hold the visualization
    Container container = new Container();
    container.addNotify();
    container.add(mVV);
    container.setVisible(true);
    container.paintComponents(graphics2d);

    // Dispose of the graphics and close the document
    graphics2d.dispose();
    document.close();

    // Put mVV back onto visible plane
    setLayout(new BorderLayout());
    add(mVV, BorderLayout.CENTER);
}

From source file:net.yacy.cora.util.Html2Image.java

/**
 * convert a pdf (first page) to an image. proper values are i.e. width = 1024, height = 1024, density = 300, quality = 75
 * using internal pdf library or external command line tool on linux or mac
 * @param pdf input pdf file/*from   www. j  av  a2  s.c  o  m*/
 * @param image output jpg file
 * @param width
 * @param height
 * @param density (dpi)
 * @param quality
 * @return
 */
public static boolean pdf2image(File pdf, File image, int width, int height, int density, int quality) {
    final File convert = convertMac1.exists() ? convertMac1
            : convertMac2.exists() ? convertMac2 : convertDebian;

    // convert pdf to jpg using internal pdfbox capability
    if (OS.isWindows || !convert.exists()) {
        try {
            PDDocument pdoc = PDDocument.load(pdf);
            BufferedImage bi = new PDFRenderer(pdoc).renderImageWithDPI(0, density, ImageType.RGB);

            return ImageIO.write(bi, "jpg", image);

        } catch (IOException ex) {
        }
    }

    // convert on mac or linux using external command line utility
    try {
        // i.e. convert -density 300 -trim yacy.pdf[0] -trim -resize 1024x -crop x1024+0+0 -quality 75% yacy-convert-300.jpg
        // note: both -trim are necessary, otherwise it is trimmed only on one side. The [0] selects the first page of the pdf
        String command = convert.getAbsolutePath() + " -density " + density + " -trim " + pdf.getAbsolutePath()
                + "[0] -trim -resize " + width + "x -crop x" + height + "+0+0 -quality " + quality + "% "
                + image.getAbsolutePath();
        List<String> message = OS.execSynchronous(command);
        if (image.exists())
            return true;
        ConcurrentLog.warn("Html2Image", "failed to create image with command: " + command);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);

        // another try for mac: use Image Events using AppleScript in osacript commands...
        // the following command overwrites a pdf with an png, so we must make a copy first
        if (!OS.isMacArchitecture)
            return false;
        File pngFile = new File(pdf.getAbsolutePath() + ".tmp.pdf");
        org.apache.commons.io.FileUtils.copyFile(pdf, pngFile);
        String[] commandx = { "osascript", "-e", "set ImgFile to \"" + pngFile.getAbsolutePath() + "\"", "-e",
                "tell application \"Image Events\"", "-e", "set Img to open file ImgFile", "-e",
                "save Img as PNG", "-e", "end tell" };
        //ConcurrentLog.warn("Html2Image", "failed to create image with command: " + commandx);
        message = OS.execSynchronous(commandx);
        for (String m : message)
            ConcurrentLog.warn("Html2Image", ">> " + m);
        // now we must read and convert this file to a jpg with the target size 1024x1024
        try {
            File newPngFile = new File(pngFile.getAbsolutePath() + ".png");
            pngFile.renameTo(newPngFile);
            Image img = ImageParser.parse(pngFile.getAbsolutePath(), FileUtils.read(newPngFile));
            final Image scaled = img.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
            final MediaTracker mediaTracker = new MediaTracker(new Container());
            mediaTracker.addImage(scaled, 0);
            try {
                mediaTracker.waitForID(0);
            } catch (final InterruptedException e) {
            }
            // finally write the image
            final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            bi.createGraphics().drawImage(scaled, 0, 0, width, height, null);
            ImageIO.write(bi, "jpg", image);
            newPngFile.delete();
            return image.exists();
        } catch (IOException e) {
            ConcurrentLog.logException(e);
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

@Before
public void setUp() throws IllegalAccessException {
    Set<String> urlsWithBrowsers = ImmutableSet.of("u2", "u4", "u6");

    mockFrame = Mockito.mock(JFrame.class);
    mockContentPane = new Container();
    mockManyBrowsersPanel = Mockito.mock(ManyBrowsersPanel.class);
    mockMainCallbacks = Mockito.mock(MainCallbacks.class);
    mockConfiguration = Mockito.mock(Configuration.class);

    Mockito.when(mockFrame.getContentPane()).thenReturn(mockContentPane);

    Mockito.doAnswer(invocationOnMock -> windowListener = invocationOnMock.getArgument(0)).when(mockFrame)
            .addWindowListener(Mockito.any(WindowListener.class));

    Mockito.when(mockManyBrowsersPanel.hasBrowserForUrl(Mockito.anyString()))
            .thenAnswer(invocationOnMock -> urlsWithBrowsers.contains(invocationOnMock.<String>getArgument(0)));

    // Initialize the private Container.component field to prevent a null pointer exception later.
    FieldUtils.writeField(mockManyBrowsersPanel, "component", new ArrayList<>(), true);

    Mockito.when(mockMainCallbacks.shutdownApplication(Mockito.anyInt(), Mockito.any()))
            .thenAnswer(invocationOnMock -> {
                shutdownApplicationWasCalled = true;

                return true;
            });/*from  w w w. j ava  2 s  . com*/

    Mockito.when(mockConfiguration.getBackgroundBrowserMaxCount()).thenReturn(2);
    Mockito.when(mockConfiguration.getBackgroundTimerInitialDelay()).thenReturn(2000);
    Mockito.when(mockConfiguration.getBackgroundTimerDelay()).thenReturn(600);
    Mockito.when(mockConfiguration.getFetchedValue()).thenReturn("fetched");
}

From source file:org.muse.mneme.impl.AttachmentServiceImpl.java

/**
 * Create a thumbnail image from the full image in the byte[], of the desired width and height and quality, preserving aspect ratio.
 * /*from w  w w .  ja v a2  s  .  c  om*/
 * @param full
 *        The full image bytes.
 * @param width
 *        The desired max width (pixels).
 * @param height
 *        The desired max height (pixels).
 * @param quality
 *        The JPEG quality (0 - 1).
 * @return The thumbnail JPEG as a byte[].
 * @throws IOException
 * @throws InterruptedException
 */
protected byte[] makeThumb(byte[] full, int width, int height, float quality)
        throws IOException, InterruptedException {
    // read the image from the byte array, waiting till it's processed
    Image fullImage = Toolkit.getDefaultToolkit().createImage(full);
    MediaTracker tracker = new MediaTracker(new Container());
    tracker.addImage(fullImage, 0);
    tracker.waitForID(0);

    // get the full image dimensions
    int fullWidth = fullImage.getWidth(null);
    int fullHeight = fullImage.getHeight(null);

    // preserve the aspect of the full image, not exceeding the thumb dimensions
    if (fullWidth > fullHeight) {
        // full width will take the full desired width, set the appropriate height
        height = (int) ((((float) width) / ((float) fullWidth)) * ((float) fullHeight));
    } else {
        // full height will take the full desired height, set the appropriate width
        width = (int) ((((float) height) / ((float) fullHeight)) * ((float) fullWidth));
    }

    // draw the scaled thumb
    BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2D = thumbImage.createGraphics();
    g2D.drawImage(fullImage, 0, 0, width, height, null);

    // encode as jpeg to a byte array
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(byteStream);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
    param.setQuality(quality, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(thumbImage);
    out.close();
    byte[] thumb = byteStream.toByteArray();

    return thumb;
}

From source file:org.spiderplan.tools.visulization.GraphFrame.java

/**
 * @param graph//from   w ww .ja v a  2s.c o  m
 * @param history optional history of the graph
 * @param title 
 * @param lC the layout
 * @param edgeLabels map from edges to string labels
 * @param w width of the window
 * @param h height of the window
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public GraphFrame(AbstractTypedGraph<V, E> graph, Vector<AbstractTypedGraph<V, E>> history, String title,
        LayoutClass lC, Map<E, String> edgeLabels, int w, int h) {
    super(title);
    this.edgeLabels = edgeLabels;
    this.g = new ObservableGraph<V, E>(graph);
    this.g.addGraphEventListener(this);

    this.defaultEdgeType = this.g.getDefaultEdgeType();

    this.layoutClass = lC;

    this.history = history;

    this.setLayout(lC);

    layout.setSize(new Dimension(w, h));

    try {
        Relaxer relaxer = new VisRunner((IterativeContext) layout);
        relaxer.stop();
        relaxer.prerelax();
    } catch (java.lang.ClassCastException e) {
    }

    //      Layout<V,E> staticLayout = new StaticLayout<V,E>(g, layout);
    //      Layout<V,E> staticLayout = new SpringLayout<V, E>(g);

    vv = new VisualizationViewer<V, E>(layout, new Dimension(w, h));

    JRootPane rp = this.getRootPane();
    rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    getContentPane().setLayout(new BorderLayout());
    getContentPane().setBackground(java.awt.Color.lightGray);
    getContentPane().setFont(new Font("Serif", Font.PLAIN, 10));

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.S);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<V>());
    vv.setForeground(Color.black);

    graphMouse = new EditingModalGraphMouse<V, E>(vv.getRenderContext(), null, null);
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());

    //        vv.getRenderContext().setEd
    vv.getRenderContext().setEdgeLabelTransformer(this);
    vv.getRenderContext().setEdgeDrawPaintTransformer(
            new PickableEdgePaintTransformer<E>(vv.getPickedEdgeState(), Color.black, Color.cyan));

    vv.addComponentListener(new ComponentAdapter() {

        /**
         * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent)
         */
        @Override
        public void componentResized(ComponentEvent arg0) {
            super.componentResized(arg0);
            layout.setSize(arg0.getComponent().getSize());
        }
    });

    getContentPane().add(vv);

    /**
     * Create simple container for stuff on SOUTH border of this JFrame
     */
    Container c = new Container();
    c.setLayout(new FlowLayout());
    c.setBackground(java.awt.Color.lightGray);
    c.setFont(new Font("Serif", Font.PLAIN, 10));

    /**
     * Button to dump jpeg
     */
    dumpJPEG = new JButton("Dump");
    dumpJPEG.addActionListener(this);
    dumpJPEG.setName("Dump");
    c.add(dumpJPEG);

    /**
     * Button that creates offspring frame for selected vertices
     */
    subGraphButton = new JButton("Subgraph");
    subGraphButton.addActionListener(this);
    subGraphButton.setName("Subgraph");
    c.add(subGraphButton);

    subGraphDepthLabel = new JLabel("Depth");
    c.add(subGraphDepthLabel);
    subGraphDepth = new JTextField("0", 2);
    subGraphDepth.setHorizontalAlignment(SwingConstants.CENTER);
    subGraphDepth.setToolTipText("Depth of sub-graph created from selected nodes.");
    c.add(subGraphDepth);

    /**
     * Button that switches mouse mode
     */
    switchMode = new JButton("Transformation");
    switchMode.addActionListener(this);
    switchMode.setName("SwitchMode");
    c.add(switchMode);

    /**
     * ComboBox for Layout selection:
     */
    JComboBox layoutList;
    if (graph instanceof Forest) {
        String[] layoutStrings = { "Static", "Circle", "DAG", "Spring", "Spring2", "FR", "FR2", "Baloon",
                "ISOM", "KK", "PolarPoint", "RadialTree", "Tree" };
        layoutList = new JComboBox(layoutStrings);
    } else {
        String[] layoutStrings = { "Static", "Circle", "DAG", "Spring", "Spring2", "FR", "FR2", "ISOM", "KK",
                "PolarPoint" };
        layoutList = new JComboBox(layoutStrings);
    }

    layoutList.setSelectedIndex(5);
    layoutList.addActionListener(this);
    layoutList.setName("SelectLayout");
    c.add(layoutList);

    /**
     * Add container to layout
     */
    c.setVisible(true);
    getContentPane().add(c, BorderLayout.SOUTH);

    /**
     * Setup history scroll bar
     */
    if (history != null) {
        historySlider = new JSlider(0, history.size() - 1, history.size() - 1);
        historySlider.addChangeListener(this);
        historySlider.setMajorTickSpacing(10);
        historySlider.setMinorTickSpacing(1);
        historySlider.setPaintTicks(true);
        historySlider.setPaintLabels(true);

        historySlider.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        Font font = new Font("Serif", Font.ITALIC, 15);
        historySlider.setFont(font);

        getContentPane().add(historySlider, BorderLayout.NORTH);

    }
    this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    this.pack();
    this.setVisible(true);
}