Search in sources :

Example 1 with ServiceException

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

the class ImportProcess method getOMEXML.

/**
 * Valid only after {@link ImportStep#READER}.
 */
public String getOMEXML() {
    if (omeXML == null) {
        // NB: Extract the OME-XML once, then keep it cached.
        try {
            ServiceFactory factory = new ServiceFactory();
            OMEXMLService service = factory.getInstance(OMEXMLService.class);
            omeXML = service.getOMEXML(getOMEMetadata());
        } catch (DependencyException de) {
        } catch (ServiceException se) {
        }
    }
    return omeXML;
}
Also used : ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService)

Example 2 with ServiceException

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

the class MINCReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    try {
        ServiceFactory factory = new ServiceFactory();
        netcdf = factory.getInstance(NetCDFService.class);
        netcdf.setFile(id);
    } catch (DependencyException e) {
        throw new MissingLibraryException(e);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Vector<String> variableList = netcdf.getVariableList();
        for (String variable : variableList) {
            Hashtable<String, Object> attributes = netcdf.getVariableAttributes(variable);
            String[] keys = attributes.keySet().toArray(new String[0]);
            Arrays.sort(keys);
            for (String key : keys) {
                if (attributes.get(key) instanceof Object[]) {
                    final StringBuilder sb = new StringBuilder();
                    Object[] o = (Object[]) attributes.get(key);
                    for (Object q : o) {
                        sb.append(q.toString());
                    }
                    addGlobalMeta(variable + " " + key, sb.toString());
                } else {
                    addGlobalMeta(variable + " " + key, attributes.get(key));
                }
            }
        }
    }
    CoreMetadata m = core.get(0);
    try {
        Object pixels = netcdf.getVariableValue("/image");
        if (pixels == null) {
            pixels = netcdf.getVariableValue("/minc-2.0/image/0/image");
            isMINC2 = true;
        }
        m.littleEndian = isMINC2;
        boolean signed = false;
        if (isMINC2) {
            Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/minc-2.0/image/0/image");
            String unsigned = attrs.get("_Unsigned").toString();
            if (!unsigned.startsWith("true")) {
                signed = true;
            }
        } else {
            Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/image");
            String signtype = attrs.get("signtype").toString();
            if (signtype.startsWith("signed")) {
                signed = true;
            }
        }
        if (pixels instanceof byte[][][]) {
            m.pixelType = signed ? FormatTools.INT8 : FormatTools.UINT8;
            pixelData = (byte[][][]) pixels;
        } else if (pixels instanceof byte[][][][]) {
            byte[][][][] actualPixels = (byte[][][][]) pixels;
            m.pixelType = signed ? FormatTools.INT8 : FormatTools.UINT8;
            pixelData = new byte[actualPixels.length * actualPixels[0].length][][];
            int nextPlane = 0;
            for (int t = 0; t < actualPixels.length; t++) {
                for (int z = 0; z < actualPixels[t].length; z++) {
                    pixelData[nextPlane++] = actualPixels[t][z];
                }
            }
        } else if (pixels instanceof short[][][]) {
            m.pixelType = signed ? FormatTools.INT16 : FormatTools.UINT16;
            short[][][] s = (short[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.shortsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof int[][][]) {
            m.pixelType = signed ? FormatTools.INT32 : FormatTools.UINT32;
            int[][][] s = (int[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.intsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof float[][][]) {
            m.pixelType = FormatTools.FLOAT;
            float[][][] s = (float[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.floatsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof double[][][]) {
            m.pixelType = FormatTools.DOUBLE;
            double[][][] s = (double[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.doublesToBytes(s[i][j], isLittleEndian());
                }
            }
        }
    } catch (ServiceException e) {
        throw new FormatException(e);
    }
    Length physicalX = null;
    Length physicalY = null;
    Length physicalZ = null;
    Length xPosition = null;
    Length yPosition = null;
    Length zPosition = null;
    if (isMINC2) {
        Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/xspace");
        m.sizeX = Integer.parseInt(attrs.get("length").toString());
        physicalX = getStepSize(attrs);
        xPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/yspace");
        m.sizeY = Integer.parseInt(attrs.get("length").toString());
        physicalY = getStepSize(attrs);
        yPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/zspace");
        m.sizeZ = Integer.parseInt(attrs.get("length").toString());
        physicalZ = getStepSize(attrs);
        zPosition = getStart(attrs);
    } else {
        m.sizeX = netcdf.getDimension("/xspace");
        m.sizeY = netcdf.getDimension("/yspace");
        m.sizeZ = netcdf.getDimension("/zspace");
        Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/xspace");
        physicalX = getStepSize(attrs);
        xPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/yspace");
        physicalY = getStepSize(attrs);
        yPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/zspace");
        physicalZ = getStepSize(attrs);
        zPosition = getStart(attrs);
    }
    try {
        m.sizeT = netcdf.getDimension("/time");
    } catch (NullPointerException e) {
        m.sizeT = 1;
    }
    m.sizeC = 1;
    m.imageCount = getSizeZ() * getSizeT() * getSizeC();
    m.rgb = false;
    m.indexed = false;
    m.dimensionOrder = "XYZCT";
    String history = null;
    if (isMINC2) {
        history = netcdf.getAttributeValue("/minc-2.0/ident");
    } else {
        history = netcdf.getAttributeValue("/history");
    }
    addGlobalMeta("Comment", history);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, xPosition != null || yPosition != null || zPosition != null);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        store.setImageDescription(history, 0);
        if (physicalX != null) {
            store.setPixelsPhysicalSizeX(physicalX, 0);
        }
        if (physicalY != null) {
            store.setPixelsPhysicalSizeY(physicalY, 0);
        }
        if (physicalZ != null) {
            store.setPixelsPhysicalSizeZ(physicalZ, 0);
        }
        for (int i = 0; i < getImageCount(); i++) {
            if (xPosition != null) {
                store.setPlanePositionX(xPosition, 0, i);
            }
            if (yPosition != null) {
                store.setPlanePositionY(yPosition, 0, i);
            }
            if (zPosition != null) {
                int z = getZCTCoords(i)[0];
                Double pos = zPosition.value().doubleValue();
                if (physicalZ != null && z > 0) {
                    pos += z * physicalZ.value().doubleValue();
                }
                store.setPlanePositionZ(FormatTools.createLength(pos, zPosition.unit()), 0, i);
            }
        }
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) MissingLibraryException(loci.formats.MissingLibraryException) NetCDFService(loci.formats.services.NetCDFService)

Example 3 with ServiceException

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

the class NDPIReader method openBytes.

/**
 * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
 */
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
    FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
    if (x == 0 && y == 0 && w == 1 && h == 1) {
        return buf;
    } else if (getSizeX() <= MAX_SIZE || getSizeY() <= MAX_SIZE) {
        int ifdIndex = getIFDIndex(getCoreIndex(), no);
        in = new RandomAccessInputStream(currentId);
        tiffParser = new TiffParser(in);
        tiffParser.setUse64BitOffsets(true);
        tiffParser.setYCbCrCorrection(false);
        byte[] b = tiffParser.getSamples(ifds.get(ifdIndex), buf, x, y, w, h);
        in.close();
        tiffParser.getStream().close();
        return b;
    }
    if (initializedSeries != getCoreIndex() || initializedPlane != no) {
        IFD ifd = ifds.get(getIFDIndex(getCoreIndex(), no));
        long offset = ifd.getStripOffsets()[0];
        long byteCount = ifd.getStripByteCounts()[0];
        if (in != null) {
            in.close();
        }
        in = new RandomAccessInputStream(currentId);
        in.seek(offset);
        in.setLength(offset + byteCount);
        try {
            service.close();
            long[] markers = ifd.getIFDLongArray(MARKER_TAG);
            if (!use64Bit) {
                for (int i = 0; i < markers.length; i++) {
                    markers[i] = markers[i] & 0xffffffffL;
                }
            }
            if (markers != null) {
                service.setRestartMarkers(markers);
            }
            service.initialize(in, getSizeX(), getSizeY());
        } catch (ServiceException e) {
            throw new FormatException(e);
        }
        initializedSeries = getCoreIndex();
        initializedPlane = no;
    }
    service.getTile(buf, x, y, w, h);
    return buf;
}
Also used : ServiceException(loci.common.services.ServiceException) IFD(loci.formats.tiff.IFD) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) FormatException(loci.formats.FormatException)

Example 4 with ServiceException

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

the class HamamatsuVMSReader method openBytes.

/**
 * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
 */
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
    FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
    int startCol = x / MAX_JPEG_SIZE;
    int startRow = y / MAX_JPEG_SIZE;
    String file = null;
    switch(getCoreIndex()) {
        case 0:
            file = tileFiles[no][startRow][startCol];
            break;
        case 1:
            file = macroFile;
            break;
        case 2:
            file = mapFile;
            break;
    }
    if (getSizeX() <= MAX_SIZE || getSizeY() <= MAX_SIZE) {
        JPEGReader reader = new JPEGReader();
        reader.setId(file);
        reader.openBytes(0, buf, x, y, w, h);
        reader.close();
        return buf;
    }
    if (service == null) {
        service = new JPEGTurboServiceImpl();
    }
    try {
        Region image = new Region(x, y, w, h);
        for (int row = startRow; row < nRows; row++) {
            for (int col = startCol; col < nCols; col++) {
                Region tile = new Region(col * MAX_JPEG_SIZE, row * MAX_JPEG_SIZE, col == nCols - 1 ? getSizeX() % MAX_JPEG_SIZE : MAX_JPEG_SIZE, row == nRows - 1 ? getSizeY() % MAX_JPEG_SIZE : MAX_JPEG_SIZE);
                if (!tile.intersects(image)) {
                    continue;
                }
                file = tileFiles[no][row][col];
                if (initializedSeries != getCoreIndex() || initializedPlane != no || !file.equals(initializedFile)) {
                    service.close();
                    if (restartMarkers.containsKey(file)) {
                        service.setRestartMarkers(restartMarkers.get(file));
                    } else {
                        service.setRestartMarkers(null);
                    }
                    // closing the service will close this file
                    RandomAccessInputStream s = new RandomAccessInputStream(file);
                    service.initialize(s, tile.width, tile.height);
                    restartMarkers.put(file, service.getRestartMarkers());
                    initializedSeries = getCoreIndex();
                    initializedPlane = no;
                    initializedFile = file;
                }
                Region intersection = tile.intersection(image);
                int tileX = intersection.x % MAX_JPEG_SIZE;
                int tileY = intersection.y % MAX_JPEG_SIZE;
                int rowLen = intersection.width * getRGBChannelCount();
                byte[] b = new byte[rowLen * intersection.height];
                service.getTile(b, tileX, tileY, intersection.width, intersection.height);
                for (int tileRow = 0; tileRow < intersection.height; tileRow++) {
                    int src = tileRow * rowLen;
                    int dest = (((intersection.y + tileRow - y) * w) + (intersection.x - x)) * getRGBChannelCount();
                    System.arraycopy(b, src, buf, dest, rowLen);
                }
            }
        }
    } catch (ServiceException e) {
        throw new FormatException(e);
    }
    return buf;
}
Also used : ServiceException(loci.common.services.ServiceException) Region(loci.common.Region) RandomAccessInputStream(loci.common.RandomAccessInputStream) FormatException(loci.formats.FormatException) JPEGTurboServiceImpl(loci.formats.services.JPEGTurboServiceImpl)

Example 5 with ServiceException

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

the class OMEXMLServiceImpl method validateOMEXML.

/**
 * @see OMEXMLService#validateOMEXML(java.lang.String, boolean)
 */
@Override
public boolean validateOMEXML(String xml, boolean pixelsHack) {
    // HACK: Inject a TiffData element beneath any childless Pixels elements.
    if (pixelsHack) {
        // 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 false;
        }
        // inject TiffData elements as needed
        NodeList list = doc.getElementsByTagName("Pixels");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            NodeList children = node.getChildNodes();
            boolean needsTiffData = true;
            for (int j = 0; j < children.getLength(); j++) {
                Node child = children.item(j);
                String name = child.getLocalName();
                if ("TiffData".equals(name) || "BinData".equals(name)) {
                    needsTiffData = false;
                    break;
                }
            }
            if (needsTiffData) {
                // inject TiffData element
                Node tiffData = doc.createElement("TiffData");
                node.insertBefore(tiffData, node.getFirstChild());
            }
        }
        // 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 false;
        }
    }
    try {
        OMEXMLMetadata omexml = createOMEXMLMetadata(xml);
        OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) omexml.getRoot();
        for (int image = 0; image < root.sizeOfImageList(); image++) {
            Image img = root.getImage(image);
            for (int i = 0; i < img.sizeOfLinkedAnnotationList(); i++) {
                Annotation annotation = img.getLinkedAnnotation(i);
                if (!(annotation instanceof XMLAnnotation)) {
                    continue;
                }
                String annotationXML = ((XMLAnnotation) annotation).getValue();
                Document annotationRoot = XMLTools.parseDOM(annotationXML);
                NodeList nodes = annotationRoot.getElementsByTagName("ModuloAlongZ");
                if (nodes.getLength() > 0) {
                    ((XMLAnnotation) annotation).setValue("");
                }
                nodes = annotationRoot.getElementsByTagName("ModuloAlongC");
                if (nodes.getLength() > 0) {
                    ((XMLAnnotation) annotation).setValue("");
                }
                nodes = annotationRoot.getElementsByTagName("ModuloAlongT");
                if (nodes.getLength() > 0) {
                    ((XMLAnnotation) annotation).setValue("");
                }
            }
        }
        omexml.setRoot(root);
        xml = getOMEXML(omexml);
    } catch (ServiceException | ParserConfigurationException | SAXException | IOException e) {
        LOGGER.warn("Could not remove Modulo annotations", e);
    }
    return XMLTools.validateXML(xml, "OME-XML", SCHEMA_CLASSPATH_READER);
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) Image(ome.xml.model.Image) 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) Annotation(ome.xml.model.Annotation) ModuloAnnotation(loci.formats.meta.ModuloAnnotation) OriginalMetadataAnnotation(loci.formats.meta.OriginalMetadataAnnotation) XMLAnnotation(ome.xml.model.XMLAnnotation) SAXException(org.xml.sax.SAXException) ServiceException(loci.common.services.ServiceException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) XMLAnnotation(ome.xml.model.XMLAnnotation) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

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