= Do you want to share your own code snippet? = Let us know! Send a message to [[https://groups.google.com/forum/#!forum/cytoscape-helpdesk|Cytoscape Helpdesk]] to have your snippet included in this cookbook. <> = Examples = Look at the sample Apps [[https://github.com/cytoscape/cytoscape-samples/tree/master/|here]] (some of answers below might have no sample project yet, but most do). = Swing Application = == How to add a tabbed Panel to Control panel? == In Cytoscape desktop, there are three !CytoPanels, Control panel, data panel and result panel, located at West, south and east, respectively. New tabbed panel can be easily added to the !CytoPanel. All the app developer should do is (1) defines a JPanel, which implements the !CytoPanelComponnet; (2) register the new panel as OSGi service. The internal !CytoPanel manager will automatically pick up the newly registered service identified as !CytoPanelComponent and adds the new panel to the specified target !CytoPanel. '''Step 1''' {{{ #!java // Define a CytoPanel class public class MyCytoPanel extends JPanel implements CytoPanelComponent { ... @Override public CytoPanelName getCytoPanelName() { return CytoPanelName.WEST; } ... } }}} '''Step 2''' {{{ #!java // In the start method of your CyActivator class: // Create an instance: MyCytoPanel myPanel = new MyPanel(); // Register it as a service: registerService(bc,myCytoPanel,CytoPanelComponent.class, new Properties()); }}} == How to add an image icon (menu item) to the toolbar? == Sometimes, an app needs to add an menu item to the cytoscape menu or add an image icon on the Cytoscape toolbar. In such case, app developer needs to (1) define a class, which implements !CyAction or extends !AbstractCyAction; (2) and register the class as an OSGi service. The internal !CyAction manger of Cytoscape will pick up the registered service and create the menu item as defined. Note the methods isInToolbar() and isInMenu(), its return value true or false will determine if menu item or image icon will be created or not. '''Step 1''' {{{ #!java // Define a CyAction class public class AddImageIconAction extends AbstractCyAction { public AddImageIconAction(CySwingApplication cySwingApplication){ ... ImageIcon icon = new ImageIcon(getClass().getResource("/images/tiger.jpg")); putValue(LARGE_ICON_KEY, icon); ... } public boolean isInToolBar() { return true; } ... } }}} '''Step 2''' {{{ #!java // In the start method of your CyActivator class: // Create an instance: AddImageIconAction addImageIconAction = new AddImageIconAction(cySwingApplication); // Register it as a service: registerService(bc,addImageIconAction,CyAction.class, new Properties()); }}} == How to create a submenu? == The way to define a submenu item is similar to define a menu item. Besides the definition of menu item itself, it is also necessary to define its parent menu item, see below. '''Step 1''' {{{ #!java // Define a CyAction class public class MySubMenuItemAction extends AbstractCyAction { ... public MySubMenuItemAction(CySwingApplication cySwingApplication){ super("My Sub MenuItem..."); setPreferredMenu("Apps.My MenuItem"); //setMenuGravity(2.0f); ... } }}} '''Step 2''' {{{ #!java // In the start method of your CyActivator class: // Create an instance: MySubMenuItemAction action = new MySubMenuItemAction(cySwingApplication); // Register it as a service: registerService(bc,action,CyAction.class, new Properties()); }}} Note that apps can expose functionality using submenus, and there is a spectrum of possibilities: * To expose a single function, an app can register a single submenu (e.g., My !MenuItem) under the Apps menu (as shown above). * To expose multiple functions, an app can register a submenu under the Apps menu (e.g., My !AppMenu) and then register individual functions as sub-submenus (e.g., My !MenuItem1, My !MenuItem2, etc) under the submenu. * Apps that have more complex interfaces can add submenus under non-App menus provided they supply documentation explaining the new submenus -- this should be a rare occurrence. = Model = == How to create, modify, and destroy a network, nodes, and edges? == To create a network, get a reference to the `CyNetworkFactory` service, and tell it to create a network. With the new network, nodes and edges can be created through the `CyNetwork` interface. {{{ #!java // To get a reference of CyNetworkFactory at CyActivator class of the App CyNetworkFactory networkFactory = getService(bc, CyNetworkFactory.class); ... // Create a new network CyNetwork myNet = networkFactory.createNetwork(); // Set name for network myNet.getRow(net).set(CyNetwork.NAME, "My network"); ... // Add two nodes to the network CyNode node1 = myNet.addNode(); CyNode node2 = myNet.addNode(); // Set name for new nodes myNet.getRow(node1).set(CyNetwork.NAME, "Node1"); myNet.getRow(node2).set(CyNetwork.NAME, "Node2"); // Add an edge myNet.addEdge(node1, node2, true); // Add the network to Cytoscape CyNetworkManager networkManager = getService(bc, CyNetworkManager.class); networkManager.addNetwork(myNet); }}} Destroying networks is done through the `CyNetworkManager` service. First, in the `start` method of your `CyActivator` class: {{{ #!java // Get a CyNetworkManager CyNetworkManager netMgr = getService(bc,CyNetworkManager.class); }}} Now you can use `CyNetworkManager` in your code: {{{ #!java // Destroy a network with NetworkManager netMgr.destroyNetwork(myNet); }}} == How to determine which nodes are currently selected on a network? == The selection state of a node or edge is saved in the table associated with the network. Its attribute or column name is “selected”. Therefore, to determine the selection state of a node, we need to get the !CyRow of the node and check the value of column “selected”. There is a util class `CyTableUtil`. We can use this class to get the list of selected nodes in a network {{{ #!java //Get the selected nodes List nodes = CyTableUtil.getNodesInState(myNetwork,"selected",true); }}} == How to set the name of a network? == The network name is kept in the table associated with the network, and its column name is “name”. To set the network name, first we need to get the !CyRow of the network object, then set the “name” attribute of this row. {{{ #!java CyNetwork net = ...; String name = ...; net.getRow(net).set(CyNetwork.NAME, name); }}} == How to get the name of a network? == The network title is kept in the table associated with the network, and its column name is “name”. To get the network name/title, first we need to get the !CyRow of the network object, then get the “name” attribute of this row. {{{ #!java CyNetwork net = ...; String name = net.getRow(net).get(CyNetwork.NAME, String.class); }}} == How to set the name of a node? == The name of a node is kept in the !CyRow of the table associated with the network, and its column name is “name”. To set the node name, first we need to get the !CyRow of the node object, then set the “name” attribute of this row. {{{ #!java CyNode node = ...; String myNodeName = ...; net.getRow(node).set(CyNetwork.NAME, myNodeName); }}} == How to get the name of a node? == The name of a node is kept in the !CyRow of the table associated with the network, and its column name is “name”. To get the node name, first we need to get the !CyRow of the node object, then get the “name” attribute of this row. {{{ #!java CyNode node = ...; String myNodeName = net.getRow(node).get(CyNetwork.NAME, String.class); }}} == How to load attribute data? == There are three steps to load attributes, (1) Create a global table with key "name"; (2) populate the newly created table with the attribute data; and (3) map the new table to the target table based on the key attribute. After an attribute table is loaded, the attribute table will remain as an independent table inside Cytoscape, and its relationship to the merged table is maintained in the target table as a point or reference. The target table could be a table of node attribute, edge attribute or network table. When we look at the merged table, the newly created columns are called "virtual columns" of the merged table. In the table browser, virtual columns are colored differently from the other columns to indicated they are virtual columns. {{{ #!java // Define a task public class CreateTableTask extends AbstractTask { .... @Override public void run(TaskMonitor tm) throws IOException { // Step 1: create a new table CyTable table = tableFactory.createTable("MyAttrTable " + Integer.toString(numImports++), "name", String.class, true, true); // create a column for the table String attributeName = "MyAttributeName"; table.createColumn(attributeName, Integer.class, false); // Step 2: populate the table with some data String[] keys = {"YLL021W","YBR170C","YLR249W"}; //map to the the "name" column CyRow row = table.getRow(keys[0]); row.set(attributeName, new Integer(2)); row = table.getRow(keys[1]); row.set(attributeName, new Integer(3)); row = table.getRow(keys[2]); row.set(attributeName, new Integer(4)); // We are loading node attribute Class type = CyNode.class; // Step 3: pass the new table to MapNetworkAttrTask super.insertTasksAfterCurrentTask( new MapNetworkAttrTask(type,table,netMgr,appMgr,rootNetworkManager) ); } .... } }}} == How to remove attributes? == '''Step 1''': get the !CyTable through the network {{{ #!java // case for Node table CyTable nodeTable = network.getDefaultNodeTable(); }}} '''Step 2''': Find the column and delete it {{{ #!java if(nodeTable.getColumn(columnName)!= null){ nodeTable.deleteColumn(columnName); } }}} == How to get all the nodes with a specific attribute value? == Copy this method in your code: {{{ #!java /** * Get all the nodes with a given attribute value. * * This method is effectively a wrapper around {@link CyTable#getMatchingRows}. * It converts the table's primary keys (assuming they are node SUIDs) back to * nodes in the network. * * Here is an example of using this method to find all nodes with a given name: * * {@code * CyNetwork net = ...; * String nodeNameToSearchFor = ...; * Set nodes = getNodesWithValue(net, net.getDefaultNodeTable(), "name", nodeNameToSearchFor); * // nodes now contains all CyNodes with the name specified by nodeNameToSearchFor * } * @param net The network that contains the nodes you are looking for. * @param table The node table that has the attribute value you are looking for; * the primary keys of this table must be SUIDs of nodes in {@code net}. * @param colname The name of the column with the attribute value * @param value The attribute value * @return A set of {@code CyNode}s with a matching value, or an empty set if no nodes match. */ private static Set getNodesWithValue( final CyNetwork net, final CyTable table, final String colname, final Object value) { final Collection matchingRows = table.getMatchingRows(colname, value); final Set nodes = new HashSet(); final String primaryKeyColname = table.getPrimaryKey().getName(); for (final CyRow row : matchingRows) { final Long nodeId = row.get(primaryKeyColname, Long.class); if (nodeId == null) continue; final CyNode node = net.getNode(nodeId); if (node == null) continue; nodes.add(node); } return nodes; } }}} == How to use model objects (CyNetwork, CyNode, etc.) when writing tests? == '''Step 1'''. Include the JUnit framework as a dependency in your {{{pom.xml}}}: {{{#!xml junit junit test }}} ''Step 2''. Include the {{{model-impl}}} package as a dependency in your {{{pom.xml}}}: {{{#!xml org.cytoscape model-impl ${cytoscape.api.version} test org.cytoscape model-impl ${cytoscape.api.version} test-jar test org.cytoscape event-api ${cytoscape.api.version} test-jar test }}} Note: The test jar is missing in 3.7.2, please use 3.7.1 for cytoscape.api.version. ''Step 3''. In your testing code, use {{{NetworkTestSupport}}} to get a {{{CyNetwork}}} instance: {{{#!java import org.cytoscape.model.NetworkTestSupport; ... final NetworkTestSupport nts = new NetworkTestSupport(); final CyNetwork network = nts.getNetwork(); // Now you have a CyNetwork! }}} == How to check if an attribute exists? == What if you're not interested in an attribute's current value but simply want to check if the column was defined of not? Use {{{CyTable.getColumn(String)}}} method: {{{#!java // CyTable cyTable = ... ... if(cyTable.getColumn("foo") != null) { // found ... } }}} E.g., to check for "foo" attribute in the default network table, use: {{{#!java ... boolean exists1 = cyNetwork.getDefaultNetworkTable() .getColumn("foo") != null; }}} instead of: {{{#!java ... boolean exists2 = cyNetwork.getRow(cyNetwork) .get("foo", fooType) != null; //wrong boolean exists3 = cyNetwork.getRow(cyNetwork) .isSet("foo"); //wrong // - both cannot tell non-existing from null-value attribute. }}} (Same for the default node and edge tables.) = View Model = == Getting node views for newly created nodes? == After creating a node and edge, this is how to get its view: {{{ #!java CyNetworkView networkView = ...; CyNetwork network = networkView.getModel(); CyEventHelper eventHelper = ...; CyNode newNode = network.addNode(); network.getRow(newNode).set(CyNetwork.NAME, "New Node"); eventHelper.flushPayloadEvents(); View newNodeView = networkView.getNodeView(newNode); }}} After creating the node in {{{CyNetwork}}}, you have to call {{{CyEventHelper}}}'s {{{flushPayloadEvents}}} so that the new node gets a node view. If {{{flushPayloadEvents}}} is not called, {{{getNodeView}}} may return null. If you are creating a bunch of nodes at once, call {{{flushPayloadEvents}}} after you have finished creating all the nodes, ''not'' after each node is created. Example: {{{ #!java CyNetworkView networkView = ...; CyNetwork network = networkView.getModel(); CyEventHelper eventHelper = ...; for (int i = 1; i <= 100; i++) { CyNode node = network.addNode(); network.getRow(newNode).set(CyNetwork.NAME, "Node " + i); } eventHelper.flushPayloadEvents(); }}} == How to create, modify, and destroy a network view? == To create a network, get a reference to the `CyNetworkViewFactory` service, and tell it to create a network view. First, in the `start` method of your `CyActivator` class: {{{ #!java // Get a CyNetworkViewFactory CyNetworkViewFactory networkViewFactory = getService(bc, CyNetworkViewFactory.class); }}} Now you can use `CyNetworkViewFactory` in your code: {{{ #!java // Create a new network view CyNetworkView myView = networkViewFactory.createNetworkView(myNet); // Add view to Cytoscape CyNetworkViewManager networkViewManager = getService(bc, CyNetworkViewManager.class); networkViewManager.addNetworkView(myView); }}} Destroying network views is done through the `CyNetworkViewManager` service. First, in the `start` method of your `CyActivator` class: {{{ #!java // get a CyNetworkViewManager CyNetworkViewManager networkViewManager = getService(bc, CyNetworkViewManager.class); }}} Now you can use `CyNetworkViewManager` in your code: {{{ #!java // destroy a network view through NetworkViewManager networkViewManager.destroyNetworkView(myView); }}} == How to change the background color of a view? == Network background color is changed as a _visual property_. {{{ #!java // Set the background of current view to RED view.setVisualProperty(BasicVisualLexicon.NETWORK_BACKGROUND_PAINT, Color.red); view.updateView(); }}} == How to zoom a network view? == {{{ #!java // Get the scale and adjust double newScale = view.getVisualProperty(NETWORK_SCALE_FACTOR).doubleValue() * scale; view.setVisualProperty(NETWORK_SCALE_FACTOR, newScale); ... view.updateView(); }}} == How to get and set node coordinate positions? == Given a {{{View}}}, here's how to get its x and y coordinate positions: {{{ #!java View nodeView = ...; Double x = nodeView.getVisualProperty(BasicVisualLexicon.NODE_X_LOCATION); Double y = nodeView.getVisualProperty(BasicVisualLexicon.NODE_Y_LOCATION);}}} Here's how to set the x and y coordinate positions: {{{ #!java View nodeView = ...; double x = ...; double y = ...; nodeView.setVisualProperty(BasicVisualLexicon.NODE_X_LOCATION, x); nodeView.setVisualProperty(BasicVisualLexicon.NODE_Y_LOCATION, y);}}} == How to write a layout algorithm? == First define a layout class, which implements !CyLayoutAlgorithm interface or extends !AbstractLayoutAlgorithm class. Then register the layout class as a service. {{{ #!java // Define a layout class public class MyLayout extends AbstractLayoutAlgorithm { ... } // Define a layout task class public class MyLayoutTask extends AbstractLayoutTask { ... //Perform actual layout task final protected void doLayout(final TaskMonitor taskMonitor) { ... } ... } // Register the layout class as a service in CyActivator class Properties myLayoutProps = new Properties(); myLayoutProps.setProperty("preferredMenu","My Layouts"); registerService(bc,myLayout,CyLayoutAlgorithm.class, myLayoutProps); }}} == How to add components to the node view, edge view, and attribute browser context menus? == To add a context menu to a !NodeView, define a class, which extends !AbstractNodeViewTaskFactory, and register the !NodeViewTaskFactory as service. We can add the title of menu item by setting the service property when we register the nodeViewTaskFactory. To add context menu to the table browser, define a class, which extends !AbstractTableCellTaskFactory. Create an instance and register it as service (Note register as !TableCellTaskFactory). {{{ #!java // Define a class MyNodeViewTaskFactory public class MyNodeViewTaskFactory extends AbstractNodeViewTaskFactory { ... } // Register myNodeViewTaskFactory as a service in CyActivator Properties myNodeViewTaskFactoryProps = new Properties(); myNodeViewTaskFactoryProps.setProperty("title","My context menu title"); registerService(bc,myNodeViewTaskFactory,NodeViewTaskFactory.class, myNodeViewTaskFactoryProps); }}} Look at the sample Apps. == Code snippet for updating the network view == {{{ #!java public enum RedoLayout { YES, NO }; public enum RedoVisualStyle { YES, NO }; /** * Update a given CyNetworkView including optionally updating its layout and visual style. * @param view the CyNetworkView to layout * @param redoVS if redoVS=RedoVisualStyle.YES, apply the visual style associated with view. * @param redoLayout if redoLayout=RedoLayout.YES, apply the CyLayoutAlgorithm specified by layoutAlgorName * to view. If RedoLayout.NO, no layout is performed. * @param layoutAlgorName the name of the layout algorithm to apply. if null, the default * layout algorithm is used. If redoLayout=RedoLayout.NO * layoutAlgorName is ignored. * @throws IllegalArgumentException if layoutAlgorName is non-null, redoLayout=RedoLayout.YES, and no * layout algorithm is found. */ public static void updateView(CyNetworkView view, RedoVisualStyle redoVS, RedoLayout redoLayout, String layoutAlgorName) { if (redoLayout == RedoLayout.YES) { final CyLayoutAlgorithmManager alMan = _adapter.getCyLayoutAlgorithmManager(); CyLayoutAlgorithm algor = null; if (layoutAlgorName == null) { algor = alMan.getDefaultLayout(); } else { algor = alMan.getLayout(layoutAlgorName); } if (algor == null) { throw new IllegalArgumentException ("No such algorithm found '" + layoutAlgorName + "'."); } TaskIterator itr = algor.createTaskIterator(view, algor.createLayoutContext(), CyLayoutAlgorithm.ALL_NODE_VIEWS, null); _adapter.getTaskManager().execute(itr); // We use the synchronous task manager otherwise the visual style and updateView() // may occur before the view is relayed out: SynchronousTaskManager synTaskMan = _adapter.getCyServiceRegistrar().getService(SynchronousTaskManager.class); synTaskMan.execute(itr); } if (redoVS == RedoVisualStyle.YES) { _adapter.getVisualMappingManager().getVisualStyle(view).apply(view); } view.updateView(); } }}} == How to detect if an edge is invisible? == Cytoscape renders an edge invisible upon either of these two conditions: * A user sets the Visible property for an edge to false * A user sets the Visible property for a node, to which the edge is connected, to false It is not sufficient to check the Visible property of the edge because the property is not updated if the edge is rendered invisible because of a connected node. To address this issue, we present an isVisible method: {{{ #!java boolean isVisible(View edgeView, CyNetworkView networkView) { boolean visibleByEdgeProp = edgeView.getVisualProperty(BasicVisualLexicon.EDGE_VISIBLE); if (!visibleByEdgeProp) { return false; } CyEdge model = edgeView.getModel(); CyNode source = model.getSource(); CyNode target = model.getTarget(); View sourceView = networkView.getNodeView(source); View targetView = networkView.getNodeView(target); boolean visibleBySourceProp = sourceView.getVisualProperty(BasicVisualLexicon.NODE_VISIBLE); boolean visibleByTargetProp = targetView.getVisualProperty(BasicVisualLexicon.NODE_VISIBLE); if (!visibleBySourceProp || !visibleByTargetProp) { return false; } return true; } }}} == How to set visual property values before node and edge views exist? == Cytoscape decouples the network topology and table models from its view model. The view model specifies the appearance or visualization of nodes and edges. When nodes and edges are created in a network, their view model objects are created only after a triggering of an event (`org.cytoscape.event.CyEventHelper.flushPayloadEvents()`). This is done to prevent Cytoscape from unnecessarily redrawing the network while a task is in the process of constructing a network. But the separation of the network and table models from the view model can be problematic if you need to assign visual property values to nodes and edges that don't have views at the time of their construction. To address this issue, we present the `DelayedVizProp` class: {{{ #!java import org.cytoscape.model.CyNode; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.View; import org.cytoscape.view.model.VisualProperty; class DelayedVizProp { final CyIdentifiable netObj; final VisualProperty prop; final Object value; final boolean isLocked; /** * Specify the desired visual property value for a node or edge. * @param netObj A CyNode or CyEdge * @param prop The visual property whose value you want to assign * @param value The visual property value you want to assign * @param isLocked true if you want the value to be set as a bypass value, false if you want the value to persist until a visual style is applied to the network view */ public DelayedVizProp(final CyIdentifiable netObj, final VisualProperty prop, final Object value, final boolean isLocked) { this.netObj = netObj; this.prop = prop; this.value = value; this.isLocked = isLocked; } /** * Assign the visual properties stored in delayedProps to the given CyNetworkView. * @param netView The CyNetworkView that contains the nodes and edges for which you want to assign the visual properties * @param delayedProps A series of DelayedVizProps that specifies the visual property values of nodes and edges */ public static void applyAll(final CyNetworkView netView, final Iterable delayedProps) { for (final DelayedVizProp delayedProp : delayedProps) { final Object value = delayedProp.value; if (value == null) continue; View view = null; if (delayedProp.netObj instanceof CyNode) { final CyNode node = (CyNode) delayedProp.netObj; view = netView.getNodeView(node); } else if (delayedProp.netObj instanceof CyEdge) { final CyEdge edge = (CyEdge) delayedProp.netObj; view = netView.getEdgeView(edge); } if (delayedProp.isLocked) { view.setLockedValue(delayedProp.prop, value); } else { view.setVisualProperty(delayedProp.prop, value); } } } } }}} While building your network, create instances of `DelayedVizProp` and store them in a `List`. After calling `org.cytoscape.event.CyEventHelper.flushPayloadEvents()`, call `applyAll` on the network view that contains your nodes and edges. = VizMapper = == How to use the VizMapper programmatically? == Cytosape provides services for using visual mapping programming. These services are !VisualMappingManager, !VisualStyleFactory and !VisualMappingFunctionFactory. App should get references to these services in !CyActivator class, the entry point of the app. We can create new visualStyle with !VisualStyleFactory and create mapping function with !VisualMappingFunctionFactory very easily. After a new visual style is created, it should register with the !VisualMappingManger, in this way the new visual style will be available throughout Cytoscape. {{{ #!java // To get references to services in CyActivator class VisualMappingManager vmmServiceRef = getService(bc,VisualMappingManager.class); VisualStyleFactory visualStyleFactoryServiceRef = getService(bc,VisualStyleFactory.class); VisualMappingFunctionFactory vmfFactoryC = getService(bc,VisualMappingFunctionFactory.class, "(mapping.type=continuous)"); VisualMappingFunctionFactory vmfFactoryD = getService(bc,VisualMappingFunctionFactory.class, "(mapping.type=discrete)"); VisualMappingFunctionFactory vmfFactoryP = getService(bc,VisualMappingFunctionFactory.class, "(mapping.type=passthrough)"); // To create a new VisualStyle object and set the mapping function VisualStyle vs= this.visualStyleFactoryServiceRef.createVisualStyle("My visual style"); //Use pass-through mapping String ctrAttrName1 = "SUID"; PassthroughMapping pMapping = (PassthroughMapping) vmfFactoryP.createVisualMappingFunction(ctrAttrName1, String.class, attrForTest, BasicVisualLexicon.NODE_LABEL); vs.addVisualMappingFunction(pMapping); // Add the new style to the VisualMappingManager vmmServiceRef.addVisualStyle(vs); // Apply the visual style to a NetwokView vs.apply(myNetworkView); myNetworkView.updateView(); }}} Look at the sample App. == How to apply a continuous color gradient to nodes according to their degree? == {{{ #!java // Set node color map to attribute "Degree" ContinuousMapping mapping = (ContinuousMapping) this.continuousMappingFactoryServiceRef.createVisualMappingFunction("Degree", Integer.class, BasicVisualLexicon.NODE_FILL_COLOR); // Define the points Double val1 = 2d; BoundaryRangeValues brv1 = new BoundaryRangeValues(Color.RED, Color.GREEN, Color.PINK); Double val2 = 12d; BoundaryRangeValues brv2 = new BoundaryRangeValues(Color.WHITE, Color.YELLOW, Color.BLACK); // Set the points mapping.addPoint(val1, brv1); mapping.addPoint(val2, brv2); // add the mapping to visual style vs.addVisualMappingFunction(mapping); }}} == How to load a visual properties file? == Cytoscape provide a service 'LoadVizmapFileTaskFactory' for loading visual styles definded in a property file. {{{ #!java // get a reference to Cytoscape service -- LoadVizmapFileTaskFactory LoadVizmapFileTaskFactory loadVizmapFileTaskFactory = getService(bc,LoadVizmapFileTaskFactory.class); }}} {{{ #!java // Use the service to load visual style, 'f' is the File object to hold the visual properties Set vsSet = loadVizmapFileTaskFactory.loadStyles(f); }}} = I/O = == How to build a network reader to support my own format? == First, we should define the format of my network file and its file extension. Let's say, each line in our network file has two columns, tab-delimited. And we define file extension '.tc', stands for 'two columns'. {{{ #!java //1. define a file filter (BasicCyFileFilter), to support the reader to read the file with extension '.tc' HashSet extensions = new HashSet(); extensions.add("tc"); HashSet contentTypes = new HashSet(); contentTypes.add("txt"); String description = "My test filter"; DataCategory category = DataCategory.NETWORK; BasicCyFileFilter filter = new BasicCyFileFilter(extensions,contentTypes, description, category, swingAdapter.getStreamUtil()); //2. Create an instance of the ReaderFactory // Note that extends TCReaderFactory must implement the interface InputStreamTaskFactory or extends the class AbstractInputStreamTaskFactory. // And the defined task must implement CyNetworkReader TCReaderFactory factory = new TCReaderFactory(filter, swingAdapter.getCyNetworkFactory(), swingAdapter.getCyNetworkViewFactory()); //3. register the ReaderFactory as an InputStreamTaskFactory. Properties props = new Properties(); props.setProperty("readerDescription","TC file reader"); props.setProperty("readerId","tcNetworkReader"); swingAdapter.getCyServiceRegistrar().registerService(factory, InputStreamTaskFactory.class, props); }}} Compile the following sample App, and install the app in Cytoscape. When we try to import a network from a file (File-->Import-->Network-->File..), we will find file type '.tc' is listed as one of the file types supported by Cytoscape. Look at the sample App. == How to build a table reader to support my own format? == = Work = == How to use the Cytoscape task monitor to show the progress of my job? == Get a Cytoscape service DialogTaskManager and execute the task through the taskManager. {{{ #!java // Get a Cytoscape service 'DialogTaskManager' in CyActivator class DialogTaskManager dialogTaskManager = getService(bc, DialogTaskManager.class); // Define a task and set the progress in the run() method public class MyTask extends AbstractTask { ... public void run(final TaskMonitor taskMonitor) { // Give the task a title. taskMonitor.setTitle("My task"); ... taskMonitor.setProgress(0.1); // do something here ... taskMonitor.setProgress(1.0); } // Execute the task through the TaskManager DialogTaskManager.execute(myTaskFactory); }}} == How to use Tunable? == An app might need to generate dialog and get input from user. An easy way to generate such dialog is to define a Task and use tunable annotation, and let Cytoscape generate the dialog automatically. In the Task class, define a '''public''' class field, its data type, and description as the following example: {{{ #!java @Tunable(description="Node is red?", groups="Appearence") public boolean isRed; @Tunable(description="Scale", groups={"Appearence", "Mappings"}) public double scale = 0.2; // Default value }}} will generate the following when the app is launched {{attachment:tunable.png}} When the class is initialized, a core Cytoscape service, !TunableInterceptor will inspect this class and generate UI based on the tunable annotation. In this case, a text field with attached description "scale", default value "0.2", will show up in the automatically generated dialog. Note that in above example, the data type is 'double', data type can also be 'int', 'boolean', 'String', or 'List'. If a field is defined as tunable, and its data type is 'boolean', then a radio button will be generated in the dialog. = Session = == How to save/restore app states? == There are two events, which are important for saving/restoring App state. The two evetns are !SessionAboutToBeSavedEvent and !SessionLoadedEvent. App should implement the two listeners and register them. {{{ #!java // Implements the session event listeners public class MyClass implements SessionAboutToBeSavedListener, SessionLoadedListener { // Save app state in a file public void handleEvent(SessionAboutToBeSavedEvent e){ // save app state file "myAppStateFile" ... } // restore app state from a file public void handleEvent(SessionLoadedEvent e){ if (e.getLoadedSession().getAppFileListMap() == null || e.getLoadedSession().getAppFileListMap().size() ==0){ return; } List files = e.getLoadedSession().getAppFileListMap().get("myAppStateFile"); ... } } // Register the two listeners in the CyActivator class registerService(bc,myClass,SessionAboutToBeSavedListener.class, new Properties()); registerService(bc,myClass,SessionLoadedListener.class, new Properties()); }}} == How to use CyProperty to save values across sessions? == !CyProperty acts as a container to save properties of the type (key, value) across sessions. They are available for the user to manually change in the preference menu option. Start by creating a subclass of !AbstractConfigDirPropsReader. {{{ #!java class PropsReader extends AbstractConfigDirPropsReader { public PropsReader(String name, String fileName) { super(name, fileName, CyProperty.SavePolicy.CONFIG_DIR); } } }}} Register the reader in your !CyActivator. {{{ #!java PropsReader propsReader = new PropsReader(“myApp", “myApp.props"); Properties propsReaderServiceProps = new Properties(); propsReaderServiceProps.setProperty("cyPropertyName", “myApp.props"); registerAllServices(context, propsReader, propsReaderServiceProps); }}} Next, create a file in your App resources directory that contains the property keys and their default values. {{{ myApp.firstProperty=0 myApp.secondProperty=hello }}} The default properties will be loaded from the App jar the first time your App runs. When Cytoscape shuts down the properties will be saved in the Cytoscape config directory and/or the session file depending on which !SavePolicy constant you specified. The property values can be edited by going to the menu Edit > Preferences > Properties and then selecting ‘myApp’ from the dropdown in the dialog. You can access the property reader as an OSGi service. {{{ #!java CyProperty cyProperties = getService(bc, CyProperty.class, "(cyPropertyName=myApp.props)"); String propertyValue = cyProperties.getProperty(“myApp.firstProperty”); }}} = Events = == How to handle events from a network == '''Step 1''' {{{ #!java // Define a class, which implements a listener interface public class MyListenerClass implements NetworkAddedListener { .... public void handleEvent(NetworkAddedEvent e){ // do something here } } }}} '''Step 2''' {{{ #!java // In the `start` method of your `CyActivator` class, // register the listener in the CyActivator class registerService(bc,myListenerClass, NetworkAddedListener.class, new Properties()); }}} == How to use Service listener == Cytoscape is an OSGi based application, service can be registered and unregistered in the OSGi container. An app can listen such event to react based on the service added or removed from the OSGi container. For example, the following command in !CyActivator of the sample App will register a listener, which listens to the presence or absence of !CyProperty service. {{{ #!java registerServiceListener(bc, myserviceListener, "addPropertyService", "removePropertyService", CyProperty.class); }}} The two methods addPropertyService() and removePropertyService() should be defined in !MyserviceListener. Note that the above example, will listen service event for !CyProperty only, we can also listen to other service, such as !TaskFactory, !NetworkTaskFactory, !CyLayoutAlgorithm, !CytoPanelComponent, etc. = Equations = == How to add new attribute functions via a Cytoscape App? == Here we will go through all the steps necessary to create a new built-in function IXOR(). The complete example code and can be downloaded from here. The easiest part is writing the actual plug-in class, which look similar to this: {{{ #!java import org.cytoscape.equations.EquationCompiler; import org.cytoscape.equations.Interpreter; import org.cytoscape.equations.EquationParser; public class Sample23 { public Sample23(EquationCompiler eqCompilerRef, Interpreter interpreterRef){ final EquationParser theParser = eqCompilerRef.getParser(); theParser.registerFunction(new IXor()); } } }}} Here we register a new built-in function called IXor. You can also register multiple built-in functions if you prefer. The next part is creating one class each for every new built-in. Each such class has to implement the org.cytoscape.equations.Function interface usually via org.cytoscape.equations.AbstractFunction. The easiest way to get started is to peruse the existing built-ins in equations Cytoscape core library and look for a function with a similar or identical argument list. If you can't find one it may still be instructive to read through the implementation of a couple of existing functions. First you have to create the constructor where you describe the arguments that your function will take: {{{ #!java public IXor() { super(new ArgDescriptor[] { new ArgDescriptor(ArgType.INT, "arg1", "A quantity that can be converted to an integer."), new ArgDescriptor(ArgType.INT, "arg2", "A quantity that can be converted to an integer."), }); }}} The most trivial to implement methods are getName(), and getFunctionSummary(). {{{ #!java /** * Used to parse the function string. This name is treated in a case-insensitive manner! * @return the name by which you must call the function when used in an attribute equation. */ public String getName() { return "IXOR"; } /** * Used to provide help for users. * @return a description of what this function does */ public String getFunctionSummary() { return "Returns an integer value that is the exclusive-or of 2 other integer values."; } }}} The next method is still simple but already touches on the one area that is somewhat complicated in attribute functions: data types and data type conversions! {{{ #!java public Class getReturnType() { return Long.class; } }}} Our example function is supposed to return an integer value. Integers in equation functions are represented as instances of class java.lang.Long. Therefore it is imperative not to return Integer.class! The user of the function can be blissfully unaware of this distinction. Just remember to always substitute Long for Integer and you should be fine. The next method evaluateFunction() is the one that gets called when an expression is being evaluated. No argument type-checking is needed here because the compiler already took care of that for us. But, we need to handle all possible valid argument types and counts. (N.B., functions may be overloaded and/or variadic.) In this example the arguments can be any combination of Long and Double. {{{ #!java public Object evaluateFunction(final Object[] args) { long arg1; try { arg1 = FunctionUtil.getArgAsLong(args[0]); } catch (final Exception e) { throw new IllegalArgumentException("IXOR: can't convert the 1st argument to an integer!"); } long arg2; try { arg2 = FunctionUtil.getArgAsLong(args[0]); } catch (final Exception e) { throw new IllegalArgumentException("IXOR: can't convert the 2nd argument to an integer!"); } final long result = arg1 ^ arg2; return (Long)result; } }}} [[http://wiki.cytoscape.org/Implementing_Attribute_Equations_Functions|This tutorial]] on how to write attribute functions may also be helpful. Look at the sample App. = Automation = Cytoscape Apps can be controlled via external software, such as Jupyter or R. There are two ways to expose features of an App for automation: via JAX-RS, and via Tunables/Cytoscape Command Line. Either way, or both can be utilized in the same App, depending on the developers needs and knowledge. == How to Add REST Automation via JAX-RS == The CyREST App detects services registered in Cytoscape’s environment, and exposes those that are annotated via JAX-RS. Exposing services requires two steps: === Adding JAX-RS Annotations === JAX-RS Annotations indicate to the CyREST App how an external application can pass information to and from a Java method. The sample code below illustrates a simple example: {{{ #!java @Api @Path("/basicgreeting/v1") public interface GreetingResource { @GET @Produces(MediaType.APPLICATION_JSON) public SimpleMessage greeting(); } }}} === Registering the Annotated Service === Once you have annotated methods in a Java class with JAX-RS annotation, they must be registered in your CyActivator to become visible to the CyREST App. The above class is registered in the code below: {{{ #!java public class CyActivator extends AbstractCyActivator { … public void start(BundleContext bc) { … try { registerService(bc, new GreetingResourceImpl(), GreetingResource.class, new Properties()); } catch (Exception e) { …//Deal with any exceptions here. } } } }}} The [[https://github.com/cytoscape/cytoscape-automation/tree/master/for-app-developers/cy-automation-cy-rest-basic-sample|CyREST Basic Sample App]] and the [[https://github.com/cytoscape/cytoscape-automation/tree/master/for-app-developers/cy-automation-cy-rest-best-practices-sample|CyREST Best Practices Sample App]] offer requirements for App dependencies, details on implementation, and best practices for providing automation through JAX-RS annotations. == How to Add Command Line Automation == Commands available through the Cytoscape Command Line are automatically exposed via CyREST, and can also be made available to Cytoscape menu items and dialogs. A limitation to this approach is that only a subset of the functionality of JAX-RS will be available. Exposing functionality through Commands is done by implementing Tasks, and then providing them through TaskFactories that are registered with Command properties. {{{ #!java public class YourTask extends AbstractTask { @ProvidesTitle public String getTitle() { return "Task Title Here"; } @Tunable (description="Task Description Here") public String name = null; @Override public void run(TaskMonitor arg0) throws Exception { //Your code here } } }}} A TaskFactory is implemented in the following code: {{{ #!java public class YourTaskFactory extends AbstractTaskFactory { … public boolean isReady() { return true; } public TaskIterator createTaskIterator() { return new TaskIterator(new SayHelloTask()); } } }}} A TaskFactory is registered in an App’s CyActivator in the following code: {{{ #!java public class CyActivator extends AbstractCyActivator { … public void start(BundleContext bc) throws InvalidSyntaxException { Properties yourTaskFactoryProps = new Properties(); yourTaskFactoryProps.setProperty(COMMAND_NAMESPACE, SAMPLE_COMMAND_NAMESPACE); yourTaskFactoryProps.setProperty(COMMAND, "your_commands_name"); yourTaskFactoryProps.setProperty(COMMAND_DESCRIPTION, “Your Command’s description”); yourTaskFactoryProps.setProperty(PREFERRED_MENU, "Your App"); yourTaskFactoryProps.setProperty(IN_MENU_BAR, "true"); yourTaskFactoryProps.setProperty(IN_CONTEXT_MENU, "false"); yourTaskFactoryProps.setProperty("title", "Your command’s title"); TaskFactory yourTaskFactory = new YourTaskFactory(); registerAllServices(bc, yourTaskFactory, yourTaskFactoryProps); } } }}} The [[https://github.com/cytoscape/cytoscape-automation/tree/master/for-app-developers/cy-automation-taskfactory-sample|TaskFactory Sample]] offers requirements for App dependencies, details on implementation, and best practices for providing automation for the Command Line. = Web Services = == How to use a web service client? == First define a listener of web service client and register it as service -- !WebServiceHelper. This class will keep tracker of web service clients available using a Map. {{{ #!java public class WebServiceHelper { ... public void addWebServiceClient(final WebServiceClient newFactory, final Map properties) { webserviceMap.put(newFactory, properties); } public void removeWebServiceClient(final WebServiceClient factory, final Map properties) { webserviceMap.remove(factory); } ... } }}} At running time, check if the needed service is available by looking at the map. {{{ #!java Iterator it = webserviceMap.keySet().iterator(); while (it.hasNext()){ WebServiceClient client = it.next(); // Based on the serviceLocation, we can find if the client we are looking for is available System.out.println("WebService CLient client: DisplayName() is "+client.getDisplayName()); System.out.println("WebService CLient client: ServiceLocation() is "+client.getServiceLocation()); .... } }}} If the needed client is found, then we can construct the query and execute the query through the API of the client. == How to write a web service client? == '''Step 1''': Define a UI class for the setting of the client. This UI may listen to Cytoscape events {{{ #!java public class MyWebserviceClientPanel extends JPanel implements ColumnCreatedListener, ColumnDeletedListener, SetCurrentNetworkListener { ... } }}} '''Step 2''': Define a client class, which must implement !WebServiceClient and pass the UI class defined at previous step to the client. If UI is not defined, the default UI will be used. {{{ #!java public class MyWebserviceClient extends AbstractWebServiceGUIClient implements TableImportWebServiceClient { ... } }}} '''Step 3''': After the client is registered as service, the client can be find under File-->Import->Table-->Public databases... == How to use Apache HTTP Client for working with web services == === TL;DR === Don't use `java.net.URLConnection`: it doesn't support cancellation and can be slow. Use [[http://hc.apache.org/httpcomponents-client-ga/|Apache's HTTP Client (HC)]] instead. === Introduction === Biomedical resources and databases are becoming increasingly accessible through public web services. Cytoscape apps that integrate these resources need an HTTP client to access them. The Java standard library provides such an HTTP client: `HttpURLConnection` in the `java.net` package. However, `HttpURLConnection` has some significant limitations. Most importantly, it does not support cancellation. A well-written app correctly implements the `cancel()` method in the `Task` interface, which is vital for a responsive user interface. Users who are stuck behind an interrupted internet connection would need to back out of a HTTP request. [[http://hc.apache.org/httpcomponents-client-ga/|Apache's HTTP Client (HC)]] is an alternative third-party library to `HttpURLConnection` that addresses its limitations. Here's a comparison: '''Java standard library's HttpURLConnection''' Advantages: * Included with Java * Simple to use -- an entire HTTP client in a single class Disadvantages: * No support for cancellation -- impossible to cancel an HTTP request during task execution * No pooling of connections '''[[http://hc.apache.org/httpcomponents-client-ga/|Apache's HTTP Client (HC)]]''' Advantages: * HTTP requests can be canceled * HTTP connections are pooled for improved efficiency. A connection to a server is maintained for subsequent requests. * Supports multiple, simultaneous HTTP requests Disadvantages: * Requires your app to bundle the HC library * Complex -- it's an entire library just dedicated to HTTP client functionality * All HTTP requests must be properly closed, otherwise the connection pool becomes full and becomes impossible to issue subsequent requests HC's complexity can be daunting. To help with using HC, here we present a quick guide and some tips for working with HC 4.x. === Obtaining an HttpClient instance === {{{ #!java import java.net.ProxySelector; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.SystemDefaultRoutePlanner; ... final CloseableHttpClient client = HttpClientBuilder.create() .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) // use JVM's proxy settings // add more stuff here later to configure the client .build(); }}} Notes: * Use a single client instance for your all of your app's HTTP requests. `HttpClient` is powerful enough to handle multiple web services. * Call `CloseableHttpClient.close()` when your app is done making requests. === Creating and executing an HTTP request === With `HttpClient`, you can issue HTTP requests. An `HttpRequest` is an object that contains information about the request you want to make to the web service. At a minimum, it specifies a URL. It can also enclose data you want to send to the server, like form data or a JSON object. {{{ #!java import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpGet; ... final String url = ...; final HttpRequestBase req = new HttpGet(url); /* Or use HttpPost, HttpPut, etc. See the org.apache.http.client.methods package for other classes. */ final CloseableHttpResponse resp = client.execute(req); }}} Notes: * You ''must'' call both `CloseableHttpResponse.close()` and `HttpRequestBase.releaseConnection()`, even if an exception is thrown. It's best to put them in a `finally` block. Connections to the web service are pooled, and if the request and response objects are not closed, HC cannot use the connection again. * The `HttpClient.execute` method should be invoked inside a task. In your task's `cancel()` method, call `HttpRequestBase.abort()` to terminate the connection. ==== Posting a JSON object to the server ==== If you want to enclose a JSON object as part of your request to the server, you can use the [[http://jackson.codehaus.org/|Jackson]] library to construct the JSON object and send it to the server like so: {{{ #!java import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.ContentType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.core.JsonEncoding; ... final String url = ...; final TreeNode jsonObject = ...; /* build the JSON object you want to send here */ // serialize the jsonObject to a byte array final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ObjectMapper mapper = new ObjectMapper(); final JsonFactory jsonFactory = mapper.getFactory(); final JsonGenerator generator = jsonFactory.createGenerator(output, JsonEncoding.UTF8); generator.writeTree(jsonObject); output.flush(); output.close(); // we have a byte array of jsonObject, so now create an HttpEntity with our byte array final ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); final HttpPost post = new HttpPost(url); post.setEntity(new InputStreamEntity(input, ContentType.APPLICATION_JSON)); }}} === Ensuring that the server sent you a 2xx response === If you got a 2xx response status code, your request was successful. To check the response status code: {{{ #!java final int statusCode = resp.getStatusLine().getStatusCode(); if (200 <= statusCode && statusCode < 300) { // request succeeded! } else { // request failed :( } }}} === Reading the response === The response data from the server is stored in an ''`HttpEntity`'' object. The response data can be retrieved like so: {{{ #!java import org.apache.http.HttpEntity; ... final HttpEntity entity = resp.getEntity(); final String contentType = entity.getContentType() == null ? null : entity.getContentType().getValue(); final String charset = entity.getContentEncoding() == null ? null : entity.getContentEncoding().getValue(); final InputStream input = entity.getContent(); // read the input here }}} ==== Reading the response as a JSON object ==== Now that you have the response's encoding (`charset`) and a stream of bytes (`input`), you can read the response as a [[http://jackson.codehaus.org/|Jackson]] JSON object. {{{ #!java import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; ... final ObjectMapper mapper = new ObjectMapper(); final JsonNode responseAsJson = mapper.readValue(input, JsonNode.class); }}} ==== Reading the response as a String ==== This is complicated! You have to read the input to a byte array, then use that to construct a String. Alternatively, you can also use [[http://commons.apache.org/proper/commons-io/|Apache IO Commons library]]'s `IOUtils.toString` method. {{{ #!java final ByteArrayOutputStream output = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; while (true) { final int len = input.read(buffer); if (len < 0) break; output.write(buffer, 0, len); } final String responseAsString = new String(output.toByteArray(), Charset.forName(charset == null ? "UTF-8" : charset)); }}} === Adding support for multiple, concurrent connections === {{{ #!java import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; ... final PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(); connMgr.setDefaultMaxPerRoute(16 /* this should match the number of concurrent connections you want to support */); final CloseableHttpClient client = HttpClientBuilder.create() .setConnectionManager(connMgr) .build(); }}} = Help = == How to add plug-in specific help to the Cytoscape main help system? == If you download !CreateHelp, compile and instal it through the App Manager of your running Cytoscape, you will see topic '''Sample 24 help''' is added to your help panel (Help --> Contents...). In order to make it simpler, you can download the [[https://github.com/cytoscape/cytoscape-samples/tree/develop/CreateHelp/src/main/resources/help|help]] directory and copy this folder to your project's resources folder. Next you need to get the {{{CyHelpBroker}}} service in your !CyActivator class. The code in !CreateHelp: {{{ #!java import java.util.Properties; import org.cytoscape.application.swing.CyHelpBroker; import org.cytoscape.service.util.AbstractCyActivator; import org.osgi.framework.BundleContext; public class CyActivator extends AbstractCyActivator { @Override public void start(BundleContext context) throws Exception { CyHelpBroker cyHelpBroker = getService(context, CyHelpBroker.class); AppHelp action = new AppHelp(cyHelpBroker); registerAllServices(context, action, new Properties()); } } }}} In the main entry point of your plug-in, add the following function: {{{ #!java ... import java.net.URL; import org.cytoscape.application.swing.CyHelpBroker; import javax.help.HelpSet; ... /** * Hook plugin help into the Cytoscape main help system: */ private void addHelp() { final String HELP_SET_NAME = "/help/jhelpset"; final ClassLoader classLoader = AppHelp.class.getClassLoader(); URL helpSetURL; try { helpSetURL = HelpSet.findHelpSet(classLoader, HELP_SET_NAME); final HelpSet newHelpSet = new HelpSet(classLoader, helpSetURL); cyHelpBroker.getHelpSet().add(newHelpSet); } catch (final Exception e) { System.err.println("Sample24: Could not find help set: \"" + HELP_SET_NAME + "!"); } } }}} Invoke this function somewhere in the constructor for the class. Finally, edit the files in the help directory. Most likely you would want to edit the files named {{{jhelpmap.jhm}}} and {{{Topic.html}}}. You may consider removing both, {{{SubTopic.html}}} and the reference to it in {{{jhelpmap.jhm}}}. You can also add additional topics, if you want. The effect this will have is to add a new topic at the very bottom of the Cytoscape help index. You may have a help button in your plug-in, in which case you would probably want to add code similar to the following: {{{ #!java ... import cytoscape.view.CyHelpBroker; ... CyHelpBroker.getHelpBroker().enableHelpOnButton(helpButton, "Topic", null); ... }}} That should be all that is needed to dynamically add your own help topic(s)! = OSGi = == Building a CyActivator == When you write a Cytoscape bundle app, you will need to extend the class AbstractCyActivator. This is itself an extension of the OSGi BundleActivator class, and contains code that will be executed when your app is started and stopped. By convention, this class is named CyActivator, though it technically could be named anything as long as the proper name is specified in the Bundle-Activator field in the manifest. In general, the start method in an AbstractCyActivator should execute the minimum necessary code to start your app. This for the most part means registering They should NOT block for user input or run code that may take a while to complete - these should be done later, perhaps when the user first interacts with the app. The shutDown() method is optional, but may be used if cleanup is required beyond unregistering service (any services registered in start() will be automatically unregistered on stop. == An easier way to construct service properties == Writing code to put in service properties requires a lot of boilerplate. Here's an example: {{{ #!java public void start(BundleContext bc) { Properties props = new Properties(); props.put(TITLE, "My app"); props.put(PREFERRED_MENU, "Apps"); TaskFactory myTaskFactory = ...; registerService(bc, myTaskFactory, props); } }}} To avoid having to construct a {{{Properties}}} object manually for each service, you can use the {{{ezProps}}} method: {{{ #!java private static Properties ezProps(String... vals) { final Properties props = new Properties(); for (int i = 0; i < vals.length; i += 2) props.put(vals[i], vals[i + 1]); return props; } }}} The example above can be reworked using {{{ezProps}}}: {{{ #!java public void start(BundleContext bc) { TaskFactory myTaskFactory = ...; registerService(bc, myTaskFactory, ezProps( TITLE, "My app", PREFERRED_MENU, "Apps")); } }}} == Including packages accessed via reflection (e.g. JDBC, SAX parsers, XML utilities) == Some packages are not included in your Import-Package header in your manifest file. The maven-bundle-plugin or bndtool would normally generate this information for you. However, since both tools compute that metadata based on direct references in the compiled class files, they cannot detect packages that are accessed via reflection (e.g. using Class.forName). The old Java service model (which is used by SAX parsers, XML utilities and JDBC drivers) uses this a lot. The preferred option for getting around this is to manually add the problematic packages to your Import-Package header. For example, for the jdbc driver package, modify the maven-bundle-plugin configuration as follows: {{{ #!xml org.apache.felix maven-bundle-plugin 2.3.7 true ${bundle.symbolicName} ${project.version} ${bundle.namespace} ${bundle.namespace}.internal.* ${bundle.namespace}.internal.CyActivator mysql-connector-java;inline=true com.mysql.jdbc;version:=5.1.25,*;resolution:=optional }}} (note: option "inline=true" in the Embed-Dependency sometimes causes bundle fail to load; so, try with and without it) - and add the dependency as usual {{{ #!xml mysql mysql-connector-java 5.1.25 true }}} == Embedding Dependencies == /!\ '''Important: Do not depend on Cytoscape's third party libraries.''' Cytoscape's core bundles depend on third party libraries and are included with Cytoscape. You may find that your app also happens to depend on the same libraries. Your app should ''not'' depend on Cytoscape's third party libraries. Your app ought to include the library in its bundle even if the same library is provided by Cytoscape. Cytoscape's third party libraries are part of its implementation. These libraries could change in minor version updates of Cytoscape and would break your app. Sometimes, an app may depend on third-party jars. Third-party jars are not provided by Cytoscape core, nor from the OSGi framework. But they must be load into OSGi framework in order to run the app which depends on other jars. There is a feature request for Cytoscape App store to handle such dependencies. Before this feature is implemented in the future release of Cytoscape, for now app developer can do a work around -- use embedding dependencies. That means emebed dpendency jar into the App jar when building the App jar. The disadvantage of this approach is that your app jar will become fat, but this makes sure your app will get started smoothly in the Cytoscape without the dependency not found error. To embed 3rd-party jars into app jar, in your pom.xml, you need to give instruction to the maven-bundle-plugin, for example, the folloing configuration will add two 3rd-party jars (colt.jar and currentent.jar) into the app jar, {{{ #!java ... org.apache.felix maven-bundle-plugin ... ... colt,concurrent;scope=compile|runtime ... }}} With this Embed-Dependency instruction in the configuration of maven-bundle-plugin, if your command 'mvn clean install' executes successful, you app jar will include the 3-party jars in itself. You can also there add {{{true}}} instruction, rather than guessing and adding each dependency manually, but this might bring unwanted and conflicting java libraries, which, however, can be fixed by also defining to some dependencies in your project. = Logging = Cytoscape has a framework for allowing apps to log in Cytoscape log files, which are located in: ''.../CytoscapeConfigurations/3/framework-cytoscape.log''. Cytoscape creates a new log file for each day it is used and appends the date to the filename. To log, include the following dependencies in your pom.xml: {{{ #!java org.ops4j.pax.logging pax-logging-api 1.5.3 provided org.ops4j.pax.logging pax-logging-service 1.5.3 provided }}} Then import these packages: {{{ #!java import org.slf4j.Logger; import org.slf4j.LoggerFactory; }}} And use the logger like this (where Foo is the class that is using the Logger object: {{{ #!java private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class); LOGGER.info("Log message"); }}}