org.scijava.Context - java examples

Here are the examples of the java api org.scijava.Context taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

56 Examples 7

19 View Complete Implementation : AbstractReaderFilter.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
@Override
public void setContext(final Context ctx) {
    getParent().setContext(ctx);
}

19 View Complete Implementation : SnippetCreator.java
Copyright GNU General Public License v3.0
Author : tferr
/**
 * This method is called when the plugin is loaded. See
 * {@link ij.plugin.PlugIn#run(java.lang.String)} Prompts user for a new
 * snippet that will be saved in {@code BAR/My_Routines/}
 *
 * @param arg
 *            ignored (Otherwise specified in plugins.config).
 */
@Override
public void run(final String arg) {
    Utils.shiftClickWarning();
    if (new GuiUtils().getFileCount(Utils.getLibDir()) == 0) {
        final YesNoCancelDialog query = new YesNoCancelDialog(null, "Install lib Files?", "Some of the code generated by this plugin replacedumes the adoption\n" + "of centralized lib files, but none seem to exist in your local directory\n" + "(" + Utils.getLibDir() + ")\nWould you like to install them now?");
        if (query.cancelPressed()) {
            return;
        } else if (query.yesPressed()) {
            final Context context = (Context) IJ.runPlugIn("org.scijava.Context", "");
            final CommandService commandService = context.getService(CommandService.clreplaced);
            commandService.run(Installer.clreplaced, true);
            return;
        }
    }
    if (showDialog()) {
        if (sContents.length() > 0)
            saveAndOpenSnippet();
        else
            IJ.showStatus(sFilename + " was empty. No file was saved...");
    }
}

19 View Complete Implementation : StatefulSerializer.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static Map<Clreplaced<?>, List<Pair<DeserializerFactory, Double>>> getDeserializers(final Context context) {
    if (DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY == null) {
        try {
            DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClreplacedSortedByPriorities(DeserializerFactory.clreplaced, context));
        } catch (InstantiableException e) {
            throw new RuntimeException(e);
        }
    }
    return DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY;
}

19 View Complete Implementation : PainteraSerialization.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static Map<Clreplaced<?>, List<Pair<PainteraSerializer, Double>>> getSerializers(final Context context) {
    if (SERIALIZERS_SORTED_BY_PRIORITY == null) {
        try {
            SERIALIZERS_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClreplacedSortedByPriorities(PainteraSerializer.clreplaced, context));
        } catch (InstantiableException e) {
            throw new RuntimeException(e);
        }
    }
    return SERIALIZERS_SORTED_BY_PRIORITY;
}

19 View Complete Implementation : StatefulSerializer.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static Map<Clreplaced<?>, List<Pair<SerializerFactory, Double>>> getSerializers(final Context context) {
    if (SERIALIZER_FACTORIES_SORTED_BY_PRIORITY == null) {
        try {
            SERIALIZER_FACTORIES_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClreplacedSortedByPriorities(SerializerFactory.clreplaced, context));
        } catch (InstantiableException e) {
            throw new RuntimeException(e);
        }
    }
    return SERIALIZER_FACTORIES_SORTED_BY_PRIORITY;
}

19 View Complete Implementation : SciJavaUtils.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static <T extends SciJavaPlugin & HasTargetClreplaced<?>> Map<Clreplaced<?>, List<Pair<T, Double>>> byTargetClreplacedSortedByPriorities(final Clreplaced<T> clazz, final Context context) throws InstantiableException {
    return byTargetClreplacedSortedByPriorities(getAllMatchingPluginInfos(clazz, context));
}

19 View Complete Implementation : FilterTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
private SCIFIO makeSCIFIO() {
    final SCIFIO scifio = new SCIFIO();
    final Context ctx = scifio.getContext();
    final PluginInfo<Filter> enabledInfo = new PluginInfo<>(EnabledFilter.clreplaced, Filter.clreplaced);
    final PluginInfo<Filter> disabledInfo = new PluginInfo<>(DisabledFilter.clreplaced, Filter.clreplaced);
    ctx.getPluginIndex().add(enabledInfo);
    ctx.getPluginIndex().add(disabledInfo);
    return scifio;
}

19 View Complete Implementation : REPLEditor.java
Copyright BSD 2-Clause "Simplified" License
Author : scenerygraphics
private ThreadService threadService() {
    // HACK: Get the SciJava context from the REPL.
    // This can be fixed if/when the REPL offers a getter for it.
    final Context ctx = (Context) // 
    ClreplacedUtils.getValue(Types.field(repl.getClreplaced(), "context"), repl);
    return ctx.service(ThreadService.clreplaced);
}

19 View Complete Implementation : ModulesResource.java
Copyright Apache License 2.0
Author : imagej
/**
 * Initialize resource by injection. Should not be called directly.
 *
 * @param ctx
 */
@Inject
public void initialize(final Context ctx) {
    ctx.inject(this);
    updateModuleCache();
}

19 View Complete Implementation : DefaultTableIOPluginTest.java
Copyright Apache License 2.0
Author : imagej
/**
 * Tests for {@link DefaultTableIOPlugin}.
 *
 * @author Leon Yang
 */
public clreplaced DefaultTableIOPluginTest {

    private static final Context ctx = new Context();

    /**
     * Tests if the parser works on a common tab-delimited table.
     */
    @Test
    public void testParser() {
        final String[][] cells = { { "col1", "col2", "col3", "col4", "col5" }, { "123", "-123.0", "+123.0f", "0123.0d", "0.0" }, { "00000", "1234567890.0987654321", "+NaN", "-Infinity", "000.000" } };
        final String tableSource = makeTableSource(cells, "\t", "\n");
        final String[] colHeaders = cells[0];
        final String[] rowHeaders = { null, null };
        final Double[][] content = { { 123.0, -123.0, 123.0, 123.0, 0.0 }, { 0.0, 1234567890.0987654321, Double.NaN, Double.NEGATIVE_INFINITY, 0.0 } };
        final String expected = "col1\tcol2\tcol3\tcol4\tcol5\n" + "123.000\t-123.000\t123.000\t123.000\t0.000\n" + "0.000\t1234567890.099\tNaN\t-Infinity\t0.000\n";
        final IOPlugin<GenericTable> tableIO = ctx.service(IOService.clreplaced).getInstance(DefaultTableIOPlugin.clreplaced);
        try {
            final Function<String, Double> parser = Double::valueOf;
            final Function<Double, String> formatter = val -> String.format("%.3f", val);
            setValues(tableIO, new String[] { "readColHeaders", "writeColHeaders", "readRowHeaders", "writeRowHeaders", "separator", "eol", "quote", "cornerText", "parser", "formatter" }, new Object[] { true, true, false, true, "\t", "\n", "\"", "\\", parser, formatter });
            final GenericTable table = openTable(tableSource, tableIO);
            replacedertTableEquals(colHeaders, rowHeaders, content, table);
            replacedertEquals(expected, saveTable(table, tableIO));
        } catch (final Exception exc) {
            exc.printStackTrace();
            fail(exc.getMessage());
        }
    }

    /**
     * Tests if quoting works in different senarios.
     */
    @Test
    public void testQuote() {
        final String[][] cells = { { "CORNER_TEXT", "' col  1 with white   spaces '", "'col 2 with ''QUOTE'' inside'", "'col 3 'connect,two' quoted strings'" }, { "should\tnot,break", "'unnecessary_quotes'", "should break" }, { "some,empty,cells", "", " ''" } };
        final String tableSource = makeTableSource(cells, " ", "\r\n");
        final String[] colHeaders = { " col  1 with white   spaces ", "col 2 with 'QUOTE' inside", "col 3 connect,two quoted strings" };
        final String[] rowHeaders = { "should\tnot,break", "some,empty,cells" };
        final String[][] content = { { "unnecessary_quotes", "should", "break" }, { "", "", "" } };
        final String expected = "CORNER_TEXT, col  1 with white   spaces ," + "'col 2 with ''QUOTE'' inside'," + "'col 3 connect,two quoted strings'\r\n" + "'should\tnot,break',unnecessary_quotes,should,break\r\n" + "'some,empty,cells','','',''\r\n";
        final IOPlugin<GenericTable> tableIO = ctx.service(IOService.clreplaced).getInstance(DefaultTableIOPlugin.clreplaced);
        try {
            setValues(tableIO, new String[] { "readColHeaders", "writeColHeaders", "readRowHeaders", "writeRowHeaders", "separator", "eol", "quote", "cornerText", "parser", "formatter" }, new Object[] { true, true, true, true, " ", "\r\n", '\'', "CORNER_TEXT", Function.idenreplacedy(), Function.idenreplacedy() });
            final GenericTable table = openTable(tableSource, tableIO);
            replacedertTableEquals(colHeaders, rowHeaders, content, table);
            setValues(tableIO, new String[] { "separator" }, new Object[] { ',' });
            replacedertEquals(expected, saveTable(table, tableIO));
        } catch (final Exception exc) {
            exc.printStackTrace();
            fail(exc.getMessage());
        }
    }

    /**
     * Tests if samll tables could be opened/saved correctly.
     */
    @Test
    public void testSmallTables() {
        final String[][] singleRow = { { "Row Header", "   3.1415926   " } };
        final String[][] singleCell = { { "   3.1415926   " } };
        final String[][] singleCol = { { "Col Header" }, { "   3.1415926   " } };
        final String[][] onlyRowHeader = { { "CORNER TEXT" }, { "Row Header" } };
        final String[][] onlyColHeader = { { "CORNER TEXT", "Col Header" } };
        final String[][] full = { { "CORNER TEXT", "Col Header" }, { "Row Header", "   3.1415926   " } };
        final String[] singleColHeader = { "Col Header" };
        final String[] singleRowHeader = { "Row Header" };
        final String[] emptyHeader = { null };
        final String[] empty = {};
        final Double[][] content = { { 3.1415926 } };
        final Double[][] emptyContent = { {} };
        final IOPlugin<GenericTable> tableIO = ctx.service(IOService.clreplaced).getInstance(DefaultTableIOPlugin.clreplaced);
        try {
            GenericTable table;
            String expected;
            final Function<String, Double> parser = Double::valueOf;
            final Function<Double, String> formatter = val -> String.format("%.3f", val);
            setValues(tableIO, new String[] { "readColHeaders", "writeColHeaders", "readRowHeaders", "writeRowHeaders", "separator", "eol", "quote", "cornerText", "parser", "formatter" }, new Object[] { false, true, true, true, ",", "\n", "'", "CORNER TEXT", parser, formatter });
            table = openTable(makeTableSource(singleRow, ",", "\n"), tableIO);
            replacedertTableEquals(emptyHeader, singleRowHeader, content, table);
            expected = "Row Header,3.142\n";
            replacedertEquals(expected, saveTable(table, tableIO));
            setValues(tableIO, new String[] { "readRowHeaders" }, new Object[] { false });
            table = openTable(makeTableSource(singleCell, ",", "\n"), tableIO);
            replacedertTableEquals(emptyHeader, emptyHeader, content, table);
            expected = "3.142\n";
            replacedertEquals(expected, saveTable(table, tableIO));
            setValues(tableIO, new String[] { "readColHeaders" }, new Object[] { true });
            table = openTable(makeTableSource(singleCol, ",", "\n"), tableIO);
            replacedertTableEquals(singleColHeader, emptyHeader, content, table);
            expected = "Col Header\n3.142\n";
            replacedertEquals(expected, saveTable(table, tableIO));
            setValues(tableIO, new String[] { "readRowHeaders" }, new Object[] { true });
            table = openTable(makeTableSource(onlyColHeader, ",", "\n"), tableIO);
            replacedertTableEquals(singleColHeader, empty, emptyContent, table);
            expected = "Col Header\n";
            replacedertEquals(expected, saveTable(table, tableIO));
            table = openTable(makeTableSource(onlyRowHeader, ",", "\n"), tableIO);
            replacedertTableEquals(empty, singleRowHeader, emptyContent, table);
            expected = "Row Header\n";
            replacedertEquals(expected, saveTable(table, tableIO));
            table = openTable(makeTableSource(full, ",", "\n"), tableIO);
            replacedertTableEquals(singleColHeader, singleRowHeader, content, table);
            expected = "CORNER TEXT,Col Header\nRow Header,3.142\n";
            replacedertEquals(expected, saveTable(table, tableIO));
        } catch (final Exception exc) {
            exc.printStackTrace();
            fail(exc.getMessage());
        }
    }

    @Test(expected = IOException.clreplaced)
    public void testOpenNonExist() throws IOException {
        final IOPlugin<GenericTable> tableIO = ctx.service(IOService.clreplaced).getInstance(DefaultTableIOPlugin.clreplaced);
        tableIO.open("fake.csv");
    }

    // -- helper methods --
    /**
     * Checks if a table has the expected column/row headers and content.
     */
    private void replacedertTableEquals(final String[] colHeaders, final String[] rowHeaders, final Object[][] content, final GenericTable table) {
        replacedertEquals(colHeaders.length, table.getColumnCount());
        replacedertEquals(rowHeaders.length, table.getRowCount());
        for (int c = 0; c < colHeaders.length; c++) {
            replacedertEquals(colHeaders[c], table.getColumnHeader(c));
            for (int r = 0; r < rowHeaders.length; r++) {
                replacedertEquals(content[r][c], table.get(c, r));
            }
        }
        for (int r = 0; r < rowHeaders.length; r++) {
            replacedertEquals(rowHeaders[r], table.getRowHeader(r));
        }
    }

    private GenericTable openTable(final String tableSource, final IOPlugin<GenericTable> tableIO) throws IOException {
        final ByteArrayHandle bah = new ByteArrayHandle(tableSource.getBytes());
        ctx.service(LocationService.clreplaced).mapFile("table.txt", bah);
        return tableIO.open("table.txt");
    }

    private String saveTable(final GenericTable table, final IOPlugin<GenericTable> tableIO) throws IOException {
        final ByteArrayHandle bah = new ByteArrayHandle();
        ctx.service(LocationService.clreplaced).mapFile("table.txt", bah);
        tableIO.save(table, "table.txt");
        return new String(bah.getBytes(), 0, (int) bah.length());
    }

    private void setValues(final Object instance, final String[] fieldNames, final Object[] values) throws SecurityException {
        final Clreplaced<?> cls = instance.getClreplaced();
        final List<Field> fields = ClreplacedUtils.getAnnotatedFields(cls, Parameter.clreplaced);
        final HashMap<String, Field> fieldMap = new HashMap<>();
        for (final Field field : fields) {
            fieldMap.put(field.getName(), field);
        }
        for (int i = 0; i < fieldNames.length; i++) {
            ClreplacedUtils.setValue(fieldMap.get(fieldNames[i]), instance, values[i]);
        }
    }

    private String makeTableSource(final String[][] cells, final String separator, final String eol) {
        final StringBuilder table = new StringBuilder();
        for (final String[] row : cells) {
            table.append(String.join(separator, row)).append(eol);
        }
        return table.toString();
    }
}

19 View Complete Implementation : PainteraSerialization.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static Map<Clreplaced<?>, List<Pair<PainteraDeserializer, Double>>> getDeserializers(final Context context) {
    if (DESERIALIZERS_SORTED_BY_PRIORITY == null) {
        try {
            DESERIALIZERS_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClreplacedSortedByPriorities(PainteraDeserializer.clreplaced, context));
        } catch (InstantiableException e) {
            throw new RuntimeException(e);
        }
    }
    return DESERIALIZERS_SORTED_BY_PRIORITY;
}

18 View Complete Implementation : KontronFormatTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Tests {@link KontronFormat} and its subclreplacedes
 *
 * @author Richard Domander (Royal Veterinary College, London)
 */
public clreplaced KontronFormatTest {

    private static final Context context = new Context();

    private static final KontronFormat format = new KontronFormat();

    private static KontronFormat.Reader reader;

    private static KontronFormat.Parser parser;

    private static DataHandleService dataHandleService;

    private static final KontronFormat.Checker checker = new KontronFormat.Checker();

    @BeforeClreplaced
    public static void oneTimeSetup() throws Exception {
        format.setContext(context);
        reader = (KontronFormat.Reader) format.createReader();
        parser = (KontronFormat.Parser) format.createParser();
        dataHandleService = context.getService(DataHandleService.clreplaced);
    }

    @Before
    public void setUp() throws Exception {
    }

    @AfterClreplaced
    public static void oneTimeTearDown() {
        context.dispose();
    }

    /**
     * Test isFormat returns false when stream is too short to match the id
     * sequence
     */
    @Test
    public void testIsFormatFalseShortStream() throws Exception {
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation(new byte[] { 0x1, 0x0, 0x47 }));
        replacedertFalse(checker.isFormat(stream));
    }

    @Test
    public void testIsFormatFalseIncorrectBytes() throws Exception {
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation(new byte[] { 0x1, 0x0, 0x47, 0x12, 0x6D, (byte) 0xA0 }));
        replacedertFalse(checker.isFormat(stream));
    }

    @Test
    public void testIsFormat() throws Exception {
        // Add an extra byte to the end to check that it doesn't affect the result
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation(new byte[] { 0x1, 0x0, 0x47, 0x12, 0x6D, (byte) 0xB0, 0x13 }));
        replacedertTrue(checker.isFormat(stream));
    }

    @Test
    public void testPopulateImageMetadata() throws Exception {
        final Metadata metadata = format.createMetadata();
        metadata.populateImageMetadata();
        final ImageMetadata imgMeta = metadata.get(0);
        replacedertTrue(imgMeta.isLittleEndian());
        replacedertTrue(imgMeta.isOrderCertain());
        replacedertEquals(8, imgMeta.getBitsPerPixel());
        replacedertEquals(FormatTools.UINT8, imgMeta.getPixelType());
        replacedertEquals(2, imgMeta.getPlanarAxisCount());
    }

    @Test
    public void testTypedParse() throws Exception {
        // SETUP
        final int width = 15;
        final int height = 10;
        final SCIFIOConfig config = new SCIFIOConfig();
        final KontronFormat.Metadata kontronMeta = new KontronFormat.Metadata();
        // Create a mock input stream with a Kontron header
        final DataHandle<Location> stream = FormatTestHelpers.createLittleEndianHandle(HEADER_BYTES, dataHandleService);
        // Mock a Kontron header
        stream.write(KontronFormat.KONTRON_ID);
        stream.writeShort(width);
        stream.writeShort(height);
        // stream.seek(HEADER_BYTES);
        reader.setSource(stream);
        // EXERCISE
        parser.typedParse(stream, kontronMeta, config);
        // VERIFY
        replacedertEquals(width, kontronMeta.getWidth());
        replacedertEquals(height, kontronMeta.getHeight());
    }

    @Test
    public void testOpenPlane() throws Exception {
        // SETUP
        final short width = 10;
        final short height = 10;
        final int planeBytes = width * height * 2;
        final Interval bounds = new FinalInterval(width, height);
        final ByteArrayPlane plane = new ByteArrayPlane();
        plane.setData(new byte[planeBytes]);
        final DataHandle<Location> handle = FormatTestHelpers.createLittleEndianHandle(HEADER_BYTES + planeBytes, dataHandleService, true);
        handle.write(KontronFormat.KONTRON_ID);
        handle.writeShort(width);
        handle.writeShort(height);
        handle.seek(KONTRON_ID.length);
        handle.writeShort(width);
        handle.writeShort(height);
        final Reader r = format.createReader();
        r.setSource(handle);
        // EXECUTE
        r.openPlane(0, 0, plane, bounds, new SCIFIOConfig());
        // VERIFY
        replacedertEquals("Position of stream incorrect: should point to the end of the file", handle.length(), handle.offset());
    }
}

18 View Complete Implementation : ScancoISQFormatTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Tests {@link ScancoISQFormat} and its subclreplacedes
 *
 * @author Richard Domander (Royal Veterinary College, London)
 */
public clreplaced ScancoISQFormatTest {

    private static final Context context = new Context();

    private static final ScancoISQFormat.Checker checker = new ScancoISQFormat.Checker();

    private static final ScancoISQFormat format = new ScancoISQFormat();

    private static ScancoISQFormat.Parser parser;

    private static DataHandleService dataHandleService;

    @BeforeClreplaced
    public static void oneTimeSetup() throws Exception {
        format.setContext(context);
        parser = (ScancoISQFormat.Parser) format.createParser();
        dataHandleService = context.getService(DataHandleService.clreplaced);
    }

    @AfterClreplaced
    public static void oneTimeTearDown() {
        context.dispose();
    }

    @Test
    public void testIsFormatFalseShortStream() throws Exception {
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation("CTDATA-HEADER_V".getBytes()));
        replacedertFalse(checker.isFormat(stream));
    }

    @Test
    public void testIsFormatIncorrectHeader() throws Exception {
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation("CTDATA-hEADER_V1".getBytes()));
        replacedertFalse(checker.isFormat(stream));
    }

    @Test
    public void testIsFormat() throws Exception {
        // Add an extra byte to the end to check that it doesn't affect the result
        final DataHandle<Location> stream = dataHandleService.create(new BytesLocation("CTDATA-HEADER_V1a".getBytes()));
        replacedertTrue(checker.isFormat(stream));
    }

    @Test
    public void testPopulateImageMetadata() throws Exception {
        // SETUP
        final ScancoISQFormat.Metadata metadata = (ScancoISQFormat.Metadata) format.createMetadata();
        final int[] dimensions = { 15, 14, 13 };
        final int[] physicalDimensions = { 45, 35, 20 };
        final double[] voxelDimensions = IntStream.range(0, 3).mapToDouble(i -> 1.0 * physicalDimensions[i] / dimensions[i]).toArray();
        metadata.setPhysicalWidth(physicalDimensions[0]);
        metadata.setPhysicalHeight(physicalDimensions[1]);
        metadata.setPhysicalDepth(physicalDimensions[2]);
        metadata.setWidth(dimensions[0]);
        metadata.setHeight(dimensions[1]);
        metadata.setSlices(dimensions[2]);
        metadata.populateImageMetadata();
        // EXECUTE
        final ImageMetadata imgMeta = metadata.get(0);
        // VERIFY
        replacedertTrue(imgMeta.isLittleEndian());
        replacedertTrue(imgMeta.isOrderCertain());
        replacedertEquals(16, imgMeta.getBitsPerPixel());
        replacedertEquals(FormatTools.INT16, imgMeta.getPixelType());
        replacedertEquals(2, imgMeta.getPlanarAxisCount());
        final List<CalibratedAxis> axes = imgMeta.getAxes();
        replacedertEquals(3, axes.size());
        for (int i = 0; i < 3; i++) {
            replacedertEquals(dimensions[i], imgMeta.getAxisLength(i));
            replacedertEquals(voxelDimensions[i], axes.get(i).averageScale(0, 1), 1e-12);
        }
    }

    @Test
    public void testTypedParse() throws Exception {
        // SETUP
        final int patientIndex = 5;
        final int scannerId = 345;
        // Apr 9 1984
        final long timestamp = 0x008c_9567_4beb_4000L;
        final int width = 12;
        final int height = 13;
        final int depth = 14;
        final int physicalWidth = 24;
        final int physicalHeight = 26;
        final int physicalDepth = 28;
        final int sliceThickness = 2;
        final int sliceIncrement = 1;
        final int firstSlice = 11;
        final int min = -1337;
        final int max = 1337;
        final int muScaling = 4096;
        final int samples = 100;
        final int projections = 111;
        final int scanDistance = 40;
        final int scannerType = 4;
        final int sampleTime = 1_000_000;
        final int measurementIndex = 1;
        final int site = 4;
        final int referenceLine = 15;
        final int algorithm = 6;
        final String name = "Johann Gambolputty de von Ausfern-schple";
        final int energy = 70_000;
        final int intensity = 200;
        final int optionalBlocks = 0;
        final DataHandle<Location> handle = FormatTestHelpers.createLittleEndianHandle(ScancoISQFormat.Metadata.HEADER_BLOCK, dataHandleService, true);
        handle.seek(28);
        handle.writeInt(patientIndex);
        handle.writeInt(scannerId);
        handle.writeLong(timestamp);
        handle.writeInt(width);
        handle.writeInt(height);
        handle.writeInt(depth);
        handle.writeInt(physicalWidth);
        handle.writeInt(physicalHeight);
        handle.writeInt(physicalDepth);
        handle.writeInt(sliceThickness);
        handle.writeInt(sliceIncrement);
        handle.writeInt(firstSlice);
        handle.writeInt(min);
        handle.writeInt(max);
        handle.writeInt(muScaling);
        handle.writeInt(samples);
        handle.writeInt(projections);
        handle.writeInt(scanDistance);
        handle.writeInt(scannerType);
        handle.writeInt(sampleTime);
        handle.writeInt(measurementIndex);
        handle.writeInt(site);
        handle.writeInt(referenceLine);
        handle.writeInt(algorithm);
        handle.write(name.getBytes());
        handle.writeInt(energy);
        handle.writeInt(intensity);
        handle.seek(508);
        handle.writeInt(optionalBlocks);
        final SCIFIOConfig config = new SCIFIOConfig();
        final ScancoISQFormat.Metadata metadata = new ScancoISQFormat.Metadata();
        // EXERCISE
        parser.typedParse(handle, metadata, config);
        metadata.populateImageMetadata();
        // VERIFY
        replacedertEquals(patientIndex, metadata.getPatientIndex());
        replacedertEquals(scannerId, metadata.getScannerId());
        replacedertTrue(LocalDate.of(1984, 4, 9).isEqual(metadata.getCreationDate()));
        replacedertEquals(width, metadata.getWidth());
        replacedertEquals(height, metadata.getHeight());
        replacedertEquals(depth, metadata.getSlices());
        replacedertEquals(physicalWidth, metadata.getPhysicalWidth());
        replacedertEquals(physicalHeight, metadata.getPhysicalHeight());
        replacedertEquals(physicalDepth, metadata.getPhysicalDepth());
        replacedertEquals(sliceThickness, metadata.getSliceThickness());
        replacedertEquals(sliceIncrement, metadata.getSliceSpacing());
        replacedertEquals(firstSlice, metadata.getFirstSlicePosition());
        replacedertEquals(min, metadata.getMinDataValue());
        replacedertEquals(max, metadata.getMaxDataValue());
        replacedertEquals(muScaling, metadata.getMuScaling());
        replacedertEquals(samples, metadata.getSamples());
        replacedertEquals(projections, metadata.getProjections());
        replacedertEquals(scanDistance, metadata.getScanDistance());
        replacedertEquals(scannerType, metadata.getScannerType());
        replacedertEquals(sampleTime, metadata.getSamplingTime());
        replacedertEquals(measurementIndex, metadata.getMeasurementIndex());
        replacedertEquals(site, metadata.getSite());
        replacedertEquals(referenceLine, metadata.getReferenceLine());
        replacedertEquals(algorithm, metadata.getReconstructionAlgorithm());
        replacedertEquals(name, metadata.getPatientName());
        replacedertEquals(energy, metadata.getEnergy());
        replacedertEquals(intensity, metadata.getIntensity());
        replacedertEquals(ScancoISQFormat.Metadata.HEADER_BLOCK, metadata.getDataOffset());
        replacedertEquals(2 * width * height, metadata.getSliceBytes());
    }

    @Test
    public void testOpenPlane() throws Exception {
        // SETUP
        final int width = 10;
        final int height = 10;
        final int depth = 3;
        final int planeBytes = width * height * 2;
        final int imageBytes = depth * planeBytes;
        final ByteArrayPlane plane = new ByteArrayPlane();
        plane.setData(new byte[planeBytes]);
        final DataHandle<Location> handle = FormatTestHelpers.createLittleEndianHandle(ScancoISQFormat.Metadata.HEADER_BLOCK + imageBytes, dataHandleService, true);
        handle.seek(44);
        handle.writeInt(width);
        handle.writeInt(height);
        handle.writeInt(depth);
        final Reader reader = format.createReader();
        reader.setSource(handle);
        // EXECUTE
        final Interval bounds = new FinalInterval(width, height, depth);
        reader.openPlane(0, 1, plane, bounds, new SCIFIOConfig());
        // VERIFY
        replacedertEquals("Position of stream incorrect: should point to the beginning of the 3rd slice", ScancoISQFormat.Metadata.HEADER_BLOCK + 2 * planeBytes, handle.offset());
    }
}

18 View Complete Implementation : TestImgLocationResolverTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Test for {@link TestImgLocationResolver}
 *
 * @author Gabriel Einsdorf
 */
public clreplaced TestImgLocationResolverTest {

    private Context ctx = new Context(LocationService.clreplaced, MetadataService.clreplaced);

    private LocationService loc = ctx.getService(LocationService.clreplaced);

    @Test
    public void testResolveString() throws URISyntaxException {
        final String ex1 = "scifioTestImg://myCoolImage?axes=X,Y";
        final String ex1Full = "scifioTestImg://myCoolImage?axes=X,Y&lengths=512,512&scales=1.0,1.0&units=um,um&planarDims=-1&interleavedDims=-1&thumbSizeX=0&thumbSizeY=0&pixelType=uint8&indexed=false&falseColor=false&little=true&metadataComplete=true&thumbnail=false&orderCertain=true&lutLength=3&scaleFactor=1&images=1";
        final String ex2 = "scifioTestImg://myAwesomeImage?lengths=300,200";
        final String ex2Full = "scifioTestImg://myAwesomeImage?axes=X,Y&lengths=300,200&scales=1.0,1.0&units=um,um&planarDims=-1&interleavedDims=-1&thumbSizeX=0&thumbSizeY=0&pixelType=uint8&indexed=false&falseColor=false&little=true&metadataComplete=true&thumbnail=false&orderCertain=true&lutLength=3&scaleFactor=1&images=1";
        final String ex3 = "scifioTestImg://great?axes=X,Y,Z&lengths=300,200,3";
        String ex3Full = "scifioTestImg://great?axes=X,Y,Z&lengths=300,200,3&scales=1.0,1.0&units=um,um&planarDims=-1&interleavedDims=-1&thumbSizeX=0&thumbSizeY=0&pixelType=uint8&indexed=false&falseColor=false&little=true&metadataComplete=true&thumbnail=false&orderCertain=true&lutLength=3&scaleFactor=1&images=1";
        String[] uriStrings = { ex1, ex2, ex3 };
        String[] fullUriStrings = { ex1Full, ex2Full, ex3Full };
        for (int i = 0; i < uriStrings.length; i++) {
            replacedertEquals(fullUriStrings[i], loc.resolve(uriStrings[i]).getURI().toString());
        }
    }
}

18 View Complete Implementation : FormatServiceTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
@Before
public void setUp() {
    final Context context = new Context();
    formatService = context.getService(FormatService.clreplaced);
}

18 View Complete Implementation : Main.java
Copyright BSD 2-Clause "Simplified" License
Author : imagej
// -- Main method --
public static void main(final String[] args) throws IOException {
    final Context context = new Context(OpService.clreplaced);
    final OpService ops = context.getService(OpService.clreplaced);
    new EvaluatorConsole(new OpEvaluator(ops)).showConsole();
}

18 View Complete Implementation : AbstractOpTest.java
Copyright BSD 2-Clause "Simplified" License
Author : imagej
/**
 * Base clreplaced for {@link Op} unit testing.
 * <p>
 * <i>All</i> {@link Op} unit tests need to have an {@link OpService} instance.
 * Following the DRY principle, we should implement it only once. Here.
 * </p>
 *
 * @author Johannes Schindelin
 * @author Curtis Rueden
 */
public abstract clreplaced AbstractOpTest {

    @Parameter
    protected Context context;

    @Parameter
    protected OpService ops;

    @Parameter
    protected OpMatchingService matcher;

    /**
     * Subclreplacedes can override to create a context with different services.
     */
    protected Context createContext() {
        return new Context(OpService.clreplaced, OpMatchingService.clreplaced, CacheService.clreplaced);
    }

    /**
     * Sets up a SciJava context with {@link OpService}.
     */
    @Before
    public void setUp() {
        createContext().inject(this);
    }

    /**
     * Disposes of the {@link OpService} that was initialized in {@link #setUp()}.
     */
    @After
    public synchronized void cleanUp() {
        if (context != null) {
            context.dispose();
            context = null;
            ops = null;
            matcher = null;
        }
    }

    private int seed;

    private int pseudoRandom() {
        return seed = 3170425 * seed + 132102;
    }

    public ArrayImg<BitType, LongArray> generateBitArrayTestImg(final boolean fill, final long... dims) {
        ArrayImg<BitType, LongArray> bits = ArrayImgs.bits(dims);
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (BitType b : bits) {
                b.set(betterRNG.nextBoolean());
            }
        }
        return bits;
    }

    public ArrayImg<Unsigned2BitType, LongArray> generateUnsigned2BitArrayTestImg(final boolean fill, final long... dims) {
        ArrayImg<Unsigned2BitType, LongArray> bits = ArrayImgs.unsigned2Bits(dims);
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (Unsigned2BitType b : bits) {
                b.set(betterRNG.nextLong());
            }
        }
        return bits;
    }

    public ArrayImg<Unsigned4BitType, LongArray> generateUnsigned4BitArrayTestImg(final boolean fill, final long... dims) {
        ArrayImg<Unsigned4BitType, LongArray> bits = ArrayImgs.unsigned4Bits(dims);
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (Unsigned4BitType b : bits) {
                b.set(betterRNG.nextLong());
            }
        }
        return bits;
    }

    public ArrayImg<Unsigned12BitType, LongArray> generateUnsigned12BitArrayTestImg(final boolean fill, final long... dims) {
        ArrayImg<Unsigned12BitType, LongArray> bits = ArrayImgs.unsigned12Bits(dims);
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (Unsigned12BitType b : bits) {
                b.set(betterRNG.nextLong());
            }
        }
        return bits;
    }

    public ArrayImg<Unsigned128BitType, LongArray> generateUnsigned128BitArrayTestImg(final boolean fill, final long... dims) {
        ArrayImg<Unsigned128BitType, LongArray> bits = ArrayImgs.unsigned128Bits(dims);
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (Unsigned128BitType b : bits) {
                BigInteger big = BigInteger.valueOf(betterRNG.nextLong());
                b.set(big);
            }
        }
        return bits;
    }

    public ArrayImg<ByteType, ByteArray> generateByteArrayTestImg(final boolean fill, final long... dims) {
        final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (byte) pseudoRandom();
            }
        }
        return ArrayImgs.bytes(array, dims);
    }

    public ArrayImg<UnsignedByteType, ByteArray> generateUnsignedByteArrayTestImg(final boolean fill, final long... dims) {
        final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (byte) pseudoRandom();
            }
        }
        return ArrayImgs.unsignedBytes(array, dims);
    }

    public ArrayImg<IntType, IntArray> generateIntArrayTestImg(final boolean fill, final long... dims) {
        final int[] array = new int[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (int) pseudoRandom() / (int) Integer.MAX_VALUE;
            }
        }
        return ArrayImgs.ints(array, dims);
    }

    public ArrayImg<UnsignedIntType, IntArray> generateUnsignedIntArrayTestImg(final boolean fill, final long... dims) {
        final int[] array = new int[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (int) pseudoRandom() / (int) Integer.MAX_VALUE;
            }
        }
        return ArrayImgs.unsignedInts(array, dims);
    }

    public CellImg<ByteType, ?> generateByteTestCellImg(final boolean fill, final long... dims) {
        final CellImg<ByteType, ?> img = new CellImgFactory<ByteType>().create(dims, new ByteType());
        if (fill) {
            final Cursor<ByteType> c = img.cursor();
            while (c.hasNext()) c.next().set((byte) pseudoRandom());
        }
        return img;
    }

    public CellImg<ByteType, ?> generateByteTestCellImg(final boolean fill, final int[] cellDims, final long... dims) {
        final CellImg<ByteType, ?> img = new CellImgFactory<ByteType>(cellDims).create(dims, new ByteType());
        if (fill) {
            final Cursor<ByteType> c = img.cursor();
            while (c.hasNext()) c.next().set((byte) pseudoRandom());
        }
        return img;
    }

    public ArrayImg<DoubleType, DoubleArray> generateDoubleArrayTestImg(final boolean fill, final long... dims) {
        final double[] array = new double[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (double) pseudoRandom() / (double) Integer.MAX_VALUE;
            }
        }
        return ArrayImgs.doubles(array, dims);
    }

    public ArrayImg<LongType, LongArray> generateLongArrayTestImg(final boolean fill, final long... dims) {
        final long[] array = new long[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (long) (pseudoRandom() / Integer.MAX_VALUE);
            }
        }
        return ArrayImgs.longs(array, dims);
    }

    public ArrayImg<UnsignedLongType, LongArray> generateUnsignedLongArrayTestImg(final boolean fill, final long... dims) {
        final long[] array = new long[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (long) (pseudoRandom() / Integer.MAX_VALUE);
            }
        }
        return ArrayImgs.unsignedLongs(array, dims);
    }

    public ArrayImg<ShortType, ShortArray> generateShortArrayTestImg(final boolean fill, final long... dims) {
        final short[] array = new short[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (short) (pseudoRandom() / Integer.MAX_VALUE);
            }
        }
        return ArrayImgs.shorts(array, dims);
    }

    public ArrayImg<UnsignedShortType, ShortArray> generateUnsignedShortArrayTestImg(final boolean fill, final long... dims) {
        final short[] array = new short[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (short) (pseudoRandom() / Integer.MAX_VALUE);
            }
        }
        return ArrayImgs.unsignedShorts(array, dims);
    }

    public ArrayImg<UnsignedVariableBitLengthType, LongArray> generateUnsignedVariableBitLengthTypeArrayTestImg(final boolean fill, final int nbits, final long... dims) {
        final long[] array = new long[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (long) (((pseudoRandom() / Integer.MAX_VALUE)) % (Math.pow(2, nbits)));
            }
        }
        final LongArray l = new LongArray(array);
        return ArrayImgs.unsignedVariableBitLengths(l, nbits, dims);
    }

    public ListImg<UnboundedIntegerType> generateUnboundedIntegerTypeListTestImg(final boolean fill, final long... dims) {
        final ListImg<UnboundedIntegerType> l = new ListImgFactory<UnboundedIntegerType>().create(dims, new UnboundedIntegerType());
        final BigInteger[] array = new BigInteger[(int) Intervals.numElements(dims)];
        RandomAccess<UnboundedIntegerType> ra = l.randomAccess();
        if (fill) {
            MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
            for (int i = 0; i < Intervals.numElements(dims); i++) {
                BigInteger val = BigInteger.valueOf(betterRNG.nextLong());
                ra.get().set(val);
                ra.fwd(0);
            }
        }
        return l;
    }

    public Img<UnsignedByteType> generateRandomlyFilledUnsignedByteTestImgWithSeed(final long[] dims, final long tempSeed) {
        final Img<UnsignedByteType> img = ArrayImgs.unsignedBytes(dims);
        final Random rand = new Random(tempSeed);
        final Cursor<UnsignedByteType> cursor = img.cursor();
        while (cursor.hasNext()) {
            cursor.next().set(rand.nextInt((int) img.firstElement().getMaxValue()));
        }
        return img;
    }

    public ArrayImg<FloatType, FloatArray> generateFloatArrayTestImg(final boolean fill, final long... dims) {
        final float[] array = new float[(int) Intervals.numElements(new FinalInterval(dims))];
        if (fill) {
            seed = 17;
            for (int i = 0; i < array.length; i++) {
                array[i] = (float) pseudoRandom() / (float) Integer.MAX_VALUE;
            }
        }
        return ArrayImgs.floats(array, dims);
    }

    public Img<FloatType> openFloatImg(final String resourcePath) {
        return openFloatImg(getClreplaced(), resourcePath);
    }

    public Img<DoubleType> openDoubleImg(final String resourcePath) {
        return openDoubleImg(getClreplaced(), resourcePath);
    }

    public static Img<FloatType> openFloatImg(final Clreplaced<?> c, final String resourcePath) {
        final URL url = c.getResource(resourcePath);
        return IO.openFloatImgs(url.getPath()).get(0).getImg();
    }

    public static Img<UnsignedByteType> openUnsignedByteType(final Clreplaced<?> c, final String resourcePath) {
        final URL url = c.getResource(resourcePath);
        return IO.openUnsignedByteImgs(url.getPath()).get(0).getImg();
    }

    public static Img<DoubleType> openDoubleImg(final Clreplaced<?> c, final String resourcePath) {
        final URL url = c.getResource(resourcePath);
        return IO.openDoubleImgs(url.getPath()).get(0).getImg();
    }

    public <T> void replacederreplacederationsEqual(final Iterable<T> expected, final Iterable<T> actual) {
        final Iterator<T> e = expected.iterator();
        final Iterator<T> a = actual.iterator();
        while (e.hasNext()) {
            replacedertTrue("Fewer elements than expected", a.hasNext());
            replacedertEquals(e.next(), a.next());
        }
        replacedertFalse("More elements than expected", a.hasNext());
    }

    public static <T> RandomAccessible<T> deinterval(RandomAccessibleInterval<T> input) {
        return Views.extendBorder(input);
    }

    public <T extends RealType<T>> boolean areCongruent(final IterableInterval<T> in, final RandomAccessible<T> out, final double epsilon) {
        Cursor<T> cin = in.localizingCursor();
        RandomAccess<T> raOut = out.randomAccess();
        while (cin.hasNext()) {
            cin.fwd();
            raOut.setPosition(cin);
            if (Math.abs(cin.get().getRealDouble() - raOut.get().getRealDouble()) > epsilon)
                return false;
        }
        return true;
    }

    public <T extends RealType<T>> double[] asArray(final Iterable<T> image) {
        return StreamSupport.stream(image.spliterator(), false).mapToDouble(t -> t.getRealDouble()).toArray();
    }

    public static clreplaced NoOp extends AbstractOp {

        @Override
        public void run() {
        // NB: No implementation needed.
        }
    }
}

18 View Complete Implementation : SciJavaUtils.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static <T extends SciJavaPlugin> List<? extends PluginInfo<T>> getAllMatchingPluginInfos(final Clreplaced<T> clazz, final Context context) {
    return getAllMatchingPluginInfos(clazz, context.getService(PluginService.clreplaced));
}

18 View Complete Implementation : IO.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
// -- Helper methods --
/**
 * Registers the given ImgPlus with the RefManagerService in the provided
 * component's Context.
 */
private static void register(final List<? extends SCIFIOImgPlus> imgPlus, final AbstractImgIOComponent component) {
    final Context ctx = component.getContext();
    final RefManagerService refManagerService = ctx.getService(RefManagerService.clreplaced);
    for (final SCIFIOImgPlus<?> img : imgPlus) {
        refManagerService.manage(img, ctx);
    }
}

17 View Complete Implementation : ScriptInstaller.java
Copyright GNU General Public License v3.0
Author : fiji
/**
 * Utility clreplaced for discovery of scripts scripting SNT
 *
 * @author Tiago Ferreira
 */
clreplaced ScriptInstaller implements MenuKeyListener {

    @Parameter
    private Context context;

    @Parameter
    private ScriptService scriptService;

    private final SNTUI ui;

    private final TreeSet<ScriptInfo> scripts;

    private boolean openInsteadOfRun;

    protected ScriptInstaller(final Context context, final SNTUI ui) {
        context.inject(this);
        this.ui = ui;
        scripts = new TreeSet<>(Comparator.comparing(this::getScriptLabel));
        // 1. Include script_templates that are not discovered by ScriptService
        final Map<String, URL> map = FileUtils.findResources(null, "script_templates/Neuroanatomy", null);
        if (map != null) {
            map.forEach((k, v) -> {
                try {
                    if (!k.toLowerCase().contains("boilerplate"))
                        scripts.add(new ScriptInfo(context, v, k));
                } catch (final IOException ignored) {
                // just skip file
                }
            });
        }
        // 2. Parse discovered scripts
        addAllDiscoveredScripts();
        // 3. Include all other scripts
        addLocalScripts();
    }

    private void addLocalScripts() {
        // Do a second preplaced in case scripts outside the plugins directory are missing
        final File dir = getScriptsDir();
        if (dir == null)
            return;
        final File[] filteredScripts = dir.listFiles((file) -> {
            final ScriptLanguage lang = scriptService.getLanguageByExtension(FileUtils.getExtension(file));
            if (lang == null)
                return false;
            final String name = file.getName();
            return file.canRead() && (name.contains("SNT") || name.toLowerCase().contains("neuroanatomy"));
        });
        if (filteredScripts != null) {
            for (final File file : filteredScripts) {
                final ScriptInfo si = scriptService.getScript(file);
                if (si != null) {
                    scripts.add(si);
                }
            }
        }
    }

    private String getScriptsDirPath() {
        File dir = getScriptsDir();
        return (dir == null) ? null : dir.getAbsolutePath();
    }

    private File getScriptsDir() {
        final List<File> dirs = scriptService.getScriptDirectories();
        for (final File dir : dirs) {
            if (!dir.getAbsolutePath().contains("plugins"))
                return dir;
        }
        return null;
    }

    private void addAllDiscoveredScripts() {
        for (final ScriptInfo si : scriptService.getScripts()) {
            final boolean pathMatch = si.getPath() != null && (si.getPath().contains("SNT") || si.getPath().toLowerCase().contains("neuroanatomy"));
            if (pathMatch)
                scripts.add(si);
        }
    }

    private void runScript(final ScriptInfo si) {
        ui.showStatus("Running script...", false);
        final Future<ScriptModule> fsm = scriptService.run(si, true, (Map<String, Object>) null);
        if (fsm.isCancelled()) {
            ui.showStatus("Script canceled...", true);
        } else if (fsm.isDone()) {
            ui.showStatus("Script completed...", true);
        }
    }

    private void openScript(final ScriptInfo si) {
        ui.showStatus("Opening script...", false);
        final TextEditor editor = new TextEditor(context);
        final BufferedReader reader = si.getReader();
        if (reader == null) {
            // local file
            editor.open(new File(si.getPath()));
        } else {
            // jar file
            try {
                final StringBuilder stringBuffer = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line).append("\n");
                }
                editor.createNewDoreplacedent(getScriptLabel(si), stringBuffer.toString());
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        editor.setVisible(true);
        ui.showStatus("", false);
    }

    private JMenu getMenu(final String folder, final boolean trimExtension) {
        final JMenu sMenu = new JMenu((folder == null) ? "Full List" : folder);
        sMenu.addMenuKeyListener(this);
        for (final ScriptInfo si : scripts) {
            final String path = si.getPath();
            if (path == null || (folder != null && !path.contains(folder)))
                continue;
            final JMenuItem mItem = new JMenuItem(getScriptLabel(si, trimExtension));
            sMenu.add(mItem);
            mItem.addMenuKeyListener(this);
            mItem.addActionListener(e -> {
                final int mods = e.getModifiers();
                if (openInsteadOfRun || (mods & InputEvent.SHIFT_MASK) != 0 || (mods & InputEvent.SHIFT_DOWN_MASK) != 0) {
                    openScript(si);
                } else {
                    runScript(si);
                }
                openInsteadOfRun = false;
            });
        }
        return sMenu;
    }

    /**
     * Returns a UI list of SNT's 'Batch' scripts *
     */
    protected JMenu getBatchScriptsMenu() {
        final JMenu menu = getMenu("Batch", true);
        for (int i = 0; i < menu.gereplacedemCount(); i++) {
            final JMenuItem mItem = menu.gereplacedem(i);
            mItem.setText(SNTUtils.stripExtension(mItem.getText()) + "...");
        }
        return menu;
    }

    /**
     * Returns a UI list with all available scripts scripting SNT *
     */
    protected JMenu getScriptsMenu() {
        final JMenu sMenu = new JMenu("Scripts");
        sMenu.add(getMenu("replacedysis", true));
        sMenu.add(getMenu("Batch", true));
        sMenu.add(getMenu("Tracing", true));
        final JMenu listMenu = getFullListMenu();
        final int listMenuPosition = sMenu.gereplacedemCount();
        sMenu.add(listMenu);
        sMenu.addSeparator();
        final JMenuItem mi = new JMenuItem("New...", IconFactory.getMenuIcon(GLYPH.CODE));
        mi.addActionListener(e -> {
            final TextEditor editor = new TextEditor(context);
            final HashMap<String, String> map = new HashMap<>();
            map.put("BeanShell", "BSH.bsh");
            map.put("Groovy", "GVY.groovy");
            map.put("Python", "PY.py");
            final String choice = new GuiUtils(ui).getChoice("Language:", "New Script", map.keySet().toArray(new String[map.keySet().size()]), "");
            final ClreplacedLoader clreplacedloader = Thread.currentThread().getContextClreplacedLoader();
            boolean save = true;
            try {
                editor.loadTemplate(clreplacedloader.getResource("script_templates/Neuroanatomy/Boilerplate/" + map.get(choice)));
            } catch (final NullPointerException ignored) {
                ui.error("Boilerpate script could not be retrieved. Use Script Editor's Templates>Neuroanatomy> instead.");
                save = false;
            } finally {
                editor.setVisible(true);
                if (save)
                    editor.saveAs(getScriptsDir() + File.separator + "_SNT_script." + FileUtils.getExtension(map.get(choice)));
            }
        });
        sMenu.add(mi);
        final JMenuItem reloadMI = new JMenuItem("Reload...", IconFactory.getMenuIcon(GLYPH.REDO));
        reloadMI.addActionListener(e -> {
            final int oldCount = scripts.size();
            addLocalScripts();
            final int newCount = scripts.size();
            if (oldCount == newCount) {
                ui.guiUtils.centeredMsg("No new scripts detected.", "List Reloaded");
                return;
            }
            sMenu.remove(listMenuPosition);
            sMenu.add(getFullListMenu(), listMenuPosition);
            sMenu.revalidate();
            ui.guiUtils.centeredMsg("" + (newCount - oldCount) + " new script(s) added to \"Scripts>Full List>\".", "New Script(s) Detected");
        });
        sMenu.add(reloadMI);
        sMenu.addSeparator();
        sMenu.add(about());
        return sMenu;
    }

    private JMenu getFullListMenu() {
        final JMenu listMenu = getMenu(null, false);
        listMenu.setIcon(IconFactory.getMenuIcon(IconFactory.GLYPH.LIST));
        return listMenu;
    }

    private String getScriptLabel(final ScriptInfo si, final boolean trimExtension) {
        final String label = (trimExtension) ? SNTUtils.stripExtension(getScriptLabel(si)) : getScriptLabel(si);
        return label.replace('_', ' ');
    }

    private String getScriptLabel(final ScriptInfo si) {
        String label = si.getLabel();
        if (label != null)
            return label;
        label = si.getName();
        if (label != null)
            return label;
        label = si.getPath();
        if (label != null)
            return label.substring(label.lastIndexOf(File.separator) + 1);
        // never null
        return si.getIdentifier();
    }

    private JMenuItem about() {
        final JMenuItem mItem = new JMenuItem("About SNT Scripts...");
        mItem.setIcon(IconFactory.getMenuIcon(IconFactory.GLYPH.QUESTION));
        mItem.addActionListener(e -> {
            ui.guiUtils.centeredMsg("This menu lists scripting routines that enhance SNT functionality. " + "The list is automatically populated at startup.<br><br>" + "To have your own scripts listed here, save them in the <tt>scripts</tt> " + "directory while including <i>SNT</i> in the filename (e.g., <tt>" + getScriptsDirPath() + File.separator + "My_SNT_script.py</tt>) <br><br>" + "To edit a listed script hold \"Shift\" while clicking on its menu entry.<br><br>" + "Several programming examples are available through the Script Editor's " + "<i>Templates>Neuroanatomy></i> menu.  Please submit a pull request to SNT's " + "repository if you would like to have your scripts distributed with Fiji.", "About SNT Scripts...");
        });
        return mItem;
    }

    @Override
    public void menuKeyTyped(final MenuKeyEvent e) {
    // ignored
    }

    @Override
    public void menuKeyPressed(final MenuKeyEvent e) {
        openInsteadOfRun = e.isShiftDown();
    }

    @Override
    public void menuKeyReleased(final MenuKeyEvent e) {
        openInsteadOfRun = e.isShiftDown();
    }
}

17 View Complete Implementation : ImageJServer.java
Copyright Apache License 2.0
Author : imagej
/**
 * Entry point to imagej-server.
 *
 * @author Leon Yang
 */
public clreplaced ImageJServer extends Application<ImageJServerConfiguration> {

    private final Context ctx;

    private final ObjectService objectService;

    private final JsonService jsonService;

    private Environment env;

    public ImageJServer(final Context ctx) {
        this.ctx = ctx;
        objectService = new DefaultObjectService();
        jsonService = new DefaultJsonService(objectService);
    }

    @Override
    public String getName() {
        return "ImageJ";
    }

    @Override
    public void initialize(final Bootstrap<ImageJServerConfiguration> bootstrap) {
        jsonService.addDeserializerTo(bootstrap.getObjectMapper());
    }

    @Override
    public void run(final ImageJServerConfiguration configuration, final Environment environment) {
        // Enable CORS headers
        final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.clreplaced);
        // Configure CORS parameters
        cors.setInitParameter("allowedOrigins", "*");
        cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
        cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
        // Add URL mapping
        cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.clreplaced), true, "/*");
        env = environment;
        // NB: not implemented yet
        final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
        environment.healthChecks().register("imagej-server", healthCheck);
        environment.jersey().register(MultiPartFeature.clreplaced);
        // -- resources --
        environment.jersey().register(AdminResource.clreplaced);
        environment.jersey().register(ModulesResource.clreplaced);
        environment.jersey().register(ObjectsResource.clreplaced);
        // -- context dependencies injection --
        environment.jersey().register(new AbstractBinder() {

            @Override
            protected void configure() {
                bind(ctx).to(Context.clreplaced);
                bind(env).to(Environment.clreplaced);
                bind(objectService).to(ObjectService.clreplaced);
                bind(jsonService).to(JsonService.clreplaced);
            }
        });
    }

    public void stop() throws Exception {
        if (env == null)
            return;
        env.getApplicationContext().getServer().stop();
    }

    public void join() throws InterruptedException {
        if (env == null)
            return;
        env.getApplicationContext().getServer().join();
    }
}

17 View Complete Implementation : GsonHelpers.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static GsonBuilder builderWithAllRequiredDeserializers(final Context context, final PainteraBaseView viewer, final Supplier<String> projectDirectory) throws InstantiableException {
    final IntFunction<SourceState<?, ?>> dependencyFromIndex = index -> viewer.sourceInfo().getState(viewer.sourceInfo().trackSources().get(index));
    return builderWithAllRequiredDeserializers(context, new Arguments(viewer), projectDirectory, dependencyFromIndex);
}

17 View Complete Implementation : GsonHelpers.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static GsonBuilder builderWithAllRequiredDeserializers(final Context context, final Arguments arguments, final Supplier<String> projectDirectory, final IntFunction<SourceState<?, ?>> dependencyFromIndex) {
    final Map<Clreplaced<?>, List<Pair<PainteraSerialization.PainteraDeserializer, Double>>> deserializers = PainteraSerialization.getDeserializers(context);
    final Map<Clreplaced<?>, List<Pair<StatefulSerializer.DeserializerFactory, Double>>> deserializerFactories = StatefulSerializer.getDeserializers(context);
    final GsonBuilder builder = new GsonBuilder();
    for (final Map.Entry<Clreplaced<?>, List<Pair<PainteraSerialization.PainteraDeserializer, Double>>> d : deserializers.entrySet()) {
        final PainteraSerialization.PainteraDeserializer<?> v = d.getValue().get(0).getKey();
        LOG.debug("Adding deserializer for clreplaced {} ({})", d.getKey(), v.isHierarchyAdapter());
        if (v.isHierarchyAdapter())
            builder.registerTypeHierarchyAdapter(d.getKey(), v);
        else
            builder.registerTypeAdapter(d.getKey(), v);
    }
    for (final Map.Entry<Clreplaced<?>, List<Pair<StatefulSerializer.DeserializerFactory, Double>>> d : deserializerFactories.entrySet()) {
        final StatefulSerializer.DeserializerFactory<?, ?> v = d.getValue().get(0).getKey();
        LOG.debug("Adding deserializer factory for clreplaced {}", d.getKey());
        builder.registerTypeAdapter(d.getKey(), v.createDeserializer(arguments, projectDirectory, dependencyFromIndex));
    }
    return builder;
}

17 View Complete Implementation : CheckerTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Unit tests for {@link io.scif.Checker} interface methods.
 *
 * @author Mark Hiner
 */
public clreplaced CheckerTest {

    private final Location id = new TestImgLocation.Builder().name("8bit-signed").pixelType("int8").axes("X", "Y", "Z", "C", "T").lengths(50, 50, 4, 5, 7).build();

    private final Location falseId = new DummyLocation();

    private Checker c;

    private FakeChecker fc;

    private Context context;

    private DataHandleService dataHandleService;

    @Before
    public void setUp() throws FormatException {
        context = new Context();
        final SCIFIO scifio = new SCIFIO();
        final Format f = scifio.format().getFormat(id);
        c = f.createChecker();
        fc = new FakeChecker();
        fc.setContext(context);
        dataHandleService = context.getService(DataHandleService.clreplaced);
    }

    @Test
    public void isFormatTests() throws IOException {
        boolean isFormat = false;
        isFormat = c.isFormat(id);
        replacedertTrue(isFormat);
        isFormat = c.isFormat(id, new SCIFIOConfig().checkerSetOpen(false));
        replacedertTrue(isFormat);
        isFormat = c.isFormat(id, new SCIFIOConfig().checkerSetOpen(true));
        replacedertTrue(isFormat);
        isFormat = c.isFormat(falseId, new SCIFIOConfig().checkerSetOpen(false));
        replacedertFalse(isFormat);
    }

    @Test
    public void checkHeaderTest() {
        boolean isFormat = false;
        isFormat = c.checkHeader(id.getName().getBytes());
        replacedertFalse(isFormat);
    }

    @Test
    public void suffixSufficientTests() throws IOException {
        // test with suffix sufficient
        fc.setSuffixSufficient(true);
        boolean isFormat = false;
        isFormat = fc.isFormat(id);
        replacedertTrue(isFormat);
        isFormat = fc.isFormat(id, new SCIFIOConfig().checkerSetOpen(false));
        replacedertTrue(isFormat);
        isFormat = fc.isFormat(id, new SCIFIOConfig().checkerSetOpen(true));
        replacedertTrue(isFormat);
        // test with suffix not sufficient
        // will return false because we can not open handles on TestImgLocation
        fc.setSuffixSufficient(false);
        isFormat = fc.isFormat(id);
        replacedertFalse(isFormat);
        isFormat = fc.isFormat(id, new SCIFIOConfig().checkerSetOpen(false));
        replacedertFalse(isFormat);
        isFormat = fc.isFormat(id, new SCIFIOConfig().checkerSetOpen(true));
        replacedertFalse(isFormat);
        isFormat = fc.checkHeader(id.getName().getBytes());
        replacedertTrue(isFormat);
    }

    @Test
    public void hasContextTests() {
        replacedertNotNull(c.getContext());
    }

    public void hasFormatTests() {
        final Format format = c.getFormat();
        replacedertNotNull(format);
        replacedertEquals(c.getFormat().getCheckerClreplaced(), c.getClreplaced());
    }

    @After
    public void tearDown() {
        context = null;
        c = null;
        fc = null;
    }

    /*
	 * Private inner clreplaced for testing suffix flags.
	 *
	 * @author Mark Hiner
	 */
    private static clreplaced FakeChecker extends io.scif.DefaultChecker {

        private boolean suffixSufficient = false;

        // -- FakeChecker Methods --
        public void setSuffixSufficient(final boolean s) {
            suffixSufficient = s;
        }

        @Override
        public boolean suffixSufficient() {
            return suffixSufficient;
        }

        @Override
        public boolean isFormat(final DataHandle<Location> stream) throws IOException {
            return true;
        }

        // -- HasFormat Methods --
        // When extending an existing component, the getFormat() method should
        // be overriden to ensure the proper format is returned.
        // FIXME: index over all components? make Format.createComponent work
        // more like services where
        // you can have a list of components returned... maybe? Or not..
        @Override
        public Format getFormat() {
            final SCIFIO scifio = new SCIFIO(getContext());
            return scifio.format().getFormatFromClreplaced(TestImgFormat.clreplaced);
        }
    }
}

16 View Complete Implementation : InstallScijavaKernel.java
Copyright Apache License 2.0
Author : scijava
public static void main(String... args) {
    Context context = new Context();
    LogService log = context.service(LogService.clreplaced);
    log.setLevel(LogLevel.INFO);
    JupyterService jupyter = context.service(JupyterService.clreplaced);
    jupyter.installKernel(args);
    context.dispose();
}

16 View Complete Implementation : ScijavaKernel.java
Copyright Apache License 2.0
Author : scijava
public static void main(String... args) {
    final Context context = new Context();
    // Remove the Display and Results post-processors to prevent output
    // windows from being displayed
    final PluginService pluginService = context.service(PluginService.clreplaced);
    final PluginInfo<SciJavaPlugin> display = pluginService.getPlugin(DisplayPostprocessor.clreplaced);
    final PluginInfo<SciJavaPlugin> results = pluginService.getPlugin(ResultsPostprocessor.clreplaced);
    pluginService.removePlugin(display);
    pluginService.removePlugin(results);
    JupyterService jupyter = context.service(JupyterService.clreplaced);
    jupyter.runKernel(args);
    context.dispose();
}

16 View Complete Implementation : ScijavaKernel.java
Copyright Apache License 2.0
Author : scijava
/**
 * @author Hadrien Mary
 */
public clreplaced ScijavaKernel extends Kernel {

    // Scijava context
    Context context;

    @Parameter
    private transient LogService log;

    private final ScijavaKernelConfigurationFile config;

    public ScijavaKernel(final Context context, final String id, final ScijavaEvaluator evaluator, ScijavaKernelConfigurationFile config, KernelSocketsFactory kernelSocketsFactory) {
        super(id, evaluator, kernelSocketsFactory);
        this.context = context;
        this.context.inject(this);
        this.config = config;
        // Don't show output when it is null
        Kernel.showNullExecutionResult = false;
        this.setLogLevel(config.getLogLevel());
        log.info("Log level used is : " + this.config.getLogLevel());
        log.info("Scijava Kernel is started and ready to use.");
    }

    @Override
    public CommOpenHandler getCommOpenHandler(Kernel kernel) {
        return new ScijavaCommOpenHandler(kernel);
    }

    @Override
    public KernelHandler<Message> getKernelInfoHandler(Kernel kernel) {
        return new ScijavaKernelInfoHandler(kernel);
    }

    private void setLogLevel(String logLevel) {
        switch(logLevel) {
            case "debug":
                this.log.setLevel(LogLevel.DEBUG);
                break;
            case "error":
                this.log.setLevel(LogLevel.ERROR);
                break;
            case "info":
                this.log.setLevel(LogLevel.INFO);
                break;
            case "none":
                this.log.setLevel(LogLevel.NONE);
                break;
            default:
                this.log.setLevel(LogLevel.INFO);
                break;
        }
    }

    public static void main(String... args) {
        final Context context = new Context();
        // Remove the Display and Results post-processors to prevent output
        // windows from being displayed
        final PluginService pluginService = context.service(PluginService.clreplaced);
        final PluginInfo<SciJavaPlugin> display = pluginService.getPlugin(DisplayPostprocessor.clreplaced);
        final PluginInfo<SciJavaPlugin> results = pluginService.getPlugin(ResultsPostprocessor.clreplaced);
        pluginService.removePlugin(display);
        pluginService.removePlugin(results);
        JupyterService jupyter = context.service(JupyterService.clreplaced);
        jupyter.runKernel(args);
        context.dispose();
    }
}

16 View Complete Implementation : SWCTypeFilterCmd.java
Copyright GNU General Public License v3.0
Author : fiji
public static Set<Integer> getChosenTypes(final Context context) {
    final String stringTypes = context.getService(PrefService.clreplaced).get(SWCTypeFilterCmd.clreplaced, CHOSEN_TYPES, "");
    if (stringTypes.isEmpty())
        return null;
    final Set<Integer> set = new HashSet<>();
    for (final char c : stringTypes.toCharArray()) {
        set.add(Character.getNumericValue(c));
    }
    return set;
}

16 View Complete Implementation : SNTUtils.java
Copyright GNU General Public License v3.0
Author : fiji
/**
 * Static utilities for SNT *
 */
public clreplaced SNTUtils {

    private static Context context;

    private static LogService logService;

    private static UIService uiService;

    public static final String VERSION = getVersion();

    private static boolean initialized;

    private static SNT plugin;

    private static HashMap<Integer, Viewer3D> viewerMap;

    private SNTUtils() {
    }

    private synchronized static void initialize() {
        if (initialized)
            return;
        if (context == null)
            context = (Context) IJ.runPlugIn("org.scijava.Context", "");
        if (logService == null)
            logService = context.getService(LogService.clreplaced);
        if (uiService == null)
            uiService = context.getService(UIService.clreplaced);
        initialized = true;
    }

    public static String getReadableVersion() {
        if (VERSION.length() < 21)
            return "SNT " + VERSION;
        return "SNT " + VERSION.substring(0, 21) + "...";
    }

    private static String getVersion() {
        return VersionUtils.getVersion(SNT.clreplaced);
    }

    public static synchronized void addViewer(final Viewer3D viewer) {
        if (viewerMap == null)
            viewerMap = new HashMap<>();
        viewerMap.put(viewer.getID(), viewer);
    }

    public static synchronized void removeViewer(final Viewer3D viewer) {
        if (viewerMap != null && viewer != null)
            viewerMap.values().removeIf(viewer::equals);
    }

    protected static HashMap<Integer, Viewer3D> getViewers() {
        return viewerMap;
    }

    protected static synchronized void error(final String string) {
        if (SNTUtils.isDebugMode())
            nonDebugError(string);
    }

    protected static void setPlugin(final SNT plugin) {
        SNTUtils.plugin = plugin;
        if (context == null && plugin != null)
            context = plugin.getContext();
    }

    public static SNT getPluginInstance() {
        return plugin;
    }

    protected static synchronized void nonDebugError(final String string) {
        if (!initialized)
            initialize();
        logService.error("[SNT] " + string);
    }

    public static synchronized void error(final String string, final Throwable t) {
        if (!SNTUtils.isDebugMode())
            return;
        if (!initialized)
            initialize();
        logService.error("[SNT] " + string, t);
    }

    public static synchronized void log(final String string) {
        if (!SNTUtils.isDebugMode())
            return;
        if (!initialized)
            initialize();
        logService.info("[SNT] " + string);
    }

    protected static synchronized void warn(final String string) {
        if (!SNTUtils.isDebugMode())
            return;
        if (!initialized)
            initialize();
        logService.warn("[SNT] " + string);
    }

    protected static void convertTo32bit(final ImagePlus imp) throws IllegalArgumentException {
        if (imp.getBitDepth() == 32)
            return;
        if (imp.getNSlices() == 1)
            new ImageConverter(imp).convertToGray32();
        else
            new StackConverter(imp).convertToGray32();
    }

    public static void convertTo8bit(final ImagePlus imp) {
        if (imp.getType() != ImagePlus.GRAY8) {
            final boolean doScaling = ImageConverter.getDoScaling();
            ImageConverter.setDoScaling(true);
            new ImageConverter(imp).convertToGray8();
            ImageConverter.setDoScaling(doScaling);
        }
    }

    public static ImagePlus getMIP(final ImagePlus imp) {
        final ImagePlus mip = ZProjector.run(imp, "max");
        new ContrastEnhancer().stretchHistogram(mip, 0.35);
        return mip;
    }

    public static String tableToString(final GenericTable table, final int firstRow, final int lastRow) {
        final int fRow = Math.max(0, firstRow);
        final int lRow = Math.min(table.getRowCount() - 1, lastRow);
        final String sep = "\t";
        final StringBuilder sb = new StringBuilder();
        IntStream.range(0, table.getColumnCount()).forEach(col -> {
            sb.append(table.getColumnHeader(col)).append(sep);
        });
        sb.append("\n\r");
        IntStream.rangeClosed(fRow, lRow).forEach(row -> {
            IntStream.range(0, table.getColumnCount()).forEach(col -> {
                sb.append(table.get(col, row)).append(sep);
            });
            sb.append("\n\r");
        });
        return sb.toString().replaceAll("null", " ");
    }

    public static void csvQuoteAndPrint(final PrintWriter pw, final Object o) {
        pw.print(stringForCSV("" + o));
    }

    private static String stringForCSV(final String s) {
        boolean quote = false;
        String result = s;
        if (s.indexOf(',') >= 0 || s.indexOf(' ') >= 0)
            quote = true;
        if (s.indexOf('"') >= 0) {
            quote = true;
            result = s.replaceAll("\"", "\"\"");
        }
        if (quote)
            return "\"" + result + "\"";
        else
            return result;
    }

    protected static String getColorString(final Color color) {
        String name = "none";
        name = Colors.getColorName(color, name);
        if (!"none".equals(name))
            name = Colors.colorToString(color);
        return name;
    }

    protected static Color getColor(String colorName) {
        if (colorName == null)
            colorName = "none";
        Color color = null;
        color = Colors.getColor(colorName, color);
        if (color == null)
            color = Colors.decode(colorName, color);
        return color;
    }

    public static String stripExtension(final String filename) {
        final int lastDot = filename.lastIndexOf(".");
        return (lastDot > 0) ? filename.substring(0, lastDot) : filename;
    }

    protected static boolean fileAvailable(final File file) {
        try {
            return file != null && file.exists();
        } catch (final SecurityException ignored) {
            return false;
        }
    }

    protected static boolean isValidURL(final String url) {
        try {
            new URL(url).toURI();
            return true;
        } catch (final Exception e) {
            return false;
        }
    }

    public static String formatDouble(final double value, final int digits) {
        return (Double.isNaN(value)) ? "NaN" : getDecimalFormat(value, digits).format(value);
    }

    public static DecimalFormat getDecimalFormat(final double value, final int digits) {
        StringBuilder pattern = new StringBuilder("0.");
        while (pattern.length() < digits + 2) pattern.append("0");
        final double absValue = Math.abs(value);
        if ((absValue > 0 && absValue < 0.01) || absValue >= 1000)
            pattern.append("E0");
        final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
        final DecimalFormat df = (DecimalFormat) nf;
        return df;
    }

    /**
     * replacedesses if SNT is running in debug mode
     *
     * @return the debug flag
     */
    public static boolean isDebugMode() {
        return SNT.verbose;
    }

    /**
     * Enables/disables debug mode
     *
     * @param b verbose flag
     */
    public static void setDebugMode(final boolean b) {
        if (isDebugMode() && !b) {
            log("Exiting debug mode...");
        }
        SNT.verbose = b;
        if (isDebugMode()) {
            // will initialize uiService
            log("Entering debug mode...");
            final ConsolePane<?> console = uiService.getDefaultUI().getConsolePane();
            if (console != null)
                console.show();
        }
    }

    public static File findClosestPair(final File file, final String pairExt) {
        try {
            SNTUtils.log("Finding closest pair for " + file);
            final File dir = file.getParentFile();
            final String[] list = dir.list((f, s) -> s.endsWith(pairExt));
            SNTUtils.log("Found " + list.length + " " + pairExt + " files");
            if (list.length == 0)
                return null;
            Arrays.sort(list);
            String dirPath = dir.getAbsolutePath();
            if (!dirPath.endsWith(File.separator))
                dirPath += File.separator;
            int cost = Integer.MAX_VALUE;
            final String seed = stripExtension(file.getName().toLowerCase());
            String closest = null;
            final Levenshtein levenshtein = new Levenshtein(5, 10, 1, 5, 5, 0);
            for (final String item : list) {
                final String filename = stripExtension(Paths.get(item).getFileName().toString()).toLowerCase();
                final int currentCost = levenshtein.cost(seed, filename);
                SNTUtils.log("Levenshtein cost for '" + item + "': " + currentCost);
                if (currentCost <= cost) {
                    cost = currentCost;
                    closest = item;
                }
            }
            SNTUtils.log("Identified pair '" + closest + "'");
            return new File(dirPath + closest);
        } catch (final SecurityException | NullPointerException ignored) {
            return null;
        }
    }

    public static boolean similarCalibrations(final Calibration a, final Calibration b) {
        double ax = 1, ay = 1, az = 1;
        double bx = 1, by = 1, bz = 1;
        String aunit = "", bunit = "";
        if (a != null) {
            ax = a.pixelWidth;
            ay = a.pixelHeight;
            az = a.pixelDepth;
            aunit = a.getUnit();
        }
        if (b != null) {
            bx = b.pixelWidth;
            by = b.pixelHeight;
            bz = b.pixelDepth;
            bunit = a.getUnit();
        }
        if (!aunit.equals(bunit))
            return false;
        final double epsilon = 0.000001;
        final double pixelWidthDifference = Math.abs(ax - bx);
        if (pixelWidthDifference > epsilon)
            return false;
        final double pixelHeightDifference = Math.abs(ay - by);
        if (pixelHeightDifference > epsilon)
            return false;
        final double pixelDepthDifference = Math.abs(az - bz);
        return !(pixelDepthDifference > epsilon);
    }

    protected static String getSanitizedUnit(final String unit) {
        final BoundingBox bd = new BoundingBox();
        bd.setUnit(unit);
        return bd.getUnit();
    }

    /**
     * Generates a list of random paths. Only useful for debugging purposes
     *
     * @return the list of random Paths
     */
    public static List<Path> randomPaths() {
        final List<Path> data = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            final Path p = new Path(1, 1, 1, "unit");
            final double v1 = new Random().nextGaussian();
            final double v2 = new Random().nextGaussian();
            p.addPointDouble(v1, v2, v1);
            p.addPointDouble(v2, v1, v2);
            data.add(p);
        }
        return data;
    }
}

16 View Complete Implementation : DefaultTableIOPluginBenchmark.java
Copyright Apache License 2.0
Author : imagej
/**
 * @author Leon Yang
 */
@BenchmarkOptions(benchmarkRounds = 20, warmupRounds = 1)
public clreplaced DefaultTableIOPluginBenchmark {

    private boolean benchmarkTestsEnabled = "enabled".equals(System.getProperty("imagej.server.benchmark.tests"));

    @Before
    public void skipBenchmarksByDefault() {
        replacedumeTrue(benchmarkTestsEnabled);
    }

    private static Context ctx;

    @BeforeClreplaced
    public static void prepare() {
        ctx = new Context();
        final StringBuilder sb = new StringBuilder(10 * 1024 * 1024);
        for (int i = 0; i < 1023; i++) {
            sb.append(String.format("%09d,", i));
        }
        sb.append(String.format("%08d\r\n", 1023));
        final MersenneTwisterFast r = new MersenneTwisterFast();
        for (int i = 0; i < 1023; i++) {
            for (int j = 0; j < 1023; j++) {
                sb.append(String.format("%.7f,", r.nextFloat()));
            }
            sb.append(String.format("%.6f\r\n", r.nextFloat()));
        }
        final ByteArrayHandle bah = new ByteArrayHandle(sb.toString().getBytes());
        ctx.getService(LocationService.clreplaced).mapFile("large.csv", bah);
    }

    @AfterClreplaced
    public static void cleanup() {
        ctx.dispose();
    }

    /**
     * Needed for JUnit-Benchmarks
     */
    @Rule
    public TestRule benchmarkRun = new BenchmarkRule();

    @Test
    public void openLarge() {
        final IOPlugin<GenericTable> tableIO = ctx.service(IOService.clreplaced).getInstance(DefaultTableIOPlugin.clreplaced);
        try {
            tableIO.open("large.csv");
        } catch (IOException exc) {
            exc.printStackTrace();
        }
    }
}

16 View Complete Implementation : GsonHelpers.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static GsonBuilder builderWithAllRequiredSerializers(final Context context, final PainteraBaseView viewer, final Supplier<String> projectDirectory) {
    final ToIntFunction<SourceState<?, ?>> dependencyFromIndex = state -> viewer.sourceInfo().trackSources().indexOf(state.getDataSource());
    return builderWithAllRequiredSerializers(context, projectDirectory, dependencyFromIndex);
}

16 View Complete Implementation : GsonHelpers.java
Copyright GNU General Public License v2.0
Author : saalfeldlab
public static GsonBuilder builderWithAllRequiredSerializers(final Context context, final Supplier<String> projectDirectory, final ToIntFunction<SourceState<?, ?>> dependencyToIndex) {
    LOG.debug("Creating builder with required serializers.");
    final Map<Clreplaced<?>, List<Pair<PainteraSerialization.PainteraSerializer, Double>>> serializers = PainteraSerialization.getSerializers(context);
    final Map<Clreplaced<?>, List<Pair<StatefulSerializer.SerializerFactory, Double>>> serializerFactories = StatefulSerializer.getSerializers(context);
    LOG.debug("Found serializer factories for these clreplacedes: {}", serializerFactories.keySet());
    final GsonBuilder builder = new GsonBuilder();
    for (final Map.Entry<Clreplaced<?>, List<Pair<PainteraSerialization.PainteraSerializer, Double>>> d : serializers.entrySet()) {
        final PainteraSerialization.PainteraSerializer v = d.getValue().get(0).getKey();
        LOG.debug("Adding serializer for clreplaced {} ({})", d.getKey(), v.isHierarchyAdapter());
        if (v.isHierarchyAdapter())
            builder.registerTypeHierarchyAdapter(d.getKey(), v);
        else
            builder.registerTypeAdapter(d.getKey(), v);
    }
    for (final Map.Entry<Clreplaced<?>, List<Pair<StatefulSerializer.SerializerFactory, Double>>> d : serializerFactories.entrySet()) {
        final StatefulSerializer.SerializerFactory v = d.getValue().get(0).getKey();
        LOG.debug("Adding serializer factory for clreplaced {}", d.getKey());
        builder.registerTypeAdapter(d.getKey(), v.createSerializer(projectDirectory, dependencyToIndex));
    }
    return builder;
}

16 View Complete Implementation : AbstractFormatTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Abstract superclreplaced for format tests, provides image testing and sample file
 * retrieval methods.
 *
 * @author Gabriel Einsdorf, KNIME GmbH
 */
public clreplaced AbstractFormatTest {

    private FileLocation baseFolder;

    private final Location[] sources;

    private final Context ctx = new Context();

    private final InitializeService init = ctx.getService(InitializeService.clreplaced);

    public AbstractFormatTest(final Location... sources) {
        if (sources.length == 0) {
            throw new IllegalArgumentException("At least one source is required!");
        }
        this.sources = sources;
    }

    public FileLocation baseFolder() {
        if (baseFolder == null)
            initBaseFolder();
        return baseFolder;
    }

    public void testImg(final Location imgLoc, final String hash, final int[] dims, final AxisType... axes) {
        testImg(imgLoc, hash, "", dims, axes);
    }

    public void testImg(final Location imgLoc, final String hash, final String metadataJson, final int[] dims, final AxisType... axes) {
        try {
            final ImgOpener opener = new ImgOpener(ctx);
            final SCIFIOImgPlus<?> img = opener.openImgs(imgLoc).get(0);
            replacedertEquals("Wrong number or dims: ", dims.length, img.numDimensions());
            for (int i = 0; i < dims.length; i++) {
                replacedertEquals("The dimensions of dim " + i + " are wrong!", dims[i], img.dimension(i));
            }
            replacedertEquals("missmatch between axes and dims:", dims.length, axes.length);
            for (int i = 0; i < axes.length; i++) {
                // NB: instances of Axes.unknown are all different but share the same
                // label
                if (Axes.UNKNOWN_LABEL.equals(axes[i].getLabel())) {
                    replacedertEquals(Axes.UNKNOWN_LABEL, img.axis(i).type().getLabel());
                    continue;
                }
                replacedertEquals("Axis missmatch at position " + i, axes[i], img.axis(i).type());
            }
            replacedertEquals(hash, ImageHash.hashImg(img));
            if (!"".equals(metadataJson)) {
                final Metadata metadata = init.initializeReader(imgLoc).getMetadata();
                replacedertEquals(metadataJson, MetaDataSerializer.metaToJson(metadata));
            }
        } catch (FormatException | IOException exc) {
            throw new replacedertionError("Error during image test", exc);
        }
    }

    /**
     * Double-checked locking initialization for {@link #baseFolder}.
     */
    private synchronized void initBaseFolder() {
        if (baseFolder != null)
            return;
        try {
            final SampleFileService sampleFileService = ctx.getService(SampleFileService.clreplaced);
            baseFolder = sampleFileService.prepareFormatTestFolder(sources);
            replacedertTrue(ctx.getService(DataHandleService.clreplaced).exists(baseFolder));
        } catch (final IOException e) {
            throw new replacedertionError("Could not initialize base folder", e);
        }
    }
}

16 View Complete Implementation : StratecPQCTFormatTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * Tests for {@link StratecPQCTFormat}
 *
 * @author Richard Domander (Royal Veterinary College, London)
 */
public clreplaced StratecPQCTFormatTest {

    private static final String validName = Paths.get("I1234567.m02").toString();

    private static final String validDevice = "device.typ";

    private static final StratecPQCTFormat format = new StratecPQCTFormat();

    private static final Context context = new Context();

    private static final DataHandleService handles = context.getService(DataHandleService.clreplaced);

    private static final Checker checker = new Checker();

    private static final Parser parser = new Parser();

    @BeforeClreplaced
    public static void oneTimeSetup() {
        format.setContext(context);
    }

    @AfterClreplaced
    public static void oneTimeTearDown() {
        context.dispose();
    }

    @Test
    public void testMakeSuffixArray() throws Exception {
        final String[] suffixes = format.makeSuffixArray();
        for (int i = 0; i < 256; i++) {
            replacedertEquals("Malformed suffix", 0, suffixes[i].indexOf('m'));
            final int hexValue = Integer.parseInt(suffixes[i].substring(1), 16);
            replacedertEquals("Missing suffix", i, hexValue);
        }
    }

    @Test
    public void testIsFormatFalseNoDevice() throws Exception {
        // Check that method doesn't crash with NPE even if there's no device data
        final DataHandle<Location> handle = createTestHandle(HEADER_SIZE, validName);
        // zero-fill the handle
        handle.write(new byte[DEVICE_NAME_INDEX]);
        handle.write(1);
        replacedertFalse(checker.isFormat(handle));
    }

    @Test
    public void testIsFormatFalseShortStream() throws Exception {
        final DataHandle<Location> handle = createTestHandle(HEADER_SIZE - 1, validName);
        // zero-fill the handle
        handle.write(new byte[DEVICE_NAME_INDEX]);
        handle.write((byte) validDevice.length());
        handle.write(validDevice.getBytes());
        replacedertFalse(checker.isFormat(handle));
    }

    @Test
    public void testIsFormatFalseBadDevice() throws Exception {
        final String device = "device.tyq";
        final DataHandle<Location> handle = createTestHandle(HEADER_SIZE, validName);
        // zero-fill the handle
        handle.write(new byte[DEVICE_NAME_INDEX]);
        handle.write((byte) device.length());
        handle.write(device.getBytes());
        replacedertFalse(checker.isFormat(handle));
    }

    @Test
    public void testIsFormatFalseBadFilename() throws Exception {
        final DataHandle<Location> handle = createTestHandle(HEADER_SIZE, "I123456G.m02");
        // zero-fill the handle
        handle.write(new byte[DEVICE_NAME_INDEX]);
        handle.write((byte) validDevice.length());
        handle.write(validDevice.getBytes());
        replacedertFalse(checker.isFormat(handle));
    }

    @Test
    public void testIsFormat() throws Exception {
        // Check that case doesn't matter
        final String device = "DevIce.TyP";
        final DataHandle<Location> handle = createTestHandle(HEADER_SIZE, validName);
        // zero-fill the handle
        handle.write(new byte[DEVICE_NAME_INDEX]);
        handle.write((byte) device.length());
        handle.write(device.getBytes());
        replacedertTrue(checker.isFormat(handle));
    }

    @Test
    public void testSetDateBadInt() throws Exception {
        final Metadata metadata = (Metadata) format.createMetadata();
        metadata.setPatientBirthDate(0);
        replacedertEquals(Metadata.DEFAULT_DATE, metadata.getPatientBirthDate());
    }

    @Test
    public void testMeasurementInfoEmptyIfException() throws Exception {
        final Metadata metadata = (Metadata) format.createMetadata();
        final DataHandle<Location> handle = createTestHandle(0, validName);
        metadata.setMeasurementInfo(handle);
        replacedertTrue(metadata.getMeasurementInfo().isEmpty());
    }

    @Test
    public void testPopulateImageMetadata() throws Exception {
        // SETUP
        final Metadata metadata = (Metadata) format.createMetadata();
        final short width = 10;
        metadata.setWidth(width);
        final short height = 15;
        metadata.setHeight(height);
        final short slices = 5;
        metadata.setSlices(slices);
        final double resolution = 0.5;
        metadata.setResolution(resolution);
        final double distance = 0.1;
        metadata.setSliceDistance(distance);
        final CalibratedAxis[] expectedAxes = new CalibratedAxis[] { new DefaultLinearAxis(Axes.X, Metadata.UNIT, resolution), new DefaultLinearAxis(Axes.Y, Metadata.UNIT, resolution) };
        // EXERCISE
        metadata.populateImageMetadata();
        final ImageMetadata imgMeta = metadata.get(0);
        final List<CalibratedAxis> axes = imgMeta.getAxes();
        // VERIFY
        replacedertTrue(imgMeta.isLittleEndian());
        replacedertTrue(imgMeta.isOrderCertain());
        replacedertEquals(16, imgMeta.getBitsPerPixel());
        replacedertEquals(FormatTools.INT16, imgMeta.getPixelType());
        replacedertEquals(2, imgMeta.getPlanarAxisCount());
        replacedertEquals(width, imgMeta.getAxisLength(Axes.X));
        replacedertEquals(height, imgMeta.getAxisLength(Axes.Y));
        replacedertEquals(expectedAxes.length, axes.size());
        for (int i = 0; i < expectedAxes.length; i++) {
            final CalibratedAxis expected = expectedAxes[i];
            final CalibratedAxis axis = axes.get(i);
            replacedertEquals(expected.type(), axis.type());
            replacedertEquals(expected.unit(), axis.unit());
            replacedertEquals(expected.averageScale(0, 1), axis.averageScale(0, 1), 1e-12);
        }
    }

    @Test
    public void testSlicesAtLeastOne() throws Exception {
        final Metadata metadata = (Metadata) format.createMetadata();
        metadata.setSlices((short) 0);
        replacedertEquals(1, metadata.getSlices());
    }

    @Test
    public void testTypedParse() throws Exception {
        // SETUP
        final ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        final double resolution = 0.1234;
        final double objectSize = 31337;
        final List<String> measurementInfo = Arrays.asList("CT-X", "", "Additional", "Info");
        final String expectedInfo = measurementInfo.stream().filter(s -> !s.isEmpty()).reduce("", (s, t) -> s + t + "\n");
        final int measurementDate = 20160125;
        final short measurementNumber = 45;
        final int patientNumber = 536345;
        final int patientBirthDate = 19450508;
        final int patientAge = 43;
        final String patientName = "Max Mustermann";
        final String patientId = "MAXM1234";
        final short leftEdge = 5;
        final short topEdge = 6;
        final short width = 250;
        final short height = 200;
        final short slices = 3;
        final double sliceStart = 0.12345;
        final double sliceDistance = 0.6789;
        buffer.putDouble(12, resolution);
        buffer.putShort(30, slices);
        buffer.putDouble(32, sliceStart);
        buffer.putDouble(40, sliceDistance);
        buffer.putDouble(318, objectSize);
        for (int i = 0; i < 4; i++) {
            putShortString(Metadata.INFO_INDICES[i], buffer, measurementInfo.get(i));
        }
        buffer.putInt(986, measurementDate);
        putShortString(DEVICE_NAME_INDEX, buffer, validDevice);
        buffer.putShort(1085, measurementNumber);
        buffer.putInt(1087, patientNumber);
        buffer.putInt(1091, patientBirthDate);
        buffer.putInt(1095, patientAge);
        putShortString(1099, buffer, patientName);
        putShortString(1282, buffer, patientId);
        buffer.putShort(1525, leftEdge);
        buffer.putShort(1527, topEdge);
        buffer.putShort(1529, width);
        buffer.putShort(1531, height);
        final DataHandle<Location> handle = handles.create(new BytesLocation(buffer.array()));
        final Metadata metadata = new Metadata();
        final SCIFIOConfig config = new SCIFIOConfig();
        // EXERCISE
        parser.typedParse(handle, metadata, config);
        // VERIFY
        replacedertEquals(resolution, metadata.getResolution(), 1e-12);
        replacedertEquals(objectSize, metadata.getObjectSize(), 1e-12);
        replacedertEquals(expectedInfo, metadata.getMeasurementInfo());
        replacedertEquals(0, metadata.getMeasurementDate().compareTo(new GregorianCalendar(2016, 0, 25).getTime()));
        replacedertEquals(validDevice, metadata.getDeviceName());
        replacedertEquals(measurementNumber, metadata.getPatientMeasurementNumber());
        replacedertEquals(patientNumber, metadata.getPatientNumber());
        replacedertEquals(0, metadata.getPatientBirthDate().compareTo(new GregorianCalendar(1945, 4, 8).getTime()));
        replacedertEquals(patientAge, metadata.getPatientAge());
        replacedertEquals(patientName, metadata.getPatientName());
        replacedertEquals(patientId, metadata.getPatientId());
        replacedertEquals(leftEdge, metadata.getLeftEdge());
        replacedertEquals(topEdge, metadata.getTopEdge());
        replacedertEquals(width, metadata.getWidth());
        replacedertEquals(height, metadata.getHeight());
        replacedertEquals(slices, metadata.getSlices());
        replacedertEquals(sliceStart, metadata.getSliceStart(), 1e-12);
        replacedertEquals(sliceDistance, metadata.getSliceDistance(), 1e-12);
    }

    private void putShortString(final int position, final ByteBuffer buffer, final String string) {
        buffer.position(position);
        buffer.put((byte) string.length());
        buffer.put(string.getBytes());
    }

    @Test
    public void testOpenPlane() throws Exception {
        final short width = 10;
        final short height = 10;
        final int planeBytes = width * height * 2;
        final ByteArrayPlane plane = new ByteArrayPlane();
        plane.setData(new byte[planeBytes]);
        final ByteBuffer buffer = ByteBuffer.allocate(StratecPQCTFormat.HEADER_SIZE + planeBytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.position(1529);
        buffer.putShort(width);
        buffer.putShort(height);
        final DataHandle<Location> handle = handles.create(new BytesLocation(buffer.array()));
        final Reader reader = (Reader) format.createReader();
        reader.setSource(handle);
        // EXECUTE
        final Interval bounds = new FinalInterval(width, height);
        reader.openPlane(0, 0, plane, bounds, new SCIFIOConfig());
        // VERIFY
        replacedertEquals("Position of stream incorrect: should point to the end of the stream", StratecPQCTFormat.HEADER_SIZE + planeBytes, handle.offset());
    }

    private DataHandle<Location> createTestHandle(final int size, final String name) {
        return handles.create(new BytesLocation(new ByteArray(size)) {

            @Override
            public String getName() {
                return name;
            }
        });
    }
}

15 View Complete Implementation : DefaultOpMatchingService.java
Copyright BSD 2-Clause "Simplified" License
Author : imagej
/**
 * Default service for finding {@link Op}s which match a request.
 *
 * @author Curtis Rueden
 */
@Plugin(type = Service.clreplaced)
public clreplaced DefaultOpMatchingService extends AbstractService implements OpMatchingService {

    @Parameter
    private Context context;

    @Parameter
    private ModuleService moduleService;

    @Parameter
    private ConvertService convertService;

    @Parameter
    private LogService log;

    // -- OpMatchingService methods --
    @Override
    public OpCandidate findMatch(final OpEnvironment ops, final OpRef ref) {
        return findMatch(ops, Collections.singletonList(ref));
    }

    @Override
    public OpCandidate findMatch(final OpEnvironment ops, final List<OpRef> refs) {
        // find candidates with matching name & type
        final List<OpCandidate> candidates = findCandidates(ops, refs);
        replacedertCandidates(candidates, refs.get(0));
        // narrow down candidates to the exact matches
        final List<OpCandidate> matches = filterMatches(candidates);
        return singleMatch(candidates, matches);
    }

    @Override
    public List<OpCandidate> findCandidates(final OpEnvironment ops, final OpRef ref) {
        return findCandidates(ops, Collections.singletonList(ref));
    }

    @Override
    public List<OpCandidate> findCandidates(final OpEnvironment ops, final List<OpRef> refs) {
        final ArrayList<OpCandidate> candidates = new ArrayList<>();
        for (final OpInfo info : ops.infos()) {
            for (final OpRef ref : refs) {
                if (isCandidate(info, ref)) {
                    candidates.add(new OpCandidate(ops, ref, info));
                }
            }
        }
        return candidates;
    }

    @Override
    public List<OpCandidate> filterMatches(final List<OpCandidate> candidates) {
        final List<OpCandidate> validCandidates = validCandidates(candidates);
        List<OpCandidate> matches;
        matches = filterMatches(validCandidates, (cand) -> typesPerfectMatch(cand));
        if (!matches.isEmpty())
            return matches;
        matches = castMatches(validCandidates);
        if (!matches.isEmpty())
            return matches;
        // NB: Not implemented yet
        // matches = filterMatches(validCandidates, (cand) -> losslessMatch(cand));
        // if (!matches.isEmpty()) return matches;
        matches = filterMatches(validCandidates, (cand) -> typesMatch(cand));
        return matches;
    }

    @Override
    public Module match(final OpCandidate candidate) {
        if (!valid(candidate))
            return null;
        if (!outputsMatch(candidate))
            return null;
        final Object[] args = padArgs(candidate);
        return args == null ? null : match(candidate, args);
    }

    @Override
    public boolean typesMatch(final OpCandidate candidate) {
        if (!valid(candidate))
            return false;
        final Object[] args = padArgs(candidate);
        return args == null ? false : typesMatch(candidate, args) < 0;
    }

    @Override
    public Module replacedignInputs(final Module module, final Object... args) {
        int i = 0;
        for (final ModuleItem<?> item : OpUtils.inputs(module.getInfo())) {
            replacedign(module, args[i++], item);
        }
        return module;
    }

    @Override
    public Object[] padArgs(final OpCandidate candidate) {
        int inputCount = 0, requiredCount = 0;
        for (final ModuleItem<?> item : candidate.inputs()) {
            inputCount++;
            if (item.isRequired())
                requiredCount++;
        }
        final Object[] args = candidate.getRef().getArgs();
        if (args.length == inputCount) {
            // correct number of arguments
            return args;
        }
        if (args.length > inputCount) {
            // too many arguments
            candidate.setStatus(StatusCode.TOO_MANY_ARGS, args.length + " > " + inputCount);
            return null;
        }
        if (args.length < requiredCount) {
            // too few arguments
            candidate.setStatus(StatusCode.TOO_FEW_ARGS, args.length + " < " + requiredCount);
            return null;
        }
        // pad optional parameters with null (from right to left)
        final int argsToPad = inputCount - args.length;
        final int optionalCount = inputCount - requiredCount;
        final int optionalsToFill = optionalCount - argsToPad;
        final Object[] paddedArgs = new Object[inputCount];
        int argIndex = 0, paddedIndex = 0, optionalIndex = 0;
        for (final ModuleItem<?> item : candidate.inputs()) {
            if (!item.isRequired() && optionalIndex++ >= optionalsToFill) {
                // skip this optional parameter (pad with null)
                paddedIndex++;
                continue;
            }
            paddedArgs[paddedIndex++] = args[argIndex++];
        }
        return paddedArgs;
    }

    // -- Helper methods --
    /**
     * Helper method of {@link #findCandidates}.
     */
    private boolean isCandidate(final OpInfo info, final OpRef ref) {
        if (!info.nameMatches(ref.getName()))
            return false;
        // the name matches; now check the clreplaced
        final Clreplaced<?> opClreplaced;
        try {
            opClreplaced = info.cInfo().loadClreplaced();
        } catch (final InstantiableException exc) {
            final String msg = "Invalid op: " + info.cInfo().getClreplacedName();
            if (log.isDebug())
                log.debug(msg, exc);
            else
                log.error(msg);
            return false;
        }
        return ref.typesMatch(opClreplaced);
    }

    /**
     * Helper method of {@link #findMatch}.
     */
    private void replacedertCandidates(final List<OpCandidate> candidates, final OpRef ref) {
        if (candidates.isEmpty()) {
            throw new IllegalArgumentException("No candidate '" + ref.getLabel() + "' ops");
        }
    }

    /**
     * Gets a list of valid candidates injected with padded arguments.
     * <p>
     * Helper method of {@link #filterMatches}.
     * </p>
     *
     * @param candidates list of candidates
     * @return a list of valid candidates with arguments injected
     */
    private List<OpCandidate> validCandidates(final List<OpCandidate> candidates) {
        final ArrayList<OpCandidate> validCandidates = new ArrayList<>();
        for (final OpCandidate candidate : candidates) {
            if (!valid(candidate) || !outputsMatch(candidate))
                continue;
            final Object[] args = padArgs(candidate);
            if (args == null)
                continue;
            candidate.setArgs(args);
            if (missArgs(candidate))
                continue;
            validCandidates.add(candidate);
        }
        return validCandidates;
    }

    /**
     * Determines if the candidate arguments match with lossless conversion. Needs
     * support from the conversion in the future.
     */
    @SuppressWarnings("unused")
    private boolean losslessMatch(final OpCandidate candidate) {
        // NB: Not yet implemented
        return false;
    }

    /**
     * Filters out candidates that preplaced the given filter.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private List<OpCandidate> filterMatches(final List<OpCandidate> candidates, final Predicate<OpCandidate> filter) {
        final ArrayList<OpCandidate> matches = new ArrayList<>();
        double priority = Double.NaN;
        for (final OpCandidate candidate : candidates) {
            final ModuleInfo info = candidate.cInfo();
            final double p = info.getPriority();
            if (p != priority && !matches.isEmpty()) {
                // NB: Lower priority was reached; stop looking for any more matches.
                break;
            }
            priority = p;
            if (filter.test(candidate) && moduleConforms(candidate)) {
                matches.add(candidate);
            }
        }
        return matches;
    }

    /**
     * Determines if the candidate has some arguments missing.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private boolean missArgs(final OpCandidate candidate) {
        int i = 0;
        for (final ModuleItem<?> item : candidate.inputs()) {
            if (candidate.getArgs()[i++] == null && item.isRequired()) {
                candidate.setStatus(StatusCode.REQUIRED_ARG_IS_NULL, null, item);
                return true;
            }
        }
        return false;
    }

    /**
     * Determine if the arguments of the candidate perfectly match with the
     * reference.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private boolean typesPerfectMatch(final OpCandidate candidate) {
        int i = 0;
        final Object[] args = candidate.getArgs();
        for (final ModuleItem<?> item : candidate.inputs()) {
            if (args[i] != null) {
                final Clreplaced<?> typeClreplaced = OpMatchingUtil.getClreplaced(item.getType());
                final Clreplaced<?> argClreplaced = OpMatchingUtil.getClreplaced(args[i]);
                if (!typeClreplaced.equals(argClreplaced))
                    return false;
            }
            i++;
        }
        return true;
    }

    /**
     * Extracts a list of candidates that requires casting to match with the
     * reference.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private List<OpCandidate> castMatches(final List<OpCandidate> candidates) {
        final ArrayList<OpCandidate> matches = new ArrayList<>();
        int minLevels = Integer.MAX_VALUE;
        double priority = Double.NaN;
        for (final OpCandidate candidate : candidates) {
            final ModuleInfo info = candidate.cInfo();
            final double p = info.getPriority();
            if (p != priority && !matches.isEmpty()) {
                // NB: Lower priority was reached; stop looking for any more matches.
                break;
            }
            priority = p;
            final int nextLevels = findCastLevels(candidate);
            if (nextLevels < 0 || nextLevels > minLevels)
                continue;
            if (!moduleConforms(candidate))
                continue;
            if (nextLevels < minLevels) {
                matches.clear();
                minLevels = nextLevels;
            }
            matches.add(candidate);
        }
        return matches;
    }

    /**
     * Find the total levels of casting needed for the candidate to match with the
     * reference.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private int findCastLevels(final OpCandidate candidate) {
        int level = 0, i = 0;
        final Object[] args = candidate.getArgs();
        for (final ModuleItem<?> item : candidate.inputs()) {
            final Clreplaced<?> type = item.getType();
            if (args[i] != null) {
                final int currLevel = OpMatchingUtil.findCastLevels(type, OpMatchingUtil.getClreplaced(args[i]));
                if (currLevel < 0)
                    return -1;
                level += currLevel;
            }
            i++;
        }
        return level;
    }

    /**
     * Extracts and returns the single match from the given list of matches,
     * executing the linked {@link Module}'s initializer if applicable. If there
     * is not exactly one match, an {@link IllegalArgumentException} is thrown
     * with an replacedysis of the problem(s).
     * <p>
     * Helper method of {@link #findMatch}.
     * </p>
     *
     * @param candidates The original unfiltered list of candidates, used during
     *          the replacedysis if there was a problem finding exactly one match.
     * @param matches The list of matching candidates.
     * @return The single matching candidate, with its module initialized.
     * @throws IllegalArgumentException If there is not exactly one matching
     *           candidate.
     */
    private OpCandidate singleMatch(final List<OpCandidate> candidates, final List<OpCandidate> matches) {
        if (matches.size() == 1) {
            // a single match: initialize and return it
            final Module m = matches.get(0).getModule();
            if (log.isDebug()) {
                log.debug("Selected '" + matches.get(0).getRef().getLabel() + "' op: " + m.getDelegateObject().getClreplaced().getName());
            }
            // initialize the op, if appropriate
            if (m.getDelegateObject() instanceof Initializable) {
                ((Initializable) m.getDelegateObject()).initialize();
            }
            return matches.get(0);
        }
        final String replacedysis = OpUtils.matchInfo(candidates, matches);
        throw new IllegalArgumentException(replacedysis);
    }

    /**
     * Verifies that the given candidate's module is valid.
     * <p>
     * Helper method of {@link #match(OpCandidate)}.
     * </p>
     */
    private boolean valid(final OpCandidate candidate) {
        if (candidate.cInfo().isValid())
            return true;
        candidate.setStatus(StatusCode.INVALID_MODULE);
        return false;
    }

    /**
     * Verifies that the given candidate's output types match those of the op.
     * <p>
     * Helper method of {@link #match(OpCandidate)}.
     * </p>
     */
    private boolean outputsMatch(final OpCandidate candidate) {
        final Collection<Type> outTypes = candidate.getRef().getOutTypes();
        // no constraints on output types
        if (outTypes == null)
            return true;
        final Iterator<ModuleItem<?>> oureplacedems = candidate.outputs().iterator();
        for (final Type outType : outTypes) {
            if (!oureplacedems.hasNext()) {
                candidate.setStatus(StatusCode.TOO_FEW_OUTPUTS);
                return false;
            }
            // FIXME: Use generic replacedignability test, once it exists.
            final Clreplaced<?> raw = GenericUtils.getClreplaced(outType);
            final Clreplaced<?> oureplacedemClreplaced = oureplacedems.next().getType();
            if (!ConversionUtils.canCast(oureplacedemClreplaced, raw)) {
                // 
                candidate.setStatus(// 
                StatusCode.OUTPUT_TYPES_DO_NOT_MATCH, "request=" + raw.getName() + ", actual=" + oureplacedemClreplaced.getName());
                return false;
            }
        }
        return true;
    }

    /**
     * Verifies that the given candidate's module conforms.
     * <p>
     * Helper method of {@link #filterMatches(List)}.
     * </p>
     */
    private boolean moduleConforms(final OpCandidate candidate) {
        // create module and replacedign the inputs
        final Module module = createModule(candidate, candidate.getArgs());
        candidate.setModule(module);
        // make sure the op itself is happy with these arguments
        final Object op = module.getDelegateObject();
        if (op instanceof Contingent) {
            final Contingent c = (Contingent) op;
            if (!c.conforms()) {
                candidate.setStatus(StatusCode.DOES_NOT_CONFORM);
                return false;
            }
        }
        // found a match!
        return true;
    }

    /**
     * Helper method of {@link #match(OpCandidate)}.
     */
    private Module match(final OpCandidate candidate, final Object[] args) {
        // check that each parameter is compatible with its argument
        final int badIndex = typesMatch(candidate, args);
        if (badIndex >= 0) {
            final String message = typeClashMessage(candidate, args, badIndex);
            candidate.setStatus(StatusCode.ARG_TYPES_DO_NOT_MATCH, message);
            return null;
        }
        // create module and replacedign the inputs
        final Module module = createModule(candidate, args);
        candidate.setModule(module);
        // make sure the op itself is happy with these arguments
        final Object op = module.getDelegateObject();
        if (op instanceof Contingent) {
            final Contingent c = (Contingent) op;
            if (!c.conforms()) {
                candidate.setStatus(StatusCode.DOES_NOT_CONFORM);
                return null;
            }
        }
        // found a match!
        return module;
    }

    /**
     * Checks that each parameter is type-compatible with its corresponding
     * argument.
     */
    private int typesMatch(final OpCandidate candidate, final Object[] args) {
        int i = 0;
        for (final ModuleItem<?> item : candidate.inputs()) {
            if (!canreplacedign(candidate, args[i], item))
                return i;
            i++;
        }
        return -1;
    }

    /**
     * Helper method of {@link #match(OpCandidate, Object[])}.
     */
    private String typeClashMessage(final OpCandidate candidate, final Object[] args, final int index) {
        int i = 0;
        for (final ModuleItem<?> item : candidate.inputs()) {
            if (i++ == index) {
                final Object arg = args[index];
                final String argType = arg == null ? "null" : arg.getClreplaced().getName();
                final Type inputType = item.getGenericType();
                return index + ": cannot coerce " + argType + " -> " + inputType;
            }
        }
        throw new IllegalArgumentException("Invalid index: " + index);
    }

    /**
     * Helper method of {@link #match(OpCandidate, Object[])}.
     */
    private Module createModule(final OpCandidate candidate, final Object... args) {
        // create the module
        final Module module = moduleService.createModule(candidate.cInfo());
        // unwrap the created op
        final Op op = OpUtils.unwrap(module, candidate.getRef());
        // inject the op execution environment
        op.setEnvironment(candidate.ops());
        // populate the inputs and return the module
        return replacedignInputs(module, args);
    }

    /**
     * Helper method of {@link #match(OpCandidate, Object[])}.
     */
    private boolean canreplacedign(final OpCandidate candidate, final Object arg, final ModuleItem<?> item) {
        if (arg == null) {
            if (item.isRequired()) {
                candidate.setStatus(StatusCode.REQUIRED_ARG_IS_NULL, null, item);
                return false;
            }
            return true;
        }
        final Type type = item.getGenericType();
        if (!canConvert(arg, type)) {
            candidate.setStatus(StatusCode.CANNOT_CONVERT, arg.getClreplaced().getName() + " => " + type, item);
            return false;
        }
        return true;
    }

    /**
     * Helper method of {@link #canreplacedign}.
     */
    private boolean canConvert(final Object arg, final Type type) {
        if (isMatchingClreplaced(arg, type)) {
            // NB: Clreplaced argument for matching, to help differentiate op signatures.
            return true;
        }
        return convertService.supports(arg, type);
    }

    /**
     * Helper method of {@link #replacedignInputs}.
     */
    private void replacedign(final Module module, final Object arg, final ModuleItem<?> item) {
        if (arg != null) {
            final Type type = item.getGenericType();
            final Object value = convert(arg, type);
            module.setInput(item.getName(), value);
        }
        module.resolveInput(item.getName());
    }

    /**
     * Helper method of {@link #replacedign}.
     */
    private Object convert(final Object arg, final Type type) {
        if (isMatchingClreplaced(arg, type)) {
            // NB: Clreplaced argument for matching; fill with null.
            return null;
        }
        return convertService.convert(arg, type);
    }

    /**
     * Determines whether the argument is a matching clreplaced instance.
     */
    private boolean isMatchingClreplaced(final Object arg, final Type type) {
        return arg instanceof Clreplaced && convertService.supports((Clreplaced<?>) arg, type);
    }
}

15 View Complete Implementation : AbstractResourceTest.java
Copyright Apache License 2.0
Author : imagej
/**
 * Abstract clreplaced for resource tests. Initialize necessary variables.
 *
 * @author Leon Yang
 */
public abstract clreplaced AbstractResourceTest {

    protected static final Context ctx = new Context();

    protected static final ObjectService objectService = new DefaultObjectService();

    protected static final JsonService jsonService = new DefaultJsonService(objectService);

    protected static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        jsonService.addDeserializerTo(objectMapper);
    }

    protected static final AbstractBinder binder = new AbstractBinder() {

        @Override
        protected void configure() {
            bind(ctx).to(Context.clreplaced);
            bind(objectService).to(ObjectService.clreplaced);
            bind(jsonService).to(JsonService.clreplaced);
        }
    };

    protected static final Builder resourcesBuilder = ResourceTestRule.builder().addProvider(binder).setMapper(objectMapper);
}

15 View Complete Implementation : ImageViewer.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
/**
 * A basic renderer for image data.
 *
 * @author Curtis Rueden
 * @author Mark Hiner
 */
public clreplaced ImageViewer extends JFrame implements ActionListener, ChangeListener, KeyListener, MouseMotionListener, Runnable, WindowListener {

    // -- Constants --
    @Parameter
    private Context context;

    @Parameter
    private LogService logService;

    @Parameter
    private FormatService formatService;

    @Parameter
    private InitializeService initializeService;

    @Parameter
    private GUIService guiService;

    private static final String replacedLE = "SCIFIO Viewer";

    private static final char ANIMATION_KEY = ' ';

    // -- Fields --
    /**
     * Current format reader.
     */
    private Reader myReader;

    /**
     * Current format writer.
     */
    private Writer myWriter;

    private final JPanel pane;

    private final ImageIcon icon;

    private final JLabel iconLabel;

    private final JPanel sliderPanel;

    private final JSlider nSlider;

    private final JLabel probeLabel;

    private final JMenuItem fileView, fileSave;

    private String filename;

    private BufferedImage[] images;

    private boolean anim = false;

    private int fps = 10;

    private boolean canCloseReader = true;

    // -- Constructor --
    /**
     * Constructs an image viewer.
     */
    public ImageViewer(final Context context) {
        super(replacedLE);
        context.inject(this);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(this);
        // content pane
        pane = new JPanel();
        pane.setLayout(new BorderLayout());
        setContentPane(pane);
        // default size
        setSize(350, 350);
        // navigation sliders
        sliderPanel = new JPanel();
        sliderPanel.setVisible(false);
        sliderPanel.setBorder(new EmptyBorder(5, 3, 5, 3));
        sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.Y_AXIS));
        pane.add(BorderLayout.SOUTH, sliderPanel);
        final JPanel nPanel = new JPanel();
        nPanel.setLayout(new BoxLayout(nPanel, BoxLayout.X_AXIS));
        sliderPanel.add(nPanel);
        sliderPanel.add(Box.createVerticalStrut(2));
        nSlider = new JSlider(1, 1);
        nSlider.setEnabled(false);
        nSlider.addChangeListener(this);
        nPanel.add(new JLabel("N"));
        nPanel.add(Box.createHorizontalStrut(3));
        nPanel.add(nSlider);
        final JPanel ztcPanel = new JPanel();
        ztcPanel.setLayout(new BoxLayout(ztcPanel, BoxLayout.X_AXIS));
        sliderPanel.add(ztcPanel);
        // image icon
        final BufferedImage dummy = AWTImageTools.makeImage(new byte[1][1], 1, 1, false);
        icon = new ImageIcon(dummy);
        iconLabel = new JLabel(icon, SwingConstants.LEFT);
        iconLabel.setVerticalAlignment(SwingConstants.TOP);
        pane.add(new JScrollPane(iconLabel));
        // cursor probe
        probeLabel = new JLabel(" ");
        probeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        probeLabel.setBorder(new BevelBorder(BevelBorder.RAISED));
        pane.add(BorderLayout.NORTH, probeLabel);
        iconLabel.addMouseMotionListener(this);
        // menu bar
        final JMenuBar menubar = new JMenuBar();
        // FIXME: currently the menu bar is disabled to restrict the use of
        // ImageViewer to the Show command. We could attempt to get this
        // implementation working nicely, or just convert to an IJ2
        // implementation.
        // setJMenuBar(menubar);
        final JMenu file = new JMenu("File");
        file.setMnemonic('f');
        menubar.add(file);
        final JMenuItem fileOpen = new JMenuItem("Open...");
        fileOpen.setMnemonic('o');
        fileOpen.setActionCommand("open");
        fileOpen.addActionListener(this);
        file.add(fileOpen);
        fileSave = new JMenuItem("Save...");
        fileSave.setMnemonic('s');
        fileSave.setEnabled(false);
        fileSave.setActionCommand("save");
        fileSave.addActionListener(this);
        file.add(fileSave);
        fileView = new JMenuItem("View Metadata...");
        final JMenuItem fileExit = new JMenuItem("Exit");
        fileExit.setMnemonic('x');
        fileExit.setActionCommand("exit");
        fileExit.addActionListener(this);
        file.add(fileExit);
        final JMenu options = new JMenu("Options");
        options.setMnemonic('p');
        menubar.add(options);
        final JMenuItem optionsFPS = new JMenuItem("Frames per Second...");
        optionsFPS.setMnemonic('f');
        optionsFPS.setActionCommand("fps");
        optionsFPS.addActionListener(this);
        options.add(optionsFPS);
        final JMenu help = new JMenu("Help");
        help.setMnemonic('h');
        menubar.add(help);
        final JMenuItem helpAbout = new JMenuItem("About...");
        helpAbout.setMnemonic('a');
        helpAbout.setActionCommand("about");
        helpAbout.addActionListener(this);
        help.add(helpAbout);
        // add key listener to focusable components
        nSlider.addKeyListener(this);
    }

    /**
     * Constructs an image viewer.
     *
     * @param canCloseReader whether or not the underlying reader can be closed
     */
    public ImageViewer(final Context context, final boolean canCloseReader) {
        this(context);
        this.canCloseReader = canCloseReader;
    }

    /**
     * Convenience overload of {@link #open(Location)} for backwards
     * compatibility.
     *
     * @param id
     */
    public void open(final String id) {
        open(new FileLocation(id));
    }

    /**
     * Opens the given data source using the current format reader.
     */
    public void open(final Location id) {
        wait(true);
        try {
            canCloseReader = true;
            myReader = initializeService.initializeReader(id);
            final long planeCount = myReader.getMetadata().get(0).getPlaneCount();
            final ProgressMonitor progress = new ProgressMonitor(this, "Reading " + id, null, 0, 1);
            progress.setProgress(1);
            final BufferedImage[] img = new BufferedImage[(int) planeCount];
            for (long planeIndex = 0; planeIndex < planeCount; planeIndex++) {
                if (progress.isCanceled())
                    break;
                final Plane plane = myReader.openPlane(0, planeIndex);
                img[(int) planeIndex] = AWTImageTools.openImage(plane, myReader, 0);
            }
            progress.setProgress(2);
            setImages(myReader, img);
            myReader.close(true);
        } catch (final FormatException exc) {
            logService.info("", exc);
            wait(false);
            return;
        } catch (final IOException exc) {
            logService.info("", exc);
            wait(false);
            return;
        }
        wait(false);
    }

    /**
     * Convenience overload of {@link #save}, saves the current image to the given
     * local file destination.
     *
     * @param id
     */
    public void save(final String id) {
        save(new FileLocation(id));
    }

    /**
     * Saves the current images to the given destination using the current format
     * writer.
     */
    public void save(final Location id) {
        if (images == null)
            return;
        wait(true);
        try {
            myWriter.setDest(id);
            final boolean stack = myWriter.canDoStacks();
            final 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);
                    final boolean canceled = progress.isCanceled();
                    myWriter.savePlane(0, i, getPlane(images[i]));
                    if (canceled)
                        break;
                }
                progress.setProgress(images.length);
            } else {
                // save current image only
                myWriter.savePlane(0, 0, getPlane(getImage()));
                progress.setProgress(1);
            }
            myWriter.close();
        } catch (FormatException | IOException exc) {
            logService.info("", exc);
        }
        wait(false);
    }

    /**
     * Sets the viewer to display the given images.
     */
    public void setImages(final BufferedImage[] img) {
        setImages(null, img);
    }

    /**
     * Sets the viewer to display the given images, obtaining corresponding core
     * metadata from the specified format reader.
     */
    public void setImages(final Reader reader, final BufferedImage[] img) {
        filename = reader == null ? null : reader.getCurrentLocation().getName();
        myReader = reader;
        images = img;
        fileView.setEnabled(true);
        fileSave.setEnabled(true);
        nSlider.removeChangeListener(this);
        nSlider.setValue(1);
        nSlider.setMaximum(images.length);
        nSlider.setEnabled(images.length > 1);
        nSlider.addChangeListener(this);
        sliderPanel.setVisible(images.length > 1);
        updateLabel(-1, -1);
        sb.setLength(0);
        if (filename != null) {
            sb.append(reader.getCurrentLocation().getName());
            sb.append(" ");
        }
        final String format = reader == null ? null : reader.getFormat().getFormatName();
        if (format != null) {
            sb.append("(");
            sb.append(format);
            sb.append(")");
            sb.append(" ");
        }
        if (filename != null || format != null)
            sb.append("- ");
        sb.append(replacedLE);
        setreplacedle(sb.toString());
        if (images != null)
            icon.setImage(images[0]);
        pack();
    }

    /**
     * Gets the currently displayed image.
     */
    public BufferedImage getImage() {
        final int ndx = getPlaneIndex();
        return images == null || ndx >= images.length ? null : images[ndx];
    }

    public Plane getPlane(final BufferedImage image) {
        final BufferedImagePlane plane = new BufferedImagePlane();
        plane.setData(image);
        return plane;
    }

    /**
     * Gets the index of the currently displayed image.
     */
    public int getPlaneIndex() {
        return nSlider.getValue() - 1;
    }

    // -- Window API methods --
    @Override
    public void setVisible(final boolean visible) {
        super.setVisible(visible);
        // kick off animation thread
        new Thread(this).start();
    }

    // -- ActionListener API methods --
    /**
     * Handles menu commands.
     */
    @Override
    public void actionPerformed(final ActionEvent e) {
        final String cmd = e.getActionCommand();
        if ("open".equals(cmd)) {
            wait(true);
            final JFileChooser chooser = guiService.buildFileChooser(formatService.getAllFormats());
            wait(false);
            final int rval = chooser.showOpenDialog(this);
            if (rval == JFileChooser.APPROVE_OPTION) {
                final File file = chooser.getSelectedFile();
                if (file != null)
                    open(file.getAbsolutePath(), myReader);
            }
        } else if ("save".equals(cmd)) {
            wait(true);
            final JFileChooser chooser = guiService.buildFileChooser(formatService.getOutputFormats());
            wait(false);
            final int rval = chooser.showSaveDialog(this);
            if (rval == JFileChooser.APPROVE_OPTION) {
                if (myWriter != null) {
                    try {
                        myWriter.close();
                    } catch (final IOException e1) {
                        logService.error(e1);
                    }
                }
                final File file = chooser.getSelectedFile();
                try {
                    myWriter = initializeService.initializeWriter(myReader.getMetadata(), new FileLocation(file));
                } catch (FormatException | IOException e1) {
                    logService.error(e);
                }
                if (file != null)
                    save(file.getAbsolutePath(), myWriter);
            }
        } else if ("exit".equals(cmd))
            dispose();
        else if ("fps".equals(cmd)) {
            // HACK - JOptionPane prevents shutdown on dispose
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            final String result = JOptionPane.showInputDialog(this, "Animate using space bar. How many frames per second?", "" + fps);
            try {
                fps = Integer.parseInt(result);
            } catch (final NumberFormatException exc) {
                logService.debug("Could not parse fps " + fps, exc);
            }
        } else if ("about".equals(cmd)) {
            // HACK - JOptionPane prevents shutdown on dispose
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            final String msg = "<html>" + "SCIFIO core for reading and " + "converting file formats." + "<br>Copyright (C) 2005 - 2013" + " 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>" + "<br><br>See <a href=\"" + "http://loci.wisc.edu/software/scifio\">" + "http://loci.wisc.edu/software/scifio</a>" + "<br>for help with using SCIFIO.";
            JOptionPane.showMessageDialog(null, msg, "SCIFIO", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    // -- ChangeListener API methods --
    /**
     * Handles slider events.
     */
    @Override
    public void stateChanged(final ChangeEvent e) {
        final boolean outOfBounds = false;
        updateLabel(-1, -1);
        final BufferedImage image = outOfBounds ? null : getImage();
        if (image == null) {
            iconLabel.setIcon(null);
            iconLabel.setText("No image plane");
        } else {
            icon.setImage(image);
            iconLabel.setIcon(icon);
            iconLabel.setText(null);
        }
    }

    // -- KeyListener API methods --
    /**
     * Handles key presses.
     */
    @Override
    public void keyPressed(final KeyEvent e) {
        // toggle animation
        if (e.getKeyChar() == ANIMATION_KEY)
            anim = !anim;
    }

    @Override
    public void keyReleased(final KeyEvent e) {
    }

    @Override
    public void keyTyped(final KeyEvent e) {
    }

    // -- MouseMotionListener API methods --
    /**
     * Handles cursor probes.
     */
    @Override
    public void mouseDragged(final MouseEvent e) {
        updateLabel(e.getX(), e.getY());
    }

    /**
     * Handles cursor probes.
     */
    @Override
    public void mouseMoved(final MouseEvent e) {
        updateLabel(e.getX(), e.getY());
    }

    // -- Runnable API methods --
    /**
     * Handles animation.
     */
    @Override
    public void run() {
        while (isVisible()) {
            try {
                Thread.sleep(1000 / fps);
            } catch (final InterruptedException exc) {
                logService.debug("", exc);
            }
        }
    }

    // -- WindowListener API methods --
    @Override
    public void windowClosing(final WindowEvent e) {
    }

    @Override
    public void windowActivated(final WindowEvent e) {
    }

    @Override
    public void windowDeactivated(final WindowEvent e) {
    }

    @Override
    public void windowOpened(final WindowEvent e) {
    }

    @Override
    public void windowIconified(final WindowEvent e) {
    }

    @Override
    public void windowDeiconified(final WindowEvent e) {
    }

    @Override
    public void windowClosed(final WindowEvent e) {
        try {
            if (myWriter != null) {
                myWriter.close();
            }
            if (canCloseReader && myReader != null) {
                myReader.close();
            }
        } catch (final IOException io) {
        }
    }

    // -- Helper methods --
    private final StringBuffer sb = new StringBuffer();

    /**
     * Updates cursor probe label.
     */
    protected void updateLabel(int x, int y) {
        if (images == null)
            return;
        final int ndx = getPlaneIndex();
        sb.setLength(0);
        if (images.length > 1) {
            sb.append("N=");
            sb.append(ndx + 1);
            sb.append("/");
            sb.append(images.length);
        }
        final BufferedImage image = images[ndx];
        final int w = image == null ? -1 : image.getWidth();
        final int h = image == null ? -1 : image.getHeight();
        if (x >= w)
            x = w - 1;
        if (y >= h)
            y = h - 1;
        if (x >= 0 && y >= 0) {
            if (images.length > 1)
                sb.append("; ");
            sb.append("X=");
            sb.append(x);
            if (w > 0) {
                sb.append("/");
                sb.append(w);
            }
            sb.append("; Y=");
            sb.append(y);
            if (h > 0) {
                sb.append("/");
                sb.append(h);
            }
            if (image != null) {
                final Raster r = image.getRaster();
                final double[] pix = r.getPixel(x, y, (double[]) null);
                sb.append("; value");
                sb.append(pix.length > 1 ? "s=(" : "=");
                for (int i = 0; i < pix.length; i++) {
                    if (i > 0)
                        sb.append(", ");
                    sb.append(pix[i]);
                }
                if (pix.length > 1)
                    sb.append(")");
                sb.append("; type=");
                final int pixelType = AWTImageTools.getPixelType(image);
                sb.append(FormatTools.getPixelTypeString(pixelType));
            }
        }
        sb.append(" ");
        probeLabel.setText(sb.toString());
    }

    /**
     * Toggles wait cursor.
     */
    protected void wait(final boolean wait) {
        setCursor(wait ? Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) : null);
    }

    /**
     * Opens from the given data source using the specified reader in a separate
     * thread.
     */
    protected void open(final String id, final Reader r) {
        new Thread("ImageViewer-Opener") {

            @Override
            public void run() {
                try {
                    myReader.close();
                } catch (final IOException exc) {
                    logService.info("", exc);
                }
                myReader = r;
                open(id);
            }
        }.start();
    }

    /**
     * Saves to the given data destination using the specified writer in a
     * separate thread.
     */
    protected void save(final String id, final Writer w) {
        new Thread("ImageViewer-Saver") {

            @Override
            public void run() {
                try {
                    myWriter.close();
                } catch (final IOException exc) {
                    logService.info("", exc);
                }
                myWriter = w;
                save(id);
            }
        }.start();
    }
}

15 View Complete Implementation : ConvertImg.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
private static void convertImg(final File file) throws Exception {
    final Context c = new Context();
    final SCIFIOConfig config = new SCIFIOConfig().imgOpenerSetImgModes(ImgMode.ARRAY);
    final ImgPlus<?> img = new ImgOpener(c).openImgs(new FileLocation(file.getAbsolutePath()), config).get(0);
    final String outPath = file.getParent() + File.separator + "out_" + img.getName();
    new ImgSaver(c).saveImg(new FileLocation(outPath), img);
    c.dispose();
}

15 View Complete Implementation : AbstractSyntheticWriterTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scifio
public void testWriting(final ImgPlus<?> sourceImg, final SCIFIOConfig config) throws IOException {
    final FileLocation out = createTempFileLocation(suffix);
    final Context ctx = new Context();
    new ImgSaver(ctx).saveImg(out, sourceImg, config);
    final ImgPlus<?> written = new ImgOpener(ctx).openImgs(out).get(0);
    replacedertEquals(ImageHash.hashImg(written), ImageHash.hashImg(sourceImg));
}

15 View Complete Implementation : DefaultJupyterService.java
Copyright Apache License 2.0
Author : scijava
/**
 * @author Hadrien Mary
 */
@Plugin(type = Service.clreplaced)
public clreplaced DefaultJupyterService extends AbstractService implements JupyterService {

    @Parameter
    private transient LogService log;

    @Parameter
    private transient Context context;

    @Parameter
    private transient CommandService command;

    /* Install kernel */
    @Override
    public void installKernel(String... args) {
        Map<String, Object> parameters = parseArgumentsInstall(args);
        // TODO : Ensure parameters contains the appropriate keys.
        installKernel((String) parameters.get("logLevel"), (String) parameters.get("pythonBinaryPath"), (String) parameters.get("clreplacedpath"), (String) parameters.get("javaBinaryPath"));
    }

    @Override
    public void installKernel(String logLevel, String pythonBinaryPath) {
        installKernel(logLevel, Paths.get(pythonBinaryPath));
    }

    @Override
    public void installKernel(String logLevel, Path pythonBinaryPath) {
        installKernel(logLevel, pythonBinaryPath.toFile());
    }

    @Override
    public void installKernel(String logLevel, File pythonBinaryPath) {
        installKernel(logLevel, pythonBinaryPath, null, null);
    }

    @Override
    public void installKernel(String logLevel, String pythonBinaryPath, String clreplacedpath, String javaBinaryPath) {
        installKernel(logLevel, new File(pythonBinaryPath), clreplacedpath, javaBinaryPath);
    }

    @Override
    public void installKernel(String logLevel, File pythonBinaryPath, String clreplacedpath, String javaBinaryPath) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("logLevel", logLevel);
        parameters.put("pythonBinaryPath", pythonBinaryPath);
        parameters.put("clreplacedpath", clreplacedpath);
        parameters.put("javaBinaryPath", new File(javaBinaryPath));
        command.run(InstallScijavaKernel.clreplaced, true, parameters);
    }

    /* Run kernel */
    @Override
    public void runKernel(String... args) {
        Map<String, Object> parameters = parseArgumentsRun(args);
        // TODO : Ensure parameters contains the appropriate keys.
        runKernel((String) parameters.get("logLevel"), (String) parameters.get("connectionFile"));
    }

    @Override
    public void runKernel(String logLevel, String connectionFile) {
        runKernel(logLevel, Paths.get(connectionFile));
    }

    @Override
    public void runKernel(String logLevel, File connectionFile) {
        runKernel(logLevel, connectionFile.toPath());
    }

    @Override
    public void runKernel(String logLevel, Path connectionFile) {
        KernelRunner.run(() -> {
            String id = uuid();
            // Setup configuration
            ScijavaKernelConfigurationFile config = new ScijavaKernelConfigurationFile(this.context, logLevel, connectionFile);
            // Setup the socket
            KernelSocketsFactoryImpl kernelSocketsFactory = new KernelSocketsFactoryImpl(config);
            // Setup the evaluator
            ScijavaEvaluator evaluator = new ScijavaEvaluator(context, id, id);
            // Launch the kernel
            return new ScijavaKernel(context, id, evaluator, config, kernelSocketsFactory);
        });
    }

    /* Helpers private method */
    private Map<String, Object> parseArgumentsRun(final String... args) {
        if (args.length > 0) {
            try {
                Options options = new Options();
                options.addOption("connectionFile", true, "Connection File Path");
                options.addOption("verbose", true, "Verbose Mode");
                CommandLineParser parser = new DefaultParser();
                CommandLine cmd = parser.parse(options, args);
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("connectionFile", cmd.getOptionValue("connectionFile"));
                parameters.put("logLevel", cmd.getOptionValue("verbose"));
                return parameters;
            } catch (ParseException ex) {
                log.error("Error parsing arguments : " + ex.toString());
            }
        } else {
            log.error("No parameters preplaceded to the Scijava kernel.");
        }
        return null;
    }

    private Map<String, Object> parseArgumentsInstall(final String... args) {
        if (args.length > 0) {
            try {
                Options options = new Options();
                options.addOption("pythonBinaryPath", true, "Python Binary Path");
                options.addOption("verbose", true, "Verbose Mode");
                options.addOption("clreplacedpath", true, "Additional JAVA clreplacedpath ?");
                options.addOption("javaBinaryPath", true, "Java Binary Path");
                CommandLineParser parser = new DefaultParser();
                CommandLine cmd = parser.parse(options, args);
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("pythonBinaryPath", cmd.getOptionValue("pythonBinaryPath"));
                parameters.put("logLevel", cmd.getOptionValue("verbose"));
                if (cmd.getOptionValue("clreplacedpath") != null) {
                    parameters.put("clreplacedpath", cmd.getOptionValue("clreplacedpath"));
                } else {
                    parameters.put("clreplacedpath", null);
                }
                if (cmd.getOptionValue("javaBinaryPath") != null) {
                    parameters.put("javaBinaryPath", cmd.getOptionValue("javaBinaryPath"));
                } else {
                    parameters.put("javaBinaryPath", null);
                }
                return parameters;
            } catch (ParseException ex) {
                log.error("Error parsing arguments : " + ex.toString());
            }
        } else {
            log.error("No parameters preplaceded to the Scijava kernel.");
        }
        return null;
    }
}

15 View Complete Implementation : TestRunKernel.java
Copyright Apache License 2.0
Author : scijava
public static void main(final String[] args) {
    // Warning : if run from your IDE the clreplacedpath won't be set to your Fiji installation
    Context context = new Context();
    JupyterService jupyter = context.service(JupyterService.clreplaced);
    jupyter.runKernel("jython", "info", "");
    context.dispose();
}

15 View Complete Implementation : Utils.java
Copyright GNU General Public License v3.0
Author : tferr
/**
 * Opens the specified file in the ImageJ2 Script Editor. No tests replacedessing
 * the existence of the specified file are performed.
 *
 * @param file
 *            the file to be opened
 *
 * @see #openScript(String, String)
 * @see #openIJ1Script(String, String)
 */
public static void openIJ2Script(final File file) {
    // retrieve the ImageJ application context
    // https://github.com/imagej/imagej-tutorials/tree/master/call-modern-from-legacy
    final Context context = (Context) IJ.runPlugIn("org.scijava.Context", "");
    final TextEditor editor = new TextEditor(context);
    editor.createNewFromTemplate(file, null);
    // final TextEditor.Tab tab = editor.open(file);
    // tab.setVisible(true); // TODO. Allow doreplacedent to be opened in tabs!
    editor.setVisible(true);
}

14 View Complete Implementation : REPLEditor.java
Copyright BSD 2-Clause "Simplified" License
Author : scenerygraphics
/**
 * <Description>
 *
 * @author Ulrik Günther <[email protected]>
 */
public clreplaced REPLEditor extends EditorPane {

    protected ScriptREPL repl;

    @Parameter
    Context context;

    @Parameter
    private ScriptService scriptService;

    protected OutputPane outputPane;

    protected VarsPane varsPane;

    protected boolean executing = false;

    public REPLEditor(ScriptREPL repl, VarsPane vars, OutputPane output) {
        super();
        this.repl = repl;
        this.outputPane = output;
        this.varsPane = vars;
    }

    @Override
    protected void processKeyEvent(KeyEvent e) {
        if (executing) {
            e.consume();
            return;
        }
        if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_UP) {
            walk(false);
            e.consume();
            return;
        }
        if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_DOWN) {
            walk(true);
            e.consume();
            return;
        }
        if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_ENTER) {
            String text = getText();
            if (text.length() == 0) {
                e.consume();
                return;
            }
            if (text.endsWith("\n")) {
                System.out.println("Truncating whitespace");
                text = text.substring(0, text.length() - 1);
            }
            outputPane.append(">> " + text + "\n");
            executing = true;
            String finalText = text;
            threadService().run(() -> {
                final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
                ctx.setErrorWriter(outputPane.getOutputWriter());
                ctx.setWriter(outputPane.getOutputWriter());
                final boolean result = repl.evaluate(finalText);
                threadService().queue(() -> {
                    executing = false;
                    if (!result) {
                        outputPane.append("Umm, error occured\n");
                        System.out.println("Umm, error occured");
                    }
                    varsPane.update();
                });
            });
            setText("");
            e.consume();
        } else {
            super.processKeyEvent(e);
            e.consume();
        }
    }

    private void walk(boolean forward) {
        setText(repl.getInterpreter().walkHistory(getText(), forward));
    }

    private ThreadService threadService() {
        // HACK: Get the SciJava context from the REPL.
        // This can be fixed if/when the REPL offers a getter for it.
        final Context ctx = (Context) // 
        ClreplacedUtils.getValue(Types.field(repl.getClreplaced(), "context"), repl);
        return ctx.service(ThreadService.clreplaced);
    }

    void setREPLLanguage(String language) {
        System.out.println("Resetting language to " + language);
        if (!repl.getInterpreter().getLanguage().getNames().contains(language)) {
            repl.lang(language);
        }
        ScriptLanguage l = scriptService.getLanguageByName(language);
        setLanguage(scriptService.getLanguageByName(language));
        final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
        ctx.setErrorWriter(outputPane.getOutputWriter());
        ctx.setWriter(outputPane.getOutputWriter());
    }
}

14 View Complete Implementation : ScijavaEvaluator.java
Copyright Apache License 2.0
Author : scijava
/**
 * @author Hadrien Mary
 */
public clreplaced ScijavaEvaluator implements Evaluator {

    public static final String DEFAULT_LANGUAGE = "groovy";

    @Parameter
    private LogService log;

    @Parameter
    private transient ScriptService scriptService;

    @Parameter
    private ThreadService threadService;

    @Parameter
    Context context;

    private final Map<String, ScriptEngine> scriptEngines;

    private final Map<String, ScriptLanguage> scriptLanguages;

    private final Map<String, AutoCompleter> completers;

    private String languageName;

    protected String shellId;

    protected String sessionId;

    public ScijavaEvaluator(Context context, String shellId, String sessionId) {
        context.inject(this);
        this.shellId = shellId;
        this.sessionId = sessionId;
        this.scriptEngines = new HashMap<>();
        this.scriptLanguages = new HashMap<>();
        this.completers = new HashMap<>();
        this.languageName = DEFAULT_LANGUAGE;
    }

    @Override
    public void setShellOptions(EvaluatorParameters kp) throws IOException {
        log.debug("Set shell options : " + kp);
    }

    @Override
    public AutocompleteResult autocomplete(String code, int index) {
        // Get only the line corresponding to the index.
        List<String> lines = Arrays.asList(code.substring(0, index).split("\n"));
        String line = lines.get(lines.size() - 1);
        // TODO: we need to find a way the language related to the current cell.
        // For now, we are just using the last used language.
        AutoCompleter completer = this.completers.get(this.languageName);
        ScriptEngine scriptEngine = this.scriptEngines.get(this.languageName);
        List<String> matches;
        int startIndex;
        if (completer != null) {
            AutoCompletionResult result = completer.autocomplete(line, index, scriptEngine);
            matches = result.getMatches();
            startIndex = index;
        } else {
            matches = new ArrayList<>();
            startIndex = 0;
        }
        // Reconstruct each matches with the correct index
        List<String> newMatches = new ArrayList<>();
        String newLine;
        for (String match : matches) {
            lines.set(lines.size() - 1, match);
            newLine = lines.stream().collect(Collectors.joining("\n"));
            newMatches.add(newLine.substring(startIndex, newLine.length()));
        }
        return new AutocompleteResult(newMatches, startIndex);
    }

    @Override
    public void killAllThreads() {
        log.debug("Kill All Threads");
        // Ugly and not working :-(
        System.exit(0);
    }

    @Override
    public void evaluate(SimpleEvaluationObject seo, String code) {
        code = this.setLanguage(code);
        Worker worker = new Worker(this.context, this.scriptEngines, this.scriptLanguages);
        worker.setup(seo, code, this.languageName);
        this.threadService.queue(getClreplaced().getName(), worker);
    }

    @Override
    public void exit() {
        log.debug("Exiting DefaultEvaluator");
        // Ugly and not working :-(
        System.exit(0);
    }

    private void addLanguage(String langName) {
        if (scriptService.getLanguageByName(langName) == null) {
            log.error("Script Language for '" + langName + "' not found.");
            System.exit(1);
        }
        if (!this.scriptLanguages.keySet().contains(langName)) {
            Bindings bindings = null;
            if (!this.scriptEngines.isEmpty()) {
                String firstLanguage = this.scriptEngines.keySet().iterator().next();
                bindings = this.scriptEngines.get(firstLanguage).getBindings(ScriptContext.ENGINE_SCOPE);
            }
            log.info("Script Language for '" + langName + "' found.");
            ScriptLanguage scriptLanguage = scriptService.getLanguageByName(langName);
            this.scriptLanguages.put(langName, scriptLanguage);
            ScriptEngine engine = this.scriptLanguages.get(langName).getScriptEngine();
            this.scriptEngines.put(langName, engine);
            AutoCompleter completer = scriptLanguage.getAutoCompleter();
            this.completers.put(languageName, completer);
            // Not implemented yet
            // engine.setBindings(this.bindings, ScriptContext.ENGINE_SCOPE);
            if (bindings != null) {
                this.initBindings(bindings, engine, scriptLanguage);
            }
        }
        log.debug("Script Language found for '" + langName + "'");
    }

    private String setLanguage(String code) {
        if (code.startsWith("#!")) {
            // If code is composed of multiple lines
            if (code.split("\n").length > 1) {
                this.languageName = code.substring(2, code.indexOf("\n")).trim();
                // Return the code string without the first line
                code = code.substring(code.indexOf("\n") + 1);
            } else // If only one line
            {
                this.languageName = code.substring(2).trim();
                code = "";
            }
        }
        this.addLanguage(this.languageName);
        return code;
    }

    private void initBindings(Bindings bindings, ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {
        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.keySet().forEach((String key) -> {
            currentBindings.put(key, scriptLanguage.decode(bindings.get(key)));
        });
    }

    @Override
    public Clreplacedpath getClreplacedpath() {
        log.debug("addJarToClreplacedpath()");
        return null;
    }

    @Override
    public Imports getImports() {
        log.debug("addJarToClreplacedpath()");
        return null;
    }

    @Override
    public void addImport(ImportPath ip) {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public void resetEnvironment() {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public void removeImport(ImportPath ip) {
        log.debug("addJarToClreplacedpath()");
    }

    @Override
    public List<Path> addJarsToClreplacedpath(List<PathToJar> list) {
        log.debug("addJarsToClreplacedpath()");
        return null;
    }

    @Override
    public boolean addJarToClreplacedpath(PathToJar ptj) {
        log.debug("addJarToClreplacedpath()");
        return true;
    }

    @Override
    public void cancelExecution() {
        log.debug("cancelExecution()");
    }

    @Override
    public Path getTempFolder() {
        log.debug("getTempFolder()");
        try {
            return FileUtils.createTemporaryDirectory("scijava-jupyter-kernel", null).toPath();
        } catch (final IOException exc) {
            throw new RuntimeException(exc);
        }
    }

    @Override
    public Clreplaced<?> loadClreplaced(String clazzName) throws ClreplacedNotFoundException {
        log.debug("loadClreplaced()");
        final ClreplacedLoader ccl = Thread.currentThread().getContextClreplacedLoader();
        final ClreplacedLoader cl = ccl == null ? ClreplacedLoader.getSystemClreplacedLoader() : ccl;
        return cl.loadClreplaced(clazzName);
    }
}

14 View Complete Implementation : Tutorials.java
Copyright GNU General Public License v3.0
Author : tferr
/**
 * Loads a new instance of the Script editor with jarified tutorial files
 */
@Plugin(type = Command.clreplaced, menu = { @Menu(label = "BAR"), @Menu(label = "Help", weight = 0.01d), @Menu(label = "Open Interactive Tutorials...") })
public clreplaced Tutorials implements Command {

    @Parameter
    private Context context;

    @Parameter
    private UIService uiService;

    @Parameter
    private StatusService statusService;

    @Parameter(label = "Which introductory tutorial?", choices = { "Python", "BeanShell" })
    private String lang;

    @Override
    public void run() {
        final ArrayList<URL> urls = getTutorialFiles(lang);
        if (urls == null || urls.isEmpty()) {
            uiService.showDialog("Could not load tutorial files.", DialogPrompt.MessageType.ERROR_MESSAGE);
            return;
        }
        // Ensure files are opened in the right order
        urls.sort(new Comparator<URL>() {

            @Override
            public int compare(final URL u1, final URL u2) {
                return u1.toString().compareTo(u2.toString());
            }
        });
        final TextEditor editor = new TextEditor(context);
        for (final URL url : urls) {
            statusService.showStatus(urls.indexOf(url), urls.size(), "Opening tutorial files...");
            editor.loadTemplate(url);
        }
        editor.switchTo(0);
        editor.setVisible(true);
        editor.setreplacedle("BAR Tutorial Files [" + lang + "]");
        statusService.clearStatus();
    }

    private String getMatcherPattern(final String language) {
        // see http://docs.oracle.com/javase/tutorial/essential/io/find.html
        switch(language.toLowerCase()) {
            case "python":
                return "glob:**.py";
            case "beanshell":
                return "glob:**.bsh";
            case "groovy":
                return "glob:**.{groovy,gvy}";
            default:
                // any extension
                return "glob:**.*";
        }
    }

    /* See http://stackoverflow.com/a/28057735 for details */
    private ArrayList<URL> getTutorialFiles(final String language) {
        final String dir = "tutorials";
        final ArrayList<URL> urlList = new ArrayList<>();
        final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(getMatcherPattern(language));
        try {
            final URI uri = Utils.getBARresource(dir).toURI();
            FileSystem fileSystem = null;
            Path path;
            if ("jar".equals(uri.getScheme())) {
                fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
                path = fileSystem.getPath(dir);
            } else {
                path = Paths.get(uri);
            }
            final Stream<Path> walk = Files.walk(path, 1);
            final Iterator<Path> it = walk.iterator();
            while (it.hasNext()) {
                final Path p = it.next();
                if (matcher.matches(p)) {
                    urlList.add(p.toUri().toURL());
                }
            }
            walk.close();
            if (fileSystem != null)
                fileSystem.close();
        } catch (IOException | URISyntaxException exc) {
            return null;
        }
        return urlList;
    }

    public static void main(final String... args) {
        final ImageJ ij = net.imagej.Main.launch(args);
        ij.command().run(Tutorials.clreplaced, true);
    }
}

13 View Complete Implementation : AllScripts.java
Copyright BSD 2-Clause "Simplified" License
Author : scenerygraphics
static public void main(String[] args) {
    SceneryBase.xinitThreads();
    System.setProperty("scijava.log.level:sc.iview", "debug");
    Context context = new Context(ImageJService.clreplaced, SciJavaService.clreplaced, SCIFIOService.clreplaced, ThreadService.clreplaced, ScriptService.clreplaced, LogService.clreplaced);
    // For developer debugging
    // UIService ui = context.service( UIService.clreplaced );
    // if( !ui.isVisible() ) ui.showUI();
    IOService io = context.service(IOService.clreplaced);
    OpService ops = context.service(OpService.clreplaced);
    LogService log = context.service(LogService.clreplaced);
    SciViewService sciViewService = context.service(SciViewService.clreplaced);
    SciView sciView = sciViewService.getOrCreateActiveSciView();
    ScriptService scriptService = context.service(ScriptService.clreplaced);
    File cubeFile = null;
    Dataset img = null;
    try {
        cubeFile = ResourceLoader.createFile(AllScripts.clreplaced, "/cored_cube_var2_8bit.tif");
        img = (Dataset) io.open(cubeFile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    HashMap<String, Object> testMap = new HashMap<>();
    testMap.put("sciView", sciView);
    testMap.put("img", img);
    HashMap<String, String> testScripts = new HashMap<String, String>();
    testScripts.put("/scripts/sphere_test.py", "/outputs/sphere_test.png");
    testScripts.put("/scripts/volume_test.py", "/outputs/volume_test.png");
    for (String scriptPath : testScripts.keySet()) {
        String outputPath = testScripts.get(scriptPath);
        try {
            File scriptFile = ResourceLoader.createFile(AllScripts.clreplaced, scriptPath);
            File targetFile = ResourceLoader.createFile(AllScripts.clreplaced, outputPath);
            Img<UnsignedByteType> targetOutput = (Img<UnsignedByteType>) io.open(targetFile.getAbsolutePath());
            // Reset the scene to initial configuration
            sciView.reset();
            Thread.sleep(20);
            // Run script and block until done
            Future<ScriptModule> res = scriptService.run(scriptFile, true, testMap);
            while (!res.isDone()) {
                Thread.sleep(20);
            }
            // Get the output generated by evaluating the script
            Img<UnsignedByteType> scriptOutput = sciView.getScreenshot();
            // Look at the difference between the current target and the
            IterableInterval<UnsignedByteType> diff = ops.math().subtract(targetOutput, (IterableInterval<UnsignedByteType>) scriptOutput);
            RealType sumDiff = ops.stats().sum(diff);
            replacedert.replacedertEquals(sumDiff.getRealDouble(), 0, 0.1);
            // log.warn("Test: " + scriptPath + " preplaceded" );
            System.out.println("Test: " + scriptPath + " preplaceded");
        // For developer debugging
        // ui.show("Diff", diff);
        } catch (IOException | ScriptException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

13 View Complete Implementation : Worker.java
Copyright Apache License 2.0
Author : scijava
public clreplaced Worker implements Runnable {

    @Parameter
    private LogService log;

    @Parameter
    private Context context;

    @Parameter
    private PluginService pluginService;

    @Parameter
    private ConvertService convertService;

    private final Map<String, ScriptEngine> scriptEngines;

    private final Map<String, ScriptLanguage> scriptLanguages;

    private String languageName;

    SimpleEvaluationObject seo = null;

    String code = null;

    Worker(Context context, Map<String, ScriptEngine> scriptEngines, Map<String, ScriptLanguage> scriptLanguages) {
        context.inject(this);
        this.scriptEngines = scriptEngines;
        this.scriptLanguages = scriptLanguages;
    }

    public void setup(SimpleEvaluationObject seo, String code, String languageName) {
        this.seo = seo;
        this.code = code;
        this.languageName = languageName;
    }

    @Override
    public void run() {
        ScriptLanguage scriptLanguage = this.scriptLanguages.get(this.languageName);
        ScriptEngine scriptEngine = this.scriptEngines.get(this.languageName);
        final Reader input = new StringReader(this.code);
        final ScriptInfo info = new ScriptInfo(context, "dummy.py", input);
        info.setLanguage(scriptLanguage);
        this.seo.setOutputHandler();
        try {
            // create the ScriptModule instance
            final ScriptModule module = info.createModule();
            context.inject(module);
            // HACK: Inject our cached script engine instance, rather
            // than letting the ScriptModule instance create its own.
            final Field f = ClreplacedUtils.getField(ScriptModule.clreplaced, "scriptEngine");
            ClreplacedUtils.setValue(f, module, scriptEngine);
            // execute the code
            final List<PreprocessorPlugin> pre = pluginService.createInstancesOfType(PreprocessorPlugin.clreplaced);
            final List<PostprocessorPlugin> post = pluginService.createInstancesOfType(PostprocessorPlugin.clreplaced);
            final ModuleRunner runner = new ModuleRunner(context, module, pre, post);
            runner.run();
            // acreplacedulate the outputs into an ordered map
            final Map<String, Object> outputTable = new LinkedHashMap<>();
            info.outputs().forEach(output -> {
                final String name = output.getName();
                final Object value = output.getValue(module);
                if (value != null) {
                    outputTable.put(name, value);
                }
            });
            // convert result into a notebook-friendly form
            Object output = null;
            try {
                if (outputTable.size() == 0) {
                    output = null;
                } else if (outputTable.size() == 1) {
                    output = outputTable.values().toArray()[0];
                    if (!(output instanceof MIMEContainer)) {
                        output = convertService.convert(output, NotebookOutput.clreplaced);
                        if (output == null) {
                            log.warn("[WARNING] No suitable converter found");
                            output = outputTable.values().toArray()[0];
                        }
                    }
                } else {
                    output = convertService.convert(outputTable, NotebookOutput.clreplaced);
                    if (output == null) {
                        log.warn("[WARNING] No suitable converter found");
                        output = outputTable;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                output = "[ERROR]";
            } finally {
                this.seo.finished(output);
            }
            this.syncBindings(scriptEngine, scriptLanguage);
        } catch (final ThreadDeath ex) {
            seo.error("Execution canceled");
            log.error(ex);
        } catch (final ModuleException t) {
            seo.error(t.getMessage());
            log.error(t);
        }
        this.seo.clrOutputHandler();
        this.seo.executeCodeCallback();
    }

    private void syncBindings(ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {
        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        this.scriptEngines.forEach((String name, ScriptEngine engine) -> {
            Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
            currentBindings.keySet().forEach((String key) -> {
                bindings.put(key, scriptLanguage.decode(currentBindings.get(key)));
            });
        });
    }
}

13 View Complete Implementation : TestInstallKernel.java
Copyright Apache License 2.0
Author : scijava
public static void main(String... args) {
    String pythonBinaryPath = "/home/hadim/local/conda/bin/python";
    Context context = new Context();
    JupyterService jupyter = context.service(JupyterService.clreplaced);
    ScriptService scriptService = context.service(ScriptService.clreplaced);
    // jupyter.installKernel("groovy", "info", pythonBinaryPath);
    System.out.println(scriptService.getLanguages());
    context.dispose();
}

13 View Complete Implementation : Runner.java
Copyright GNU General Public License v3.0
Author : tferr
/**
 * Runs a JARified script *
 */
@Plugin(type = Command.clreplaced)
public clreplaced Runner {

    @Parameter
    private Context context;

    @Parameter
    private ScriptService scriptService;

    @Parameter
    private LogService logService;

    @Parameter
    private UIService uiService;

    @Parameter
    private Boolean silent;

    @Parameter
    private Boolean loaded;

    @Parameter
    private String exitStatus;

    @Parameter
    private URL lastLoadedURL;

    /* exit status */
    private static final String WAS_CANCELED = "canceled";

    private static final String WAS_DONE = "done";

    private static final String WAS_LOADED = "loaded";

    private static final String IO_ERROR = "io error";

    private static final String EXCEPTION = "exception";

    /**
     * Default constructor-based dependency injection
     */
    public Runner(final Context context) {
        context.inject(this);
        setSilent(false);
    }

    /**
     * Constructor relying on IJ1.
     *
     * @param silent
     *            if errors should be ignored by the {@link LogService}
     */
    public Runner(final boolean silent) {
        if (context == null)
            context = (Context) IJ.runPlugIn("org.scijava.Context", "");
        if (scriptService == null)
            scriptService = context.getService(ScriptService.clreplaced);
        if (logService == null)
            logService = context.getService(LogService.clreplaced);
        if (uiService == null)
            uiService = context.getService(UIService.clreplaced);
        setSilent(silent);
    }

    /**
     * Debug method *
     */
    public static void main(final String... args) throws Exception {
        final ImageJ ij = net.imagej.Main.launch(args);
        final Runner runner = new Runner(ij.context());
        runner.runScript("Data_replacedysis", "Distribution_Plotter.ijm");
    }

    private void runScript(final URL url, final String filename, final Map<String, Object> inputMap) {
        try {
            runScript(url.openStream(), filename, inputMap);
            lastLoadedURL = url;
        } catch (final IOException exc) {
            error("Could not run " + url.toString(), IO_ERROR);
            exc.printStackTrace();
        }
    }

    /**
     * Runs a script from an InputStream.
     *
     * @param in
     *            the {@link InputStream} loading the script to be executed
     * @param filename
     *            the script filename (or at least its extension)
     */
    public void runScript(final InputStream in, final String filename) {
        runScript(in, filename, null);
    }

    /**
     * Runs a (JARified) BAR script.
     *
     * @param path
     *            the path of the BAR script to be executed, e.g,
     *            {@code scripts/BAR/Data_replacedysis/Distribution_Plotter.ijm};
     */
    public void runScript(final String path) {
        runScript(Utils.getBARresource(path), path, null);
    }

    /**
     * Runs a (JARified) BAR script.
     *
     * @param path
     *            the path of the BAR script to be executed, e.g,
     *            {@code /scripts/BAR/Data_replacedysis/Distribution_Plotter.ijm};
     * @param inputMap
     *            see {@link ScriptService#run(String, Reader, boolean, Map)}
     */
    public void runScript(final String path, final Map<String, Object> inputMap) {
        runScript(Utils.getBARresource(path), path, inputMap);
    }

    /**
     * Runs a (JARified) BAR script.
     *
     * @param dir
     *            the script directory, i.e., the subdirectory in the BAR jar
     *            relative to {@code scripts/BAR/}
     * @param file
     *            the script filename (or at least its extension)
     * @param inputMap
     *            see {@link ScriptService#run(String, Reader, boolean, Map)}
     */
    public void runScript(final String dir, final String file, final Map<String, Object> inputMap) {
        final String path = "scripts/BAR/" + dir + "/" + file;
        runScript(Utils.getBARresource(path), file, inputMap);
    }

    /**
     * Runs a (JARified) BAR script.
     *
     * @param dir
     *            the script directory, i.e., the subdirectory in the BAR jar
     *            relative to {@code scripts/BAR/}
     * @param file
     *            the script filename
     */
    public void runScript(final String dir, final String file) {
        final String path = "scripts/BAR/" + dir + "/" + file;
        runScript(path);
    }

    /**
     * Runs a script from a jar file.
     *
     * @param in
     *            the {@link InputStream} loading the script to be executed
     * @param filename
     *            the script filename (or at least its extension)
     * @param inputMap
     *            see {@link ScriptService#run(String, Reader, boolean, Map)}
     */
    public void runScript(final InputStream in, final String filename, final Map<String, Object> inputMap) {
        if (in == null) {
            error("Could not find " + filename, IO_ERROR);
            return;
        }
        final Reader reader = new InputStreamReader(in);
        setLoaded(true);
        final Future<ScriptModule> fsm = scriptService.run(filename, reader, true, inputMap);
        if (fsm.isCancelled())
            setStatus(WAS_CANCELED);
        else if (fsm.isDone())
            setStatus(WAS_DONE);
    }

    /**
     * Legacy method that supports IJ1 macros that do not use script parameters.
     * Ported from {@link Macro_Runner#runMacroFromJar(String, String)}.
     *
     * @param path
     *            the path to the IJ1 macro in the BAR jar file relative to
     *            {@code scripts/}
     * @param arg
     *            the argument string to be retrieved through the IJ1 built-in
     *            macro function {@code getArgument()}
     */
    public void runBARMacro(final String path, final String arg) {
        runIJ1Macro("scripts/BAR/" + path, arg);
    }

    /**
     * Legacy method that supports IJ1 macros that do not use script parameters.
     * Ported from {@link Macro_Runner#runMacroFromJar(String, String)}.
     *
     * @param path
     *            the path to the IJ1 macro in the BAR jar file
     * @param arg
     *            the argument string to be retrieved through the IJ1 built-in
     *            macro function {@code getArgument()}
     */
    public void runIJ1Macro(final String path, final String arg) {
        final String macro = readContents(path, true);
        setStatus((macro == null) ? EXCEPTION : (new Macro_Runner()).runMacro(macro, arg));
    }

    public void installIJ1Macro(final String path) {
        installIJ1Macro(path, false);
    }

    public void installIJ1Macro(final String path, final boolean singleTool) {
        final String macro = readContents(path, true);
        if (macro != null) {
            final MacroInstaller mi = new MacroInstaller();
            if (singleTool) {
                mi.installSingleTool(macro);
            } else {
                mi.install(macro);
            }
        }
        setStatus((macro == null) ? EXCEPTION : path + " installed");
    }

    public String readContents(final String resourcePath) {
        return readContents(Utils.getBARresource(resourcePath), false);
    }

    private String readContents(final String resourcePath, final boolean setGlobalFlags) {
        return readContents(Utils.getBARresource(resourcePath), setGlobalFlags);
    }

    public String readContents(final URL url, final boolean setGlobalFlags) {
        String contents = null;
        try {
            final InputStream is = url.openStream();
            if (is == null) {
                if (setGlobalFlags)
                    error("Could not find " + url, IO_ERROR);
                return contents;
            }
            final InputStreamReader isr = new InputStreamReader(is);
            setLoaded(true);
            final StringBuffer sb = new StringBuffer();
            final char[] b = new char[8192];
            int n;
            while ((n = isr.read(b)) > 0) sb.append(b, 0, n);
            contents = sb.toString();
            is.close();
        } catch (final NullPointerException | IOException ignored) {
            if (setGlobalFlags)
                error("There was an error reading " + url, IO_ERROR);
        } finally {
            if (setGlobalFlags)
                lastLoadedURL = url;
        }
        return contents;
    }

    private void error(final String msg, final String status) {
        if (!silent)
            logService.error(msg);
        setStatus(status);
        setLoaded(false);
    }

    private void setStatus(final String status) {
        this.exitStatus = status;
    }

    private void setLoaded(final boolean loaded) {
        if (loaded)
            setStatus(WAS_LOADED);
        this.loaded = loaded;
    }

    /**
     * return {@code true} if the {@link LogService} is not logging errors. Note
     * that preplaceding invalid parameters to scripts may still trigger Console
     * warnings.
     */
    public Boolean isSilent() {
        return silent;
    }

    /**
     * Should {@link LogService} display errors?
     *
     * @param silent
     *            if {@code true} errors are ignored silently. Note that preplaceding
     *            invalid parameters to scripts may still trigger Console
     *            warnings.
     */
    public void setSilent(final Boolean silent) {
        this.silent = silent;
    }

    /**
     * replacedesses if last script was loaded successfully
     *
     * @return {@code true} if the last run script could not be loaded otherwise
     *         {@code false}
     */
    public boolean scriptLoaded() {
        return loaded;
    }

    /**
     * @return the exit status: {@code cancelled}, {@code done},
     *         {@code exception}, {@code loaded}, {@code io error}, or in the
     *         case of IJ1 macros loaded through legacy mechanisms the String
     *         value returned by the
     *         {@link Macro_Runner#runMacro(String, String)}
     */
    public String getStatus() {
        return exitStatus;
    }

    public void openLastLoadedResource() {
        if (lastLoadedURL == null) {
            return;
        }
        final TextEditor editor = new TextEditor(context);
        editor.loadTemplate(lastLoadedURL);
        editor.setreplacedle(FileUtils.shortenPath(lastLoadedURL.getPath(), 0));
        editor.setVisible(true);
    }

    public File getLastLoadedResource() {
        return FileUtils.urlToFile(lastLoadedURL);
    }
}

11 View Complete Implementation : SciViewTest.java
Copyright BSD 2-Clause "Simplified" License
Author : scenerygraphics
// @Test
public void nodeDeletionTest() {
    SceneryBase.xinitThreads();
    System.setProperty("scijava.log.level:sc.iview", "debug");
    Context context = new Context(ImageJService.clreplaced, SciJavaService.clreplaced, SCIFIOService.clreplaced, ThreadService.clreplaced);
    SciViewService sciViewService = context.service(SciViewService.clreplaced);
    SciView sciView = sciViewService.getOrCreateActiveSciView();
    Node sphere = sciView.addSphere();
    replacedert.replacedertEquals(sciView.getAllSceneNodes().length, 7);
    sciView.deleteNode(sphere);
    replacedert.replacedertEquals(sciView.getAllSceneNodes().length, 6);
    sciView.closeWindow();
}