org.scijava.Context Java Examples

The following examples show how to use org.scijava.Context. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultTableIOPluginBenchmark.java    From imagej-server with Apache License 2.0 6 votes vote down vote up
@BeforeClass
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.class).mapFile("large.csv", bah);
}
 
Example #2
Source File: SnippetCreator.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 assumes 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.class);
			commandService.run(Installer.class, true);
			return;
		}
	}
	if (showDialog()) {
		if (sContents.length()>0)
			saveAndOpenSnippet();
		else
			IJ.showStatus(sFilename +" was empty. No file was saved...");
	}

}
 
Example #3
Source File: SliceTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
@Before
public void setUp() {
	context = new Context(OpService.class);
	ops = context.service(OpService.class);

	in = ArrayImgs.bytes(20, 20, 21);
	out = ArrayImgs.bytes(20, 20, 21);

	// fill array img with values (plane position = value in px);

	for (final Cursor<ByteType> cur = in.cursor(); cur.hasNext();) {
		cur.fwd();
		cur.get().set((byte) cur.getIntPosition(2));
	}
}
 
Example #4
Source File: AbstractSyntheticWriterTest.java    From scifio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @param configuration Configuration to use for saving
 * @return The {@link FileLocation} saeved to.
 */
public FileLocation testOverwritingBehavior(SCIFIOConfig configuration)
	throws IOException
{
	Context ctx = new Context();
	try {
		final FileLocation saveLocation = createTempFileLocation("test" + suffix);
		ImgSaver saver = new ImgSaver(ctx);
		ImgOpener opener = new ImgOpener(ctx);
		ImgPlus<?> sourceImg = opener.openImgs(new TestImgLocation.Builder()
			.name("testimg").pixelType("uint8").axes("X", "Y").lengths(100, 100)
			.build()).get(0);

		saver.saveImg(saveLocation, sourceImg, configuration);
		saver.saveImg(saveLocation, sourceImg, configuration);
		return saveLocation;
	}
	finally {
		ctx.dispose();
	}
}
 
Example #5
Source File: TestScriptEngine.java    From scijava-jupyter-kernel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws ScriptException {
    // Only for testing purpose

    Context context = new Context();
    ScriptService scriptService = context.getService(ScriptService.class);
    ScriptLanguage scriptLanguage = scriptService.getLanguageByName("python");
    ScriptEngine engine = scriptLanguage.getScriptEngine();

    Object result = engine.eval("p=999\n555");
    System.out.println(result);

    scriptService = context.getService(ScriptService.class);
    scriptLanguage = scriptService.getLanguageByName("python");
    engine = scriptLanguage.getScriptEngine();
    
    result = engine.eval("555");
    System.out.println(result);

    context.dispose();
}
 
Example #6
Source File: ScijavaKernel.java    From scijava-jupyter-kernel with Apache License 2.0 6 votes vote down vote up
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.class);
final PluginInfo<SciJavaPlugin> display = pluginService.getPlugin(DisplayPostprocessor.class);
final PluginInfo<SciJavaPlugin> results = pluginService.getPlugin(ResultsPostprocessor.class);
pluginService.removePlugin(display);
pluginService.removePlugin(results);

JupyterService jupyter = context.service(JupyterService.class);
jupyter.runKernel(args);

context.dispose();
   }
 
Example #7
Source File: ScijavaKernel.java    From scijava-jupyter-kernel with Apache License 2.0 6 votes vote down vote up
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.");
   }
 
Example #8
Source File: TiffParser.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Constructs a new TIFF parser from the given input source. */
public TiffParser(final Context context, final DataHandle<Location> in) {
	setContext(context);
	scifio = new SCIFIO(context);
	log = scifio.log();
	this.in = in;
	doCaching = true;
	try {
		final long fp = in.offset();
		checkHeader();
		in.seek(fp);
	}
	catch (final IOException e) {}
}
 
Example #9
Source File: StatefulSerializer.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public static Map<Class<?>, List<Pair<DeserializerFactory, Double>>> getDeserializers(final Context context)
{
	if (DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY == null) {
		try {
			DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClassSortedByPriorities(
					DeserializerFactory.class,
					context));
		} catch (InstantiableException e) {
			throw new RuntimeException(e);
		}
	}
	return DESERIALIZER_FACTORIES_SORTED_BY_PRIORITY;
}
 
Example #10
Source File: ReadmeExampleTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testReadmesExample() throws Exception {
	// extract the example script
	final File readme = new File("README.md");
	final String contents = new String(FileUtils.readFile(readme), "UTF-8");
	final String telltale = String.format("```python%n");
	final int begin = contents.indexOf(telltale) + telltale.length();
	assertTrue(begin > telltale.length());
	assertTrue(contents.indexOf(telltale, begin) < 0);
	final int end = contents.indexOf(String.format("```%n"), begin);
	assertTrue(end > 0);
	final String snippet = contents.substring(begin, end);
	assertTrue(snippet.startsWith("# @ImageJ ij"));

	final Context context = new Context();
	final ScriptService script = context.getService(ScriptService.class);

	// create mock ImageJ gateway
	script.addAlias("ImageJ", Mock.class);
	final ScriptModule module =
		script.run("op-example.py", snippet, true).get();
	assertNotNull(module);
	module.run();

	final Mock ij = context.getService(Mock.class);
	assertEquals(3, ij.images.size());
	assertEquals(11.906, ij.getPixel("sinusoid", 50, 50), 1e-3);
	assertEquals(100, ij.getPixel("gradient", 50, 50), 1e-3);
	assertEquals(111.906, ij.getPixel("composite", 50, 50), 1e-3);
}
 
Example #11
Source File: CustomOpEnvironment.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private CustomOpEnvironment(final Context context,
	final OpEnvironment parent, final Collection<? extends OpInfo> infos)
{
	setContext(context);
	this.parent = parent;
	index = new OpIndex();
	// NB: If this is not performant and/or dynamic enough, we could create/use
	// a concatenating collection (see e.g. Guava's Iterables.concat method)
	// that does not copy all the elements.
	if (parent != null) index.addOps(parent.infos());
	index.addOps(infos);
}
 
Example #12
Source File: OpSearchResult.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public OpSearchResult(final Context context, final OpInfo info,
	final String baseDir)
{
	cacheService = context.getService(CacheService.class);
	convertService = context.getService(ConvertService.class);
	this.info = info;

	final Object shortSigKey = new ShortSigKey(info);
	final Object shortSigValue = cacheService.get(shortSigKey);
	if (shortSigValue == null) {
		shortSig = buildShortSig();
		cacheService.put(shortSigKey, shortSig);
	}
	else shortSig = (String) shortSigValue;

	props = new LinkedHashMap<>();

	props.put("Signature", info.toString());

	final String opType = info.getType().getName();
	props.put("Op type", opType.startsWith("net.imagej.ops.Ops$") ? //
		opType.substring(15).replace('$', '.') : opType);

	final String[] aliases = info.getAliases();
	if (aliases != null && aliases.length > 0) {
		props.put("Aliases", Arrays.toString(aliases));
	}

	props.put("Identifier", info.cInfo().getIdentifier());
	props.put("Location", ModuleSearcher.location(info.cInfo(), baseDir));
}
 
Example #13
Source File: PainteraSerialization.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public static Map<Class<?>, List<Pair<PainteraDeserializer, Double>>> getDeserializers(final Context context)
{
	if (DESERIALIZERS_SORTED_BY_PRIORITY == null) {
		try {
			DESERIALIZERS_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClassSortedByPriorities(PainteraDeserializer.class, context));
		} catch (InstantiableException e) {
			throw new RuntimeException(e);
		}
	}
	return DESERIALIZERS_SORTED_BY_PRIORITY;
}
 
Example #14
Source File: SciView.java    From sciview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Static launching method
 */
public static SciView create() throws Exception {
    SceneryBase.xinitThreads();

    System.setProperty( "scijava.log.level:sc.iview", "debug" );
    Context context = new Context( ImageJService.class, SciJavaService.class, SCIFIOService.class, ThreadService.class);

    SciViewService sciViewService = context.service( SciViewService.class );
    SciView sciView = sciViewService.getOrCreateActiveSciView();

    return sciView;
}
 
Example #15
Source File: NodePropertyEditor.java    From sciview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** HACK: Resolve injected {@link Context} and {@link Service} inputs. */
private void resolveInjectedInputs( final Module module ) {
    for( final ModuleItem<?> input : module.getInfo().inputs() ) {
        final Class<?> type = input.getType();
        if( Context.class.isAssignableFrom( type ) || Service.class.isAssignableFrom( type ) ) {
            module.resolveInput( input.getName() );
        }
    }
}
 
Example #16
Source File: TestRunKernel.java    From scijava-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {

        // Warning : if run from your IDE the classpath won't be set to your Fiji installation
        Context context = new Context();
        JupyterService jupyter = context.service(JupyterService.class);
        jupyter.runKernel("jython", "info", "");
        context.dispose();
    }
 
Example #17
Source File: InstallScijavaKernel.java    From scijava-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
    Context context = new Context();

    LogService log = context.service(LogService.class);
    log.setLevel(LogLevel.INFO);

    JupyterService jupyter = context.service(JupyterService.class);
    jupyter.installKernel(args);

    context.dispose();
}
 
Example #18
Source File: TiffSaver.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param ctx
 * @param loc
 * @throws IOException
 */
public TiffSaver(final Context ctx, final Location loc) throws IOException {
	Objects.requireNonNull(loc);
	Objects.requireNonNull(ctx);

	setContext(ctx);
	this.loc = loc;
	this.out = dataHandleService.create(loc);
	scifio = new SCIFIO(ctx);
	log = scifio.log();
}
 
Example #19
Source File: GsonHelpers.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: TiffSaver.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new TIFF saver from the given output source.
 *
 * @param out Output stream to save TIFF data to.
 */
public TiffSaver(final Context ctx, final DataHandle<Location> out) {
	if (out == null) {
		throw new IllegalArgumentException(
			"Output stream expected to be not-null");
	}
	this.out = out;
	this.loc = out.get();
	setContext(ctx);
	scifio = new SCIFIO(ctx);
	log = scifio.log();
}
 
Example #21
Source File: TiffSaver.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new TIFF saver from the given output source.
 *
 * @param out Output stream to save TIFF data to.
 * @param bytes In memory byte array handle that we may use to create extra
 *          input or output streams as required.
 */
public TiffSaver(final DataHandle<Location> out, final BytesLocation bytes) {
	setContext(new Context());

	if (out == null) {
		throw new IllegalArgumentException(
			"Output stream expected to be not-null");
	}
	if (bytes == null) {
		throw new IllegalArgumentException("Bytes expected to be not null");
	}
	this.out = out;
	this.bytes = bytes;
}
 
Example #22
Source File: ImgPlusCtxCleaningProvider.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean handles(final Object referent, final Object... params) {
	boolean matches = ImgPlus.class.isAssignableFrom(referent.getClass());
	matches = matches && params.length == 1;
	matches = matches && Context.class.isAssignableFrom(params[0].getClass());
	return matches;
}
 
Example #23
Source File: ImgPlusCtxCleaningProvider.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ImgPlusCtxCleaner(final Object imgPlus, final ReferenceQueue queue,
	final Object... params)
{
	super((ImgPlus) imgPlus, queue);
	if (params.length != 1) {
		throw new IllegalArgumentException(
			"ImgPlusCleanerRef require 1 parameter: a scijava-common Context");
	}

	try {
		ctx = (Context) params[0];
	}
	catch (final ClassCastException e) {
		throw new IllegalArgumentException(
			"ImgPlusCleanerRef: invalid parameter");
	}

	synchronized (ctx) {
		final Integer count = ctxRefs.get(ctx);

		if (count == null) {
			// Create a new entry for this context
			ctxRefs.put(ctx, 1);
		}
		else {
			// Increase the count for this context
			ctxRefs.put(ctx, ctxRefs.get(ctx) + 1);
		}
	}
}
 
Example #24
Source File: IO.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Registers the given ImgPlus with the RefManagerService in the provided
 * component's Context.
 */
private static void register(
	@SuppressWarnings("rawtypes") final List<? extends SCIFIOImgPlus> imgPlus,
	final AbstractImgIOComponent component)
{
	final Context ctx = component.getContext();
	final RefManagerService refManagerService = ctx.getService(
		RefManagerService.class);
	for (final SCIFIOImgPlus<?> img : imgPlus) {
		refManagerService.manage(img, ctx);
	}
}
 
Example #25
Source File: IO.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @param source the source to resolve
 * @param context
 * @return the resolved location or <code>null</code> if the resolving failed
 */
private static Location resolve(final String source, final Context context) {
	final LocationService loc = context.getService(
		LocationService.class);
	Location location = null;
	try {
		location = loc.resolve(source);
	}
	catch (final URISyntaxException e) {
		resolveError(source, e);
	}
	return location;
}
 
Example #26
Source File: JPEGTileDecoder.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public TileCache(final Context ctx, final int yy, final int hh) {
	ctx.inject(this);
	options.interleaved = true;
	options.littleEndian = false;
	this.yy = yy;
	this.hh = hh;
	codec = codecService.getCodec(JPEGCodec.class);
}
 
Example #27
Source File: AbstractSyntheticWriterTest.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
	ctx.dispose();
	assertEquals(ImageHash.hashImg(written), ImageHash.hashImg(sourceImg));
}
 
Example #28
Source File: ConvertImg.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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();
}
 
Example #29
Source File: FilterTest.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static SCIFIO makeSCIFIO() {
	final SCIFIO scifio = new SCIFIO();

	final Context ctx = scifio.getContext();

	final PluginInfo<Filter> enabledInfo = new PluginInfo<>(EnabledFilter.class,
		Filter.class);
	final PluginInfo<Filter> disabledInfo = new PluginInfo<>(
		DisabledFilter.class, Filter.class);

	ctx.getPluginIndex().add(enabledInfo);
	ctx.getPluginIndex().add(disabledInfo);

	return scifio;
}
 
Example #30
Source File: Utils.java    From Scripts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Opens the specified file in the ImageJ2 Script Editor. No tests assessing
 * 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 document to be opened in tabs!
	editor.setVisible(true);
}