Search in sources :

Example 26 with ServiceException

use of loci.common.services.ServiceException in project bioformats by openmicroscopy.

the class FormatTools method convert.

// -- Conversion convenience methods --
/**
 * Convenience method for converting the specified input file to the
 * specified output file.  The ImageReader and ImageWriter classes are used
 * for input and output, respectively.  To use other IFormatReader or
 * IFormatWriter implementation,
 * @see #convert(IFormatReader, IFormatWriter, String).
 *
 * @param input the full path name of the existing input file
 * @param output the full path name of the output file to be created
 * @throws FormatException if there is a general problem reading from or
 * writing to one of the files.
 * @throws IOException if there is an I/O-related error.
 */
public static void convert(String input, String output) throws FormatException, IOException {
    IFormatReader reader = new ImageReader();
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        reader.setMetadataStore(service.createOMEXMLMetadata());
    } catch (DependencyException de) {
        throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
    } catch (ServiceException se) {
        throw new FormatException(se);
    }
    reader.setId(input);
    IFormatWriter writer = new ImageWriter();
    convert(reader, writer, output);
}
Also used : ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService)

Example 27 with ServiceException

use of loci.common.services.ServiceException in project bioformats by openmicroscopy.

the class MetadataTools method populatePixels.

/**
 * Populates the Pixels element of the given metadata store, using core
 * metadata from the given reader.  If the {@code doPlane} flag is set,
 * then the Plane elements will be populated as well. If the
 * {@code doImageName} flag is set, then the image name will be populated as
 * well.
 *
 * @param store       The metadata store whose Pixels should be populated
 * @param r           The format reader whose core metadata should be used
 * @param doPlane     Specifies whether Plane elements should be populated
 * @param doImageName Specifies whether the Image name should be populated
 */
public static void populatePixels(MetadataStore store, IFormatReader r, boolean doPlane, boolean doImageName) {
    if (store == null || r == null)
        return;
    int oldSeries = r.getSeries();
    for (int i = 0; i < r.getSeriesCount(); i++) {
        r.setSeries(i);
        String imageName = null;
        if (doImageName) {
            Location f = new Location(r.getCurrentFile());
            imageName = f.getName();
            if (r.getSeriesCount() > 1) {
                imageName += " #" + (i + 1);
            }
        }
        String pixelType = FormatTools.getPixelTypeString(r.getPixelType());
        populateMetadata(store, r.getCurrentFile(), i, imageName, r.isLittleEndian(), r.getDimensionOrder(), pixelType, r.getSizeX(), r.getSizeY(), r.getSizeZ(), r.getSizeC(), r.getSizeT(), r.getRGBChannelCount());
        store.setPixelsInterleaved(r.isInterleaved(), i);
        store.setPixelsSignificantBits(new PositiveInteger(r.getBitsPerPixel()), i);
        try {
            OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class);
            if (service.isOMEXMLRoot(store.getRoot())) {
                MetadataStore baseStore = r.getMetadataStore();
                if (service.isOMEXMLMetadata(baseStore)) {
                    OMEXMLMetadata omeMeta;
                    try {
                        omeMeta = service.getOMEMetadata(service.asRetrieve(baseStore));
                        if (omeMeta.getTiffDataCount(i) == 0 && omeMeta.getPixelsBinDataCount(i) == 0) {
                            service.addMetadataOnly(omeMeta, i, i == 0);
                        }
                    } catch (ServiceException e) {
                        LOGGER.warn("Failed to add MetadataOnly", e);
                    }
                }
            }
        } catch (DependencyException exc) {
            LOGGER.warn("Failed to add MetadataOnly", exc);
        }
        if (doPlane) {
            for (int q = 0; q < r.getImageCount(); q++) {
                int[] coords = r.getZCTCoords(q);
                store.setPlaneTheZ(new NonNegativeInteger(coords[0]), i, q);
                store.setPlaneTheC(new NonNegativeInteger(coords[1]), i, q);
                store.setPlaneTheT(new NonNegativeInteger(coords[2]), i, q);
            }
        }
    }
    r.setSeries(oldSeries);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) PositiveInteger(ome.xml.model.primitives.PositiveInteger) ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) Location(loci.common.Location)

Example 28 with ServiceException

use of loci.common.services.ServiceException in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method getOMEXML.

/**
 * @see OMEXMLService#getOMEXML(loci.formats.meta.MetadataRetrieve)
 */
@Override
public String getOMEXML(MetadataRetrieve src) throws ServiceException {
    OMEXMLMetadata omexmlMeta = getOMEMetadata(src);
    String xml = omexmlMeta.dumpXML();
    // make sure that the namespace has been set correctly
    // convert XML string to DOM
    Document doc = null;
    Exception exception = null;
    try {
        doc = XMLTools.parseDOM(xml);
    } catch (ParserConfigurationException exc) {
        exception = exc;
    } catch (SAXException exc) {
        exception = exc;
    } catch (IOException exc) {
        exception = exc;
    }
    if (exception != null) {
        LOGGER.info("Malformed OME-XML", exception);
        return null;
    }
    Element root = doc.getDocumentElement();
    root.setAttribute("xmlns", SCHEMA_PATH + getLatestVersion());
    // convert tweaked DOM back to XML string
    try {
        xml = XMLTools.getXML(doc);
    } catch (TransformerConfigurationException exc) {
        exception = exc;
    } catch (TransformerException exc) {
        exception = exc;
    }
    if (exception != null) {
        LOGGER.info("Internal XML conversion error", exception);
        return null;
    }
    return xml;
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) Element(org.w3c.dom.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) Document(org.w3c.dom.Document) ServiceException(loci.common.services.ServiceException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) SAXException(org.xml.sax.SAXException)

Example 29 with ServiceException

use of loci.common.services.ServiceException in project bioformats by openmicroscopy.

the class ImageViewer method actionPerformed.

// -- ActionListener API methods --
/**
 * Handles menu commands.
 */
@Override
public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if ("open".equals(cmd)) {
        wait(true);
        JFileChooser chooser = GUITools.buildFileChooser(myReader);
        wait(false);
        int rval = chooser.showOpenDialog(this);
        if (rval == JFileChooser.APPROVE_OPTION) {
            final File file = chooser.getSelectedFile();
            if (file != null)
                open(file.getAbsolutePath(), fileReader);
        }
    } else if ("save".equals(cmd)) {
        wait(true);
        JFileChooser chooser = GUITools.buildFileChooser(myWriter);
        wait(false);
        int rval = chooser.showSaveDialog(this);
        if (rval == JFileChooser.APPROVE_OPTION) {
            final File file = chooser.getSelectedFile();
            if (file != null)
                save(file.getAbsolutePath(), fileWriter);
        }
    } else if ("view".equals(cmd)) {
        if (omeMeta != null) {
            XMLWindow metaWindow = new XMLWindow("OME Metadata - " + getTitle());
            metaWindow.setDefaultCloseOperation(XMLWindow.DISPOSE_ON_CLOSE);
            Exception exception = null;
            try {
                MetadataRetrieve retrieve = omexmlService.asRetrieve(omeMeta);
                metaWindow.setXML(omexmlService.getOMEXML(retrieve));
                metaWindow.setVisible(true);
            } catch (ServiceException exc) {
                exception = exc;
            } catch (ParserConfigurationException exc) {
                exception = exc;
            } catch (SAXException exc) {
                exception = exc;
            } catch (IOException exc) {
                exception = exc;
            }
            if (exception != null) {
                LOGGER.info("Cannot display OME metadata", exception);
            }
        }
    } else if ("exit".equals(cmd))
        dispose();
    else if ("fps".equals(cmd)) {
        // HACK - JOptionPane prevents shutdown on dispose
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String result = JOptionPane.showInputDialog(this, "Animate using space bar. How many frames per second?", "" + fps);
        try {
            fps = Integer.parseInt(result);
        } catch (NumberFormatException exc) {
            LOGGER.debug("Could not parse fps '{}'", fps, exc);
        }
    } else if ("about".equals(cmd)) {
        // HACK - JOptionPane prevents shutdown on dispose
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        String msg = "<html>" + "OME Bio-Formats package for reading and " + "converting biological file formats." + "<br>Copyright (C) 2005 - " + FormatTools.YEAR + " Open Microscopy Environment:" + "<ul>" + "<li>Board of Regents of the University of Wisconsin-Madison</li>" + "<li>Glencoe Software, Inc.</li>" + "<li>University of Dundee</li>" + "</ul>" + "<i>" + FormatTools.URL_BIO_FORMATS + "</i>" + "<br>Version " + FormatTools.VERSION + " (VCS revision " + FormatTools.VCS_REVISION + "), built on " + FormatTools.DATE + "<br><br>See <a href=\"" + "https://docs.openmicroscopy.org/bio-formats/" + FormatTools.VERSION + "/users/index.html\">" + "https://docs.openmicroscopy.org/bio-formats/" + FormatTools.VERSION + "/users/index.html</a>" + "<br>for help with using Bio-Formats.";
        ImageIcon bioFormatsLogo = new ImageIcon(IFormatHandler.class.getResource("bio-formats-logo.png"));
        JOptionPane.showMessageDialog(null, msg, "Bio-Formats", JOptionPane.INFORMATION_MESSAGE, bioFormatsLogo);
    }
}
Also used : ImageIcon(javax.swing.ImageIcon) IOException(java.io.IOException) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) SAXException(org.xml.sax.SAXException) EnumerationException(ome.xml.model.enums.EnumerationException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) JFileChooser(javax.swing.JFileChooser) ServiceException(loci.common.services.ServiceException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 30 with ServiceException

use of loci.common.services.ServiceException in project bioformats by openmicroscopy.

the class ImageViewer method save.

/**
 * Saves the current images to the given destination
 * using the current format writer.
 */
public void save(String id) {
    if (images == null)
        return;
    wait(true);
    try {
        if (omeMeta == null) {
            omeMeta = omexmlService.createOMEXMLMetadata();
            omeMeta.setImageID(MetadataTools.createLSID("Image", 0), 0);
            omeMeta.setPixelsID(MetadataTools.createLSID("Pixels", 0), 0);
            omeMeta.setPixelsBigEndian(false, 0);
            String order = "XYCZT";
            if (in != null)
                order = in.getDimensionOrder();
            omeMeta.setPixelsDimensionOrder((DimensionOrder) new DimensionOrderEnumHandler().getEnumeration(order), 0);
            int type = AWTImageTools.getPixelType(images[0]);
            String pixelType = FormatTools.getPixelTypeString(type);
            omeMeta.setPixelsType((PixelType) new PixelTypeEnumHandler().getEnumeration(pixelType), 0);
            int rgbChannelCount = images[0].getRaster().getNumBands();
            int realChannelCount = sizeC / rgbChannelCount;
            for (int i = 0; i < realChannelCount; i++) {
                omeMeta.setChannelID(MetadataTools.createLSID("Channel", i, 0), 0, i);
                omeMeta.setChannelSamplesPerPixel(new PositiveInteger(rgbChannelCount), 0, i);
            }
            omeMeta.setPixelsSizeX(new PositiveInteger(images[0].getWidth()), 0);
            omeMeta.setPixelsSizeY(new PositiveInteger(images[0].getHeight()), 0);
            omeMeta.setPixelsSizeC(new PositiveInteger(sizeC), 0);
            omeMeta.setPixelsSizeZ(new PositiveInteger(sizeZ), 0);
            omeMeta.setPixelsSizeT(new PositiveInteger(sizeT), 0);
        }
        myWriter.setMetadataRetrieve(omexmlService.asRetrieve(omeMeta));
        myWriter.setId(id);
        boolean stack = myWriter.canDoStacks();
        ProgressMonitor progress = new ProgressMonitor(this, "Saving " + id, null, 0, stack ? images.length : 1);
        if (stack) {
            // save entire stack
            for (int i = 0; i < images.length; i++) {
                progress.setProgress(i);
                boolean canceled = progress.isCanceled();
                myWriter.saveImage(i, images[i]);
                if (canceled)
                    break;
            }
            progress.setProgress(images.length);
        } else {
            // save current image only
            myWriter.savePlane(0, getImage());
            progress.setProgress(1);
        }
        myWriter.close();
    } catch (FormatException exc) {
        LOGGER.info("", exc);
    } catch (IOException exc) {
        LOGGER.info("", exc);
    } catch (ServiceException exc) {
        LOGGER.info("", exc);
    } catch (EnumerationException exc) {
        LOGGER.info("", exc);
    }
    wait(false);
}
Also used : ProgressMonitor(javax.swing.ProgressMonitor) PositiveInteger(ome.xml.model.primitives.PositiveInteger) ServiceException(loci.common.services.ServiceException) PixelTypeEnumHandler(ome.xml.model.enums.handlers.PixelTypeEnumHandler) IOException(java.io.IOException) DimensionOrderEnumHandler(ome.xml.model.enums.handlers.DimensionOrderEnumHandler) EnumerationException(ome.xml.model.enums.EnumerationException) FormatException(loci.formats.FormatException)

Aggregations

ServiceException (loci.common.services.ServiceException)54 FormatException (loci.formats.FormatException)40 DependencyException (loci.common.services.DependencyException)34 ServiceFactory (loci.common.services.ServiceFactory)30 OMEXMLService (loci.formats.services.OMEXMLService)29 IOException (java.io.IOException)21 IMetadata (loci.formats.meta.IMetadata)16 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)12 Location (loci.common.Location)11 PositiveInteger (ome.xml.model.primitives.PositiveInteger)11 File (java.io.File)10 ImageReader (loci.formats.ImageReader)10 MetadataStore (loci.formats.meta.MetadataStore)10 CoreMetadata (loci.formats.CoreMetadata)9 OMEXMLMetadataRoot (ome.xml.meta.OMEXMLMetadataRoot)9 EnumerationException (ome.xml.model.enums.EnumerationException)9 RandomAccessInputStream (loci.common.RandomAccessInputStream)7 MissingLibraryException (loci.formats.MissingLibraryException)7 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)6 SAXException (org.xml.sax.SAXException)6