Java源码示例:org.scijava.Context
示例1
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.");
}
示例2
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();
}
示例3
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();
}
示例4
@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));
}
}
示例5
/**
* @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();
}
}
示例6
/**
* 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...");
}
}
示例7
@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);
}
示例8
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);
}
示例9
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);
}
示例10
public static Map<Class<?>, List<Pair<SerializerFactory, Double>>> getSerializers(final Context context)
{
if (SERIALIZER_FACTORIES_SORTED_BY_PRIORITY == null) {
try {
SERIALIZER_FACTORIES_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClassSortedByPriorities(
SerializerFactory.class,
context));
} catch (InstantiableException e) {
throw new RuntimeException(e);
}
}
return SERIALIZER_FACTORIES_SORTED_BY_PRIORITY;
}
示例11
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;
}
示例12
public static Map<Class<?>, List<Pair<PainteraSerializer, Double>>> getSerializers(final Context context)
{
if (SERIALIZERS_SORTED_BY_PRIORITY == null) {
try {
SERIALIZERS_SORTED_BY_PRIORITY = Collections.unmodifiableMap(SciJavaUtils.byTargetClassSortedByPriorities(PainteraSerializer.class, context));
} catch (InstantiableException e) {
throw new RuntimeException(e);
}
}
return SERIALIZERS_SORTED_BY_PRIORITY;
}
示例13
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;
}
示例14
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();
}
示例15
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();
}
示例16
/** 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() );
}
}
}
示例17
/**
* 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;
}
示例18
/**
* Constructs an interpreter UI pane for a SciJava scripting REPL.
*
* @param context The SciJava application context to use
*/
public REPLPane(final Context context) {
context.inject(this);
output = new OutputPane(log);
final JScrollPane outputScroll = new JScrollPane(output);
outputScroll.setPreferredSize(new Dimension(440, 400));
repl = new ScriptREPL(context, output.getOutputStream());
repl.initialize();
final Writer writer = output.getOutputWriter();
final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
ctx.setErrorWriter(writer);
ctx.setWriter(writer);
vars = new VarsPane(context, repl);
vars.setBorder(new EmptyBorder(0, 0, 8, 0));
prompt = new REPLEditor(repl, vars, output);
context.inject(prompt);
prompt.setREPLLanguage("Python");
final JScrollPane promptScroll = new JScrollPane(prompt);
final JPanel bottomPane = new JPanel();
bottomPane.setLayout(new MigLayout("ins 0", "[grow,fill][pref]", "[grow,fill,align top]"));
bottomPane.add(promptScroll, "spany 2");
final JSplitPane outputAndPromptPane =
new JSplitPane(JSplitPane.VERTICAL_SPLIT, outputScroll, bottomPane);
outputAndPromptPane.setResizeWeight(1);
// outputAndPromptPane.setDividerSize(2);
mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, vars,
outputAndPromptPane);
mainPane.setDividerSize(1);
mainPane.setDividerLocation(0);
}
示例19
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) ClassUtils.getValue(//
Types.field(repl.getClass(), "context"), repl);
return ctx.service(ThreadService.class);
}
示例20
public void nestedNodeDeletionTest() 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();
Group group = new Group();
final Material material = new Material();
material.setAmbient( new Vector3f( 1.0f, 0.0f, 0.0f ) );
material.setDiffuse( new Vector3f( 1.0f, 0.0f, 0.0f ) );
material.setSpecular( new Vector3f( 1.0f, 1.0f, 1.0f ) );
final Sphere sphere = new Sphere( 1, 20 );
sphere.setMaterial( material );
sphere.setPosition( JOMLVector3.convert( new JOMLVector3(0,0,0) ) );
//sphere.setParent(group);
group.addChild(sphere);
sciView.addNode(group);
Assert.assertEquals( sciView.getAllSceneNodes().length, 7 );
sciView.deleteNode(group);
Assert.assertEquals( sciView.getAllSceneNodes().length, 6 );
sciView.closeWindow();
}
示例21
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));
}
示例22
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);
}
示例23
@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);
}
示例24
/** 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) {}
}
示例25
/**
* @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();
}
示例26
/**
* 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();
}
示例27
/**
* 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;
}
示例28
@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;
}
示例29
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);
}
}
}
示例30
/**
* 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);
}
}