1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.debug.ui;
15 import java.io.FileNotFoundException;
16 import java.io.IOException;
17 import java.lang.reflect.Array;
19 import java.net.URISyntaxException;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.LinkedList;
27 import java.util.List;
29 import java.util.UUID;
30 import java.util.concurrent.CopyOnWriteArrayList;
32 import org.eclipse.core.runtime.Assert;
33 import org.eclipse.core.runtime.FileLocator;
34 import org.eclipse.core.runtime.IPath;
35 import org.eclipse.core.runtime.Path;
36 import org.eclipse.jface.action.IStatusLineManager;
37 import org.eclipse.jface.dialogs.Dialog;
38 import org.eclipse.jface.dialogs.IDialogConstants;
39 import org.eclipse.jface.dialogs.IDialogSettings;
40 import org.eclipse.jface.dialogs.IInputValidator;
41 import org.eclipse.jface.dialogs.InputDialog;
42 import org.eclipse.jface.dialogs.MessageDialog;
43 import org.eclipse.jface.layout.GridDataFactory;
44 import org.eclipse.jface.resource.ColorDescriptor;
45 import org.eclipse.jface.resource.JFaceResources;
46 import org.eclipse.jface.resource.LocalResourceManager;
47 import org.eclipse.swt.SWT;
48 import org.eclipse.swt.SWTError;
49 import org.eclipse.swt.browser.Browser;
50 import org.eclipse.swt.browser.LocationAdapter;
51 import org.eclipse.swt.browser.LocationEvent;
52 import org.eclipse.swt.dnd.DND;
53 import org.eclipse.swt.dnd.DropTarget;
54 import org.eclipse.swt.dnd.DropTargetAdapter;
55 import org.eclipse.swt.dnd.DropTargetEvent;
56 import org.eclipse.swt.dnd.TextTransfer;
57 import org.eclipse.swt.dnd.Transfer;
58 import org.eclipse.swt.events.DisposeEvent;
59 import org.eclipse.swt.events.DisposeListener;
60 import org.eclipse.swt.events.FocusEvent;
61 import org.eclipse.swt.events.FocusListener;
62 import org.eclipse.swt.events.KeyAdapter;
63 import org.eclipse.swt.events.KeyEvent;
64 import org.eclipse.swt.events.ModifyEvent;
65 import org.eclipse.swt.events.ModifyListener;
66 import org.eclipse.swt.events.SelectionEvent;
67 import org.eclipse.swt.events.SelectionListener;
68 import org.eclipse.swt.graphics.Color;
69 import org.eclipse.swt.graphics.Point;
70 import org.eclipse.swt.graphics.RGB;
71 import org.eclipse.swt.layout.GridData;
72 import org.eclipse.swt.layout.GridLayout;
73 import org.eclipse.swt.widgets.Button;
74 import org.eclipse.swt.widgets.Composite;
75 import org.eclipse.swt.widgets.Label;
76 import org.eclipse.swt.widgets.Text;
77 import org.eclipse.ui.IWorkbenchSite;
78 import org.simantics.databoard.Bindings;
79 import org.simantics.databoard.Databoard;
80 import org.simantics.databoard.binding.Binding;
81 import org.simantics.databoard.binding.error.BindingException;
82 import org.simantics.databoard.serialization.Serializer;
83 import org.simantics.databoard.type.ArrayType;
84 import org.simantics.databoard.type.Datatype;
85 import org.simantics.databoard.type.StringType;
86 import org.simantics.databoard.util.ObjectUtils;
87 import org.simantics.db.AsyncRequestProcessor;
88 import org.simantics.db.ReadGraph;
89 import org.simantics.db.Resource;
90 import org.simantics.db.Session;
91 import org.simantics.db.Statement;
92 import org.simantics.db.VirtualGraph;
93 import org.simantics.db.WriteGraph;
94 import org.simantics.db.common.ResourceArray;
95 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
96 import org.simantics.db.common.request.Queries;
97 import org.simantics.db.common.request.ReadRequest;
98 import org.simantics.db.common.request.WriteRequest;
99 import org.simantics.db.common.uri.ResourceToPossibleURI;
100 import org.simantics.db.common.utils.ListUtils;
101 import org.simantics.db.common.utils.NameUtils;
102 import org.simantics.db.common.utils.OrderedSetUtils;
103 import org.simantics.db.event.ChangeEvent;
104 import org.simantics.db.event.ChangeListener;
105 import org.simantics.db.exception.AdaptionException;
106 import org.simantics.db.exception.DatabaseException;
107 import org.simantics.db.exception.ResourceNotFoundException;
108 import org.simantics.db.exception.ValidationException;
109 import org.simantics.db.layer0.adapter.StringModifier;
110 import org.simantics.db.layer0.variable.RVI;
111 import org.simantics.db.layer0.variable.Variable;
112 import org.simantics.db.layer0.variable.Variables;
113 import org.simantics.db.service.ClusteringSupport;
114 import org.simantics.db.service.GraphChangeListenerSupport;
115 import org.simantics.db.service.SerialisationSupport;
116 import org.simantics.db.service.VirtualGraphSupport;
117 import org.simantics.db.service.XSupport;
118 import org.simantics.debug.ui.internal.Activator;
119 import org.simantics.debug.ui.internal.DebugUtils;
120 import org.simantics.debug.ui.internal.HashMultiMap;
121 import org.simantics.layer0.Layer0;
122 import org.simantics.ui.dnd.LocalObjectTransfer;
123 import org.simantics.ui.dnd.ResourceReferenceTransfer;
124 import org.simantics.ui.dnd.ResourceTransferUtils;
125 import org.simantics.ui.utils.ResourceAdaptionUtils;
126 import org.simantics.utils.Container;
127 import org.simantics.utils.FileUtils;
128 import org.simantics.utils.datastructures.BijectionMap;
129 import org.simantics.utils.datastructures.Callback;
130 import org.simantics.utils.strings.AlphanumComparator;
131 import org.simantics.utils.ui.ErrorLogger;
132 import org.simantics.utils.ui.PathUtils;
133 import org.simantics.utils.ui.workbench.WorkbenchUtils;
136 public class GraphDebugger extends Composite {
138 public interface HistoryListener {
139 void historyChanged();
142 private static final String STATEMENT_PART_SEPARATOR = ",";
143 private final static String DEFAULT_DEBUGGER_CSS_FILE = "debugger.css";
144 private final static String DEFAULT_DEBUGGER_CSS_PATH = "css/" + DEFAULT_DEBUGGER_CSS_FILE;
146 private static int RESOURCE_NAME_MAX_LENGTH = 1000;
147 private static int RESOURCE_VALUE_MAX_SIZE = 16384;
149 private final LocalResourceManager resourceManager;
151 private String cssPath;
153 private Browser browser;
154 private final ColorDescriptor green = ColorDescriptor.createFrom(new RGB(0x57, 0xbc, 0x95));
156 private final boolean displayClusters = true;
158 private final BijectionMap<String, Resource> links = new BijectionMap<String, Resource>();
159 private final LinkedList<Resource> backHistory = new LinkedList<Resource>();
160 private final LinkedList<Resource> forwardHistory = new LinkedList<Resource>();
161 private Resource currentElement = null;
164 * The Session used to access the graph. Received from outside of this
165 * class and therefore it is not disposed here, just used.
167 private final Session session;
169 private final CopyOnWriteArrayList<HistoryListener> historyListeners = new CopyOnWriteArrayList<HistoryListener>();
171 private final AsyncRequestProcessor updater;
175 protected IWorkbenchSite site;
177 private final ChangeListener changeListener = new ChangeListener() {
179 public void graphChanged(ChangeEvent e) {
180 // This makes sure that the transaction for updating this
181 // GraphDebugger get executed in a serialized fashion.
182 updater.asyncRequest(new ReadRequest() {
185 public void run(ReadGraph graph) throws DatabaseException {
186 updateContent(graph, currentElement);
198 * @param resource the initial resource to debug or <code>null</code> for
199 * initially blank UI.
200 * @param site the workbench site that contains this debugger, for workbench
203 public GraphDebugger(Composite parent, int style, final Session session, Resource resource, IWorkbenchSite site) {
204 this(parent, style, session, resource);
212 * @param resource the initial resource to debug or <code>null</code> for
213 * initially blank UI.
215 public GraphDebugger(Composite parent, int style, final Session session, Resource resource) {
216 super(parent, style);
217 Assert.isNotNull(session, "session is null");
218 this.session = session;
219 this.currentElement = resource;
220 this.resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent);
222 updater = session;//.getService(MergingGraphRequestProcessor.class);
226 addDisposeListener(new DisposeListener() {
228 public void widgetDisposed(DisposeEvent e) {
229 GraphChangeListenerSupport support = session.getService(GraphChangeListenerSupport.class);
230 support.removeListener(changeListener);
236 * When given to setStatus, indicates that the message shouldn't be touched
237 * since <code>null</code> has a different meaning.
239 private static final String DONT_TOUCH = "DONT_TOUCH";
241 protected void setStatus(String message, String error) {
242 IStatusLineManager status = WorkbenchUtils.getStatusLine(site);
243 if (status != null) {
244 if (message != DONT_TOUCH)
245 status.setMessage(message);
246 if (error != DONT_TOUCH)
247 status.setErrorMessage(error);
251 public void defaultInitializeUI() {
252 setLayout(new GridLayout(2, false));
253 setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
255 createResourceText(this);
256 createDropLabel(this);
261 protected void initializeCSS() {
262 // Extract default css to a temporary location if necessary.
264 IPath absolutePath = PathUtils.getAbsolutePath(Activator.PLUGIN_ID, DEFAULT_DEBUGGER_CSS_PATH);
265 if (absolutePath != null) {
266 cssPath = absolutePath.toFile().toURI().toString();
268 File tempDir = FileUtils.getOrCreateTemporaryDirectory(false);
269 File css = new File(tempDir, DEFAULT_DEBUGGER_CSS_FILE);
271 URL url = FileLocator.find(Activator.getDefault().getBundle(), new Path(DEFAULT_DEBUGGER_CSS_PATH), null);
273 throw new FileNotFoundException("Could not find '" + DEFAULT_DEBUGGER_CSS_PATH + "' in bundle '" + Activator.PLUGIN_ID + "'");
274 cssPath = FileUtils.copyResource(url, css, true).toURI().toString();
276 cssPath = css.toURI().toString();
279 } catch (IOException e) {
280 // CSS extraction failed, let's just live without it then.
281 ErrorLogger.defaultLogWarning(e);
285 private static final String PROMPT_TEXT = "Enter resource ID (RID) or URI";
287 public void createResourceText(final Composite parent) {
288 final Text text = new Text(parent, SWT.BORDER);
289 text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
290 text.setText(PROMPT_TEXT);
291 GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(true, false).applyTo(text);
293 text.addFocusListener(new FocusListener() {
295 public void focusLost(FocusEvent e) {
296 if (text.getText().trim().equals("")) {
297 text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
298 text.setText(PROMPT_TEXT);
302 public void focusGained(FocusEvent e) {
303 if (text.getText().trim().equals(PROMPT_TEXT)) {
304 text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_BLACK));
310 text.addKeyListener(new KeyAdapter() {
312 public void keyPressed(KeyEvent e) {
313 if (e.keyCode == SWT.CR) {
314 String input = text.getText();
315 setLookupInput(input);
320 final Button button = new Button(parent, SWT.FLAT);
321 button.setText("&Lookup");
322 button.setEnabled(false);
323 GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(false, false).applyTo(button);
325 text.addKeyListener(new KeyAdapter() {
328 public void keyPressed(KeyEvent e) {
329 if (e.keyCode == 13) {
330 String input = text.getText();
331 setLookupInput(input);
337 button.addSelectionListener(new SelectionListener() {
339 public void widgetDefaultSelected(SelectionEvent e) {
343 public void widgetSelected(SelectionEvent e) {
344 String input = text.getText();
345 setLookupInput(input);
349 text.addModifyListener(new ModifyListener() {
351 public void modifyText(ModifyEvent e) {
352 String input = text.getText().trim();
353 if (!input.equals(PROMPT_TEXT) && !input.equals(""))
354 button.setEnabled(true);
356 button.setEnabled(false);
361 public void setLookupInput(String input) {
362 // There's no harm in trimming out spaces from both ends of the input.
363 input = input.trim();
365 SerialisationSupport support = session.getService(SerialisationSupport.class);
366 if (input.startsWith("$")) {
368 Resource r = support.getResource(Long.parseLong(input.substring(1)));
370 } catch (NumberFormatException e1) {
371 // Ignore, may happen for crap input
372 setStatus(DONT_TOUCH, "Invalid '$'-prefixed input, expected resource ID");
373 } catch (Exception e1) {
374 ErrorLogger.defaultLogError(e1);
375 setStatus(DONT_TOUCH, "Resource ID lookup failed. See Error Log.");
380 String[] parts = input.split("-");
382 if (parts.length == 1) {
384 int resourceKey = Integer.parseInt(parts[0].trim());
385 Resource r = support.getResource(resourceKey);
386 // Some validation, not enough though
387 ClusteringSupport cs = session.getService(ClusteringSupport.class);
388 long cluster = cs.getCluster(r);
392 } catch (NumberFormatException e1) {
393 // Ignore, may happen for crap input
394 setStatus(DONT_TOUCH, "Invalid input, expected transient resource ID");
395 } catch (Exception e1) {
396 ErrorLogger.defaultLogError(e1);
397 setStatus(DONT_TOUCH, "Transient resource ID lookup failed. See Error Log.");
399 } else if (parts.length == 2) {
401 int resourceIndex = Integer.parseInt(parts[1]);
402 long clusterId = Long.parseLong(parts[0]);
403 ClusteringSupport cs = session.getService(ClusteringSupport.class);
404 Resource r = cs.getResourceByIndexAndCluster(resourceIndex, clusterId);
406 } catch (NumberFormatException e1) {
407 // Ignore, may happen for crap input
408 setStatus(DONT_TOUCH, "Invalid input, expected index & cluster IDs");
409 } catch (Exception e1) {
410 ErrorLogger.defaultLogError(e1);
411 setStatus(DONT_TOUCH, "Index & cluster -based lookup failed. See Error Log.");
415 // Try to see if the input data is an URI reference
417 // First check that the input really is a proper URI.
419 if (!input.equals("http:/") && input.endsWith("/"))
420 uri = input.substring(0, input.length() - 1);
422 Resource r = session.syncRequest( Queries.resource( uri ) );
425 } catch (URISyntaxException e) {
426 // Ignore, this is not a proper URI at all.
427 } catch (ResourceNotFoundException e1) {
428 // Ok, this was an URI, but no resource was found.
429 setStatus(DONT_TOUCH, "Resource for URI '" + input + "' not found");
431 } catch (DatabaseException e1) {
432 setStatus(DONT_TOUCH, "URI lookup failed. See Error Log.");
433 ErrorLogger.defaultLogError(e1);
436 setStatus(DONT_TOUCH, "Invalid input, resource ID or URI expected");
439 public Label createDropLabel(Composite parent) {
440 final Label label = new Label(parent, SWT.BORDER);
441 label.setAlignment(SWT.CENTER);
442 label.setText("Drag a resource here to examine it in this debugger!");
443 label.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY));
444 GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).hint(SWT.DEFAULT, 20).span(2, 1).grab(true, false).applyTo(label);
446 // Add resource id drop support to the drop-area.
447 DropTarget dropTarget = new DropTarget(label, DND.DROP_LINK | DND.DROP_COPY);
448 dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), ResourceReferenceTransfer.getInstance(), LocalObjectTransfer.getTransfer() });
449 dropTarget.addDropListener(new DropTargetAdapter() {
451 public void dragEnter(DropTargetEvent event) {
452 event.detail = DND.DROP_LINK;
453 label.setBackground((Color) resourceManager.get(green));
457 public void dragLeave(DropTargetEvent event) {
458 label.setBackground(null);
462 public void drop(DropTargetEvent event) {
463 label.setBackground(null);
464 ResourceArray[] data = parseEventData(event);
465 if (data == null || data.length != 1) {
466 event.detail = DND.DROP_NONE;
469 final ResourceArray array = data[0];
470 final Resource r = array.resources[array.resources.length - 1];
475 private ResourceArray[] parseEventData(DropTargetEvent event) {
476 //System.out.println("DATA: " + event.data);
477 if (event.data instanceof String) {
479 SerialisationSupport support = session.getService(SerialisationSupport.class);
480 return ResourceTransferUtils.readStringTransferable(support, (String) event.data).toResourceArrayArray();
481 } catch (IllegalArgumentException e) {
482 ErrorLogger.defaultLogError(e);
483 } catch (DatabaseException e) {
484 ErrorLogger.defaultLogError(e);
487 ResourceArray[] ret = ResourceAdaptionUtils.toResourceArrays(event.data);
497 public Browser createBrowser(Composite parent) {
499 browser = new Browser(parent, SWT.MOZILLA);
500 } catch (SWTError e) {
501 //System.out.println("Could not instantiate Browser: " + e.getMessage());
502 browser = new Browser(parent, SWT.NONE);
504 GridDataFactory.fillDefaults().span(2, 1).grab(true, true).applyTo(browser);
506 // Left/right arrows for back/forward
507 browser.addKeyListener(new KeyAdapter() {
510 // public void keyPressed(KeyEvent e) {
511 // if (e.keyCode == SWT.F5) {
517 public void keyReleased(KeyEvent e) {
518 // System.out.println("key, char: " + e.keyCode + ", " + (int) e.character + " (" + e.character + ")");
519 if (e.keyCode == SWT.BS) {
523 if (e.keyCode == SWT.F5) {
527 if ((e.stateMask & SWT.ALT) != 0) {
528 if (e.keyCode == SWT.ARROW_RIGHT)
530 if (e.keyCode == SWT.ARROW_LEFT)
536 // Add listener for debugging functionality
537 browser.addLocationListener(new LocationAdapter() {
539 public void changing(LocationEvent event) {
540 String location = event.location;
541 if (location.startsWith("simantics:browser"))
542 location = "about:" + location.substring(17);
543 //System.out.println("changing: location=" + location);
545 // Do not follow links that are meant as actions that are
548 if ("about:blank".equals(location)) {
549 // Just changing to the same old blank url is ok since it
550 // allows the browser to refresh itself.
554 if (location.startsWith("about:-link")) {
555 String target = location.replace("about:-link", "");
556 Resource element = links.getRight(target);
557 if (element == currentElement) {
561 changeLocation(element);
562 } else if (location.startsWith("about:-remove")) {
563 String target = location.replace("about:-remove", "");
564 String n[] = target.split(STATEMENT_PART_SEPARATOR);
568 final Resource s = links.getRight(n[0]);
569 final Resource p = links.getRight(n[1]);
570 final Resource o = links.getRight(n[2]);
572 // Make sure this is what the use wants.
573 MessageDialog md = new MessageDialog(
577 "This action will remove the selected statement.\nAre you sure you want to proceed with this action?",
578 MessageDialog.QUESTION, new String[] { "Cancel", "Continue" }, 0);
579 if (md.open() != 1) {
583 session.asyncRequest(new WriteRequest() {
586 public void perform(WriteGraph g) throws DatabaseException {
588 List<Resource> ls = OrderedSetUtils.toList(g, s);
590 OrderedSetUtils.remove(g, s, o);
591 } catch (DatabaseException e) {
595 List<Resource> ls = ListUtils.toList(g, s);
597 ListUtils.removeElement(g, s, o);
598 } catch (DatabaseException e) {
601 g.denyStatement(s, p, o);
604 }, new Callback<DatabaseException>() {
607 public void run(DatabaseException parameter) {
612 } else if (location.startsWith("about:-edit-value")) {
613 String target = location.replace("about:-edit-value", "");
614 final Resource o = links.getRight(target);
616 session.asyncRequest(new ReadRequest() {
618 String previousValue;
621 public void run(ReadGraph graph) throws DatabaseException {
623 previousValue = getResourceName(graph, o);
624 final StringModifier modifier = graph.adapt(o, StringModifier.class);
625 getDisplay().asyncExec(new Runnable() {
628 InputDialog dialog = new InputDialog(
633 new IInputValidator() {
635 public String isValid(String newText) {
636 return modifier.isValid(newText);
639 private static final String DIALOG = "DebuggerEditValueDialog"; //$NON-NLS-1$
640 private IDialogSettings dialogBoundsSettings;
642 protected IDialogSettings getDialogBoundsSettings() {
643 if (dialogBoundsSettings == null) {
644 IDialogSettings settings = Activator.getDefault().getDialogSettings();
645 dialogBoundsSettings = settings.getSection(DIALOG);
646 if (dialogBoundsSettings == null)
647 dialogBoundsSettings = settings.addNewSection(DIALOG);
649 return dialogBoundsSettings;
652 protected Point getInitialSize() {
653 Point defaultSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
654 Point result = super.getInitialSize();
655 if (defaultSize.equals(result))
656 return new Point(600, 400);
659 protected int getShellStyle() {
660 return super.getShellStyle() | SWT.RESIZE;
662 protected org.eclipse.swt.widgets.Control createDialogArea(Composite parent) {
663 Composite composite = (Composite) super.createDialogArea(parent);
664 getText().setLayoutData(
665 new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL
666 | GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
668 Label label = new Label(composite, SWT.NONE);
669 label.moveAbove(getText());
670 label.setText("Input new property value. For numeric vector values, separate numbers with comma (',').");
671 GridData data = new GridData(GridData.GRAB_HORIZONTAL
672 | GridData.HORIZONTAL_ALIGN_FILL
673 | GridData.VERTICAL_ALIGN_CENTER);
674 data.widthHint = convertHorizontalDLUsToPixels(IDialogConstants.MINIMUM_MESSAGE_AREA_WIDTH);
675 label.setLayoutData(data);
676 label.setFont(parent.getFont());
680 protected int getInputTextStyle() {
681 return SWT.MULTI | SWT.BORDER;
684 int ok = dialog.open();
688 final String value = dialog.getValue();
689 session.asyncRequest(new WriteRequest() {
691 public void perform(WriteGraph g) throws DatabaseException {
692 //modifier.modify( g, htmlEscape( value ) );
693 modifier.modify( g, value );
695 }, new Callback<DatabaseException>() {
697 public void run(DatabaseException parameter) {
698 if (parameter != null)
699 ErrorLogger.defaultLogError(parameter);
708 }, new ProcedureAdapter<Object>() {
710 public void exception(Throwable t) {
711 ErrorLogger.defaultLogError(t);
719 // Schedule a request that updates the browser content.
721 GraphChangeListenerSupport support = session.getService(GraphChangeListenerSupport.class);
722 support.removeListener(changeListener);
727 public void refreshBrowser() {
728 if (currentElement == null)
731 // Schedule a request that updates the browser content.
732 updater.asyncRequest(new ReadRequest() {
735 public void run(ReadGraph graph) throws DatabaseException {
736 updateContent(graph, currentElement);
743 public Resource getDebuggerLocation() {
744 return currentElement;
747 public void changeLocation(Resource element) {
748 if (currentElement != null) {
749 backHistory.addLast(currentElement);
751 currentElement = element;
752 forwardHistory.clear();
755 setStatus(DONT_TOUCH, null);
756 fireHistoryChanged();
759 public void addHistoryListener(HistoryListener l) {
760 historyListeners.add(l);
763 public void removeHistoryListener(HistoryListener l) {
764 historyListeners.remove(l);
767 private void fireHistoryChanged() {
768 for (HistoryListener l : historyListeners)
772 public boolean hasBackHistory() {
773 return backHistory.isEmpty();
776 public boolean hasForwardHistory() {
777 return forwardHistory.isEmpty();
781 if (backHistory.isEmpty())
784 forwardHistory.addFirst(currentElement);
785 currentElement = backHistory.removeLast();
788 fireHistoryChanged();
791 public void forward() {
792 if (forwardHistory.isEmpty())
795 backHistory.addLast(currentElement);
796 currentElement = forwardHistory.removeFirst();
799 fireHistoryChanged();
802 protected String toName(Object o) {
803 Class<?> clazz = o.getClass();
804 if (clazz.isArray()) {
805 int length = Array.getLength(o);
806 if (length > RESOURCE_NAME_MAX_LENGTH) {
807 if (o instanceof byte[]) {
808 byte[] arr = (byte[]) o;
809 byte[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
810 return truncated("byte", Arrays.toString(arr2), arr.length);
811 } else if (o instanceof int[]) {
812 int[] arr = (int[]) o;
813 int[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
814 return truncated("int", Arrays.toString(arr2), arr.length);
815 } else if (o instanceof long[]) {
816 long[] arr = (long[]) o;
817 long[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
818 return truncated("long", Arrays.toString(arr2), arr.length);
819 } else if (o instanceof float[]) {
820 float[] arr = (float[]) o;
821 float[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
822 return truncated("float", Arrays.toString(arr2), arr.length);
823 } else if (o instanceof double[]) {
824 double[] arr = (double[]) o;
825 double[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
826 return truncated("double", Arrays.toString(arr2), arr.length);
827 } else if (o instanceof boolean[]) {
828 boolean[] arr = (boolean[]) o;
829 boolean[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
830 return truncated("boolean", Arrays.toString(arr2), arr.length);
831 } else if (o instanceof Object[]) {
832 Object[] arr = (Object[]) o;
833 Object[] arr2 = Arrays.copyOf(arr, RESOURCE_NAME_MAX_LENGTH);
834 return truncated("Object", Arrays.toString(arr2), arr.length);
836 return "Unknown big array " + o.getClass();
839 return o.getClass().getComponentType() + "[" + length + "] = " + ObjectUtils.toString(o);
845 protected String truncated(String type, String string, int originalLength) {
846 return type + "[" + RESOURCE_NAME_MAX_LENGTH + "/" + originalLength + "] = " + string;
849 public static String htmlEscape(String s)
851 return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\n", "<br/>");
855 * Get resource name(?)
861 protected String getResourceName(ReadGraph graph, Resource r) {
865 //System.out.println("hasValue(" + NameUtils.getSafeName(graph, r, true));
866 if (graph.hasValue(r)) {
867 // too large array may cause application to run out of memory.
868 //System.out.println("getValue(" + NameUtils.getSafeName(graph, r, true));
869 Datatype type = graph.getPossibleRelatedValue(r, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
871 Binding rviBinding = graph.getService(Databoard.class).getBindingUnchecked( RVI.class );
872 if (type.equals( rviBinding.type() )) {
873 RVI rvi = graph.getValue(r, rviBinding);
876 Variable v = Variables.getConfigurationContext( graph, currentElement );
877 name = rvi.asString(graph, v);
878 // name = rvi.resolve(graph, v).getURI(graph);
879 } catch (DatabaseException dbe ) {
880 name = rvi.toString( graph );
883 long valueSize = NameUtils.getPossibleValueSize(graph, r);
884 if (valueSize > RESOURCE_NAME_MAX_LENGTH) {
885 // Binding b = Bindings.getBinding(type);
886 // Object v = graph.getValue(r, b);
887 // Serializer s = Bindings.getSerializerUnchecked(b);
888 // int size = s.getSize(v);
889 name = "Approx. " + valueSize + " byte literal of type " + type.toSingleLineString();
891 Binding b = Bindings.getBinding(type);
892 Object v = graph.getValue(r, b);
893 if (b.type() instanceof StringType) {
894 name = (String) graph.getValue(r, b);
896 name = b.toString(v, false);
898 if (type instanceof ArrayType){
899 name = name.substring(1, name.length()-1);
904 Object o = graph.getValue(r);
909 name = "<empty value>";
913 // Does resource have a file ??
916 // Accessor accessor = graph.getAccessor(r);
917 // name = "File of type " + accessor.type().toSingleLineString();
918 // } catch (DatabaseException e) {
919 // // No file, try next alternative.
923 //name = graph.adapt(r, String.class);
925 name = DebugUtils.getSafeLabel(graph, r);
927 name = "<empty name>";
929 // ClusteringSupport support = graph.getSession().getService(ClusteringSupport.class);
931 // return "[" + r.getResourceId() + " - " + support.getCluster(r) + "]";
932 if(displayClusters) {
933 // SessionDebug debug = graph.getSession().getDebug();
934 // name += " (" + debug.getCluster(r) + ")";
937 } catch (AdaptionException e) {
938 // e.printStackTrace();
939 String name = safeReadableString(graph, r);
941 // MessageService.defaultLog(new DetailStatus(IDetailStatus.DEBUG, Activator.PLUGIN_ID, 0, NLS.bind(Messages.Name_adaption_problem, MessageUtil.resource(session, r, "this resource")), e));
942 // } catch (ReferenceSerializationException e1) {
943 // e1.printStackTrace();
944 // ErrorLogger.defaultLogWarning(e1);
947 } catch (Exception e) {
948 ErrorLogger.defaultLogError(e);
949 String name = safeReadableString(graph, r);
951 // MessageService.defaultLog(new DetailStatus(IDetailStatus.DEBUG, Activator.PLUGIN_ID, 0, NLS.bind(Messages.Name_formulation_problem, MessageUtil.resource(session, r, "this resource")), e));
952 // } catch (ReferenceSerializationException e1) {
953 // e1.printStackTrace();
954 // ErrorLogger.defaultLogWarning(e1);
960 private String getResourceRef(ReadGraph graph, Resource r) throws DatabaseException {
963 Layer0 L0 = Layer0.getInstance(graph);
964 if (graph.isInstanceOf(r, L0.Assertion)) {
965 Resource pred = graph.getSingleObject(r, L0.HasPredicate);
966 // Don't know how I encountered this but it seems to be possible in some cases..
967 // Resource obj = graph.getSingleObject(r, L0.HasObject);
968 Resource obj = graph.getPossibleObject(r, L0.HasObject);
969 String tmp = htmlEscape( getResourceName(graph, pred) + " -> " + (obj == null ? "No object ?" : getResourceName(graph, obj)) + " (Assertion)" );
970 name = tmp.substring(0, Math.min(80, tmp.length()));
972 String resourceName = getResourceName(graph, r);
973 if(resourceName.equals("Inverse")) {
974 Resource inverse = graph.getPossibleInverse(r);
975 if(inverse != null && graph.hasStatement(inverse, L0.ConsistsOf, r))
976 resourceName = getResourceName(graph, inverse) + "/Inverse";
978 String tmp = htmlEscape( resourceName );
979 name = tmp.substring(0, Math.min(80, tmp.length()));
982 } catch (OutOfMemoryError e) {
983 name = "OutOfMemoryError";
985 String ret = "<a href=\"simantics:browser-link" + getLinkString(r) + "\">"
988 if (graph.isInstanceOf(r, L0.Literal)) {
989 ret += " <a class=\"edit-link\" href=\"simantics:browser-edit-value" + getLinkString(r) + "\">"
996 private String getStatementRemoveRef(Resource s, Resource p, Resource o) {
997 return "<a href=\"simantics:browser-remove" + getStatementString(s, p, o)
998 + "\" title=\"Remove this statement\">X</a>";
1001 private void updatePred(StringBuffer content, ReadGraph graph, Resource subj, Resource pred, List<Resource[]> stats) throws DatabaseException {
1002 // Generate output content from statements
1003 String[][] objects = new String[stats.size()][];
1004 for (int i = 0; i < stats.size(); ++i) {
1005 Resource stmSubject = stats.get(i)[0];
1006 Resource object = stats.get(i)[1];
1008 objects[i] = new String[4];
1009 objects[i][0] = getLinkString(object);
1010 objects[i][1] = htmlEscape( getResourceName(graph, object) );
1011 objects[i][2] = getResourceRef(graph, object);
1013 // Make a note if the statement was acquired.
1014 if(!stmSubject.equals(subj)) {
1015 objects[i][3] = " (in " + getResourceRef(graph, stmSubject) + ")";
1019 // Sort statements by object name
1020 Arrays.sort(objects, new Comparator<String[]>() {
1022 public int compare(String[] o1, String[] o2) {
1023 return AlphanumComparator.CASE_INSENSITIVE_COMPARATOR.compare(o1[1], o2[1]);
1027 // Output table rows
1028 for (int i = 0; i < objects.length; ++i) {
1029 content.append("<tr>");
1032 content.append("<td rowspan=\"").append(objects.length).append("\" valign=\"top\">").append(getResourceRef(graph, pred)).append("</td>");
1035 if (objects[i][3] == null) content.append("<td>");
1036 else content.append("<td class=\"acquired\">");
1038 content.append(objects[i][2]);
1039 if (objects[i][3] != null)
1040 content.append(objects[i][3]);
1042 content.append("</td>");
1044 VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
1045 VirtualGraph vg = vgs.getGraph(graph, subj, pred, links.getRight(objects[i][0]));
1048 content.append("<td>").append(vg.toString()).append("</td>");
1050 content.append("<td>DB</td>");
1054 // Statement remove -link column
1055 // Only allowed for non-acquired statements.
1056 if (objects[i][3] == null) {
1057 content.append("<td class=\"remove\">");
1058 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1059 content.append("</td>");
1061 content.append("</tr>");
1065 private void updateTag(StringBuffer content, ReadGraph graph, Resource subj, Resource tag) throws DatabaseException {
1067 // Generate output content from statements
1068 String ref = getResourceRef(graph, tag);
1070 content.append("<tr>");
1071 content.append("<td rowspan=\"1\" colspan=\"3\" valign=\"top\">").append(ref).append("</td>");
1072 //content.append("<td>" + name + "</td>");
1073 content.append("<td class=\"remove\">");
1074 content.append(getStatementRemoveRef(subj, tag, subj));
1075 content.append("</td>");
1076 content.append("</tr>");
1080 private void updateOrderedSet(StringBuffer content, ReadGraph graph, Resource subj) throws DatabaseException {
1081 //List<Resource> list = OrderedSetUtils.toList(graph, subj);
1083 // Generate output content from statements
1084 String[][] objects = new String[stats.size()][];
1085 for (int i = 0; i < stats.size(); ++i) {
1086 Resource stmSubject = stats.get(i)[0];
1087 Resource object = stats.get(i)[1];
1089 objects[i] = new String[4];
1090 objects[i][0] = getLinkString(object);
1091 objects[i][1] = getResourceName(graph, object);
1092 objects[i][2] = getResourceRef(graph, object);
1094 // Make a note if the statement was acquired.
1095 if(!stmSubject.equals(subj)) {
1096 objects[i][3] = " (acquired from " + getResourceRef(graph, stmSubject) + ")";
1100 // Sort statements by object name
1101 Arrays.sort(objects, new Comparator<String[]>() {
1103 public int compare(String[] o1, String[] o2) {
1104 return o1[1].compareTo(o2[1]);
1108 List<String> list = new ArrayList<String>();
1109 Resource cur = subj;
1112 cur = OrderedSetUtils.next(graph, subj, cur);
1113 } catch(DatabaseException e) {
1114 list.add("<span style=\"color:red;font-weight:bold\">BROKEN ORDERED SET:<br/></span><span style=\"color:red\">" + e.getMessage() + "</span>");
1115 Resource inv = graph.getPossibleInverse(subj);
1116 for(Statement stat : graph.getStatements(cur, L0.IsRelatedTo)) {
1117 if(stat.getSubject().equals(cur)) {
1118 if(stat.getPredicate().equals(subj)) {
1119 list.add("next " + getResourceRef(graph, stat.getObject()));
1121 else if(stat.getPredicate().equals(inv)) {
1122 list.add("prev " + getResourceRef(graph, stat.getObject()));
1128 if(cur.equals(subj))
1130 list.add(getResourceRef(graph, cur));
1133 // Output table rows
1134 for (int i = 0; i < list.size() ; ++i) {
1135 content.append("<tr>");
1138 content.append("<td rowspan=\"").append(list.size()).append("\" valign=\"top\">Ordered Set Elements</td>");
1141 content.append("<td>");
1142 content.append(list.get(i));
1143 content.append("</td>");
1145 // Statement remove -link column
1146 // Only allowed for non-acquired statements.
1147 /*if (objects[i][3] == null) {
1148 content.append("<td class=\"remove\">");
1149 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1150 content.append("</td>");
1152 content.append("</tr>");
1156 private void updateLinkedList(StringBuffer content, ReadGraph graph, Resource subj) throws DatabaseException {
1158 List<String> list = new ArrayList<String>();
1161 List<Resource> resources = ListUtils.toList(graph, subj);
1162 for(Resource element : resources) {
1163 list.add(getResourceRef(graph, element));
1165 } catch (DatabaseException e) {
1166 throw new ValidationException(e);
1169 // Output table rows
1170 for (int i = 0; i < list.size() ; ++i) {
1171 content.append("<tr>");
1174 content.append("<td rowspan=\"").append(list.size()).append("\" valign=\"top\">Linked List Elements</td>");
1177 content.append("<td>");
1178 content.append(list.get(i));
1179 content.append("</td><td>DB</td>");
1181 // Statement remove -link column
1182 // Only allowed for non-acquired statements.
1183 /*if (objects[i][3] == null) {
1184 content.append("<td class=\"remove\">");
1185 content.append(getStatementRemoveRef(subj, pred, links.getRight(objects[i][0])));
1186 content.append("</td>");
1188 content.append("</tr>");
1192 protected synchronized void updateContent(final ReadGraph graph, Resource... resources) throws DatabaseException {
1193 L0 = Layer0.getInstance(graph);
1196 StringBuffer content = new StringBuffer();
1198 // Generate HTML -page
1199 content.append("<html>\n<head>\n")
1201 .append("\n</head>\n")
1203 .append("<div id=\"mainContent\">\n\n");
1205 for (Resource r : resources) {
1211 uri = graph.syncRequest(new ResourceToPossibleURI(r));
1212 } catch (Exception e) {
1213 ErrorLogger.defaultLogError(e);
1214 uri = "Cannot get URI: " + e.getMessage();
1218 content.append("<div id=\"top\">\n");
1219 content.append("<table class=\"top\">\n");
1221 content.append("<tr><td class=\"top_key\">URI</td><td class=\"top_value\"><span id=\"uri\">").append(uri).append("</span></td></tr>\n");
1224 XSupport xs = graph.getService(XSupport.class);
1225 boolean immutable = xs.getImmutable(r);
1227 Collection<Statement> statements = graph.getStatements(r, L0.IsWeaklyRelatedTo);
1228 HashMultiMap<Resource, Resource[]> map = new HashMultiMap<Resource, Resource[]>();
1229 for(org.simantics.db.Statement statement : statements) {
1230 Resource predicate = null;
1231 Resource subject = null;
1232 Resource obj = null;
1234 predicate = statement.getPredicate();
1235 subject = statement.getSubject();
1236 obj = statement.getObject();
1237 map.add(predicate, new Resource[] {subject, obj});
1238 } catch (Throwable e) {
1239 ErrorLogger.defaultLogError("Cannot find statement " + subject + " " + predicate + " " + obj, e);
1242 SerialisationSupport ss = graph.getSession().getService(SerialisationSupport.class);
1243 ClusteringSupport support = graph.getSession().getService(ClusteringSupport.class);
1244 content.append("<tr><td class=\"top_key\">Identifiers</td><td class=\"top_value\">");
1245 content.append("<span id=\"resource_id\">")
1246 .append(" RID = $").append(r.getResourceId())
1247 .append(" Resource Key = ").append(ss.getTransientId(r))
1248 .append(" CID = ").append(support.getCluster(r));
1249 content.append("</span></td>");
1251 content.append("<td class=\"remove\">[IMMUTABLE]</td>");
1252 content.append("</tr>\n");
1254 boolean isClusterSet = support.isClusterSet(r);
1255 Resource parentSet = support.getClusterSetOfCluster(r);
1256 String parentSetURI = parentSet != null ? graph.getPossibleURI(parentSet) : null;
1258 content.append("<tr><td class=\"top_key\">Clustering</td><td class=\"top_value\">");
1259 content.append("<span id=\"resource_id\">");
1261 if(parentSetURI != null)
1262 content.append(" Containing cluster set = ").append(parentSetURI);
1263 else if (parentSet != null)
1264 content.append(" Containing cluster set = ").append(parentSet.toString());
1266 content.append(" Not in any cluster set ");
1268 content.append("</span></td>");
1270 content.append("<td class=\"remove\">[CLUSTER SET]</td>");
1271 content.append("</tr>\n");
1273 // If the resource has a value, show it.
1274 String resourceValue = getResourceValue(graph, r);
1275 if (resourceValue != null) {
1277 .append("<tr><td class=\"top_key\">Attached value</td><td class=\"top_value\">")
1278 .append(htmlEscape(resourceValue))
1279 .append("</td></tr>\n");
1283 content.append("</table>\n");
1284 content.append("</div>\n");
1286 content.append("\n<div id=\"data\">\n");
1287 content.append("<table>\n")
1288 .append("<tr><th>Predicate</th><th>Object</th><th>Graph</th></tr>")
1289 .append("<tr><td class=\"subtitle\" colspan=\"3\">Basic information</td></tr>");
1291 boolean isOrderedSet = graph.isInstanceOf(r, L0.OrderedSet);
1292 boolean isLinkedList = graph.isInstanceOf(r, L0.List);
1295 // BASIC INFORMATION:
1296 for (Resource pred :
1297 new Resource[] {L0.HasName, L0.InstanceOf,
1298 L0.Inherits, L0.SubrelationOf,
1299 L0.PartOf, L0.ConsistsOf})
1300 if (map.containsKey(pred))
1301 updatePred(content, graph, r, pred, map.remove(pred));
1304 content.append("<tr><td class=\"subtitle\" colspan=\"3\">Tags</td></tr>");
1305 for(Statement stm : statements) {
1306 if(stm.getSubject().equals(stm.getObject())) {
1307 updateTag(content, graph, r, stm.getPredicate());
1308 map.remove(stm.getPredicate());
1313 content.append("<tr><td class=\"subtitle\" colspan=\"3\">Ordered Sets</td></tr>");
1314 for(Statement stm : statements) {
1315 Resource predicate = stm.getPredicate();
1316 if(graph.isInstanceOf(stm.getPredicate(), L0.OrderedSet)) {
1317 updateTag(content, graph, r, stm.getPredicate());
1318 if(map.get(stm.getPredicate()) != null && map.get(stm.getPredicate()).size() == 1)
1319 map.remove(stm.getPredicate());
1321 Resource inverse = graph.getPossibleInverse(predicate);
1322 if (inverse != null) {
1323 if(graph.isInstanceOf(inverse, L0.OrderedSet)) {
1324 if(map.get(stm.getPredicate()) != null && map.get(stm.getPredicate()).size() == 1)
1325 map.remove(stm.getPredicate());
1328 // FIXME : should we infor missing inverse
1333 content.append("<tr><td class=\"subtitle\" colspan=\"3\">Is Related To</td></tr>");
1335 // ELEMENTS OF ORDERED SET
1337 //content.append("<tr><td class=\"subtitle\" colspan=\"2\">Ordered set</td></tr>");
1339 updateOrderedSet(content, graph, r);
1340 } catch (ValidationException e) {
1341 content.append("<td colspan=\"3\"><span style=\"color:red;font-weight:bold\">BROKEN ORDERED SET:<br/></span><span style=\"color:red\">").append(e.getMessage()).append("</span></td>");
1345 // ELEMENTS OF LINKED LIST
1347 //content.append("<tr><td class=\"subtitle\" colspan=\"2\">Ordered set</td></tr>");
1349 updateLinkedList(content, graph, r);
1350 } catch (ValidationException e) {
1351 content.append("<td colspan=\"3\"><span style=\"color:red;font-weight:bold\">BROKEN LINKED LIST:<br/></span><span style=\"color:red\">").append(e.getMessage()).append("</span></td>");
1355 // IS RELATED TO (other)
1356 Resource[] preds = map.keySet().toArray(new Resource[0]);
1357 final Map<Resource, String> strmap = new HashMap<Resource, String>(preds.length);
1358 for(Resource pred : preds) {
1359 String str = htmlEscape( getResourceName(graph, pred) );
1362 strmap.put(pred, str);
1364 Arrays.sort(preds, new Comparator<Resource>() {
1366 public int compare(Resource o1, Resource o2) {
1367 return AlphanumComparator.CASE_INSENSITIVE_COMPARATOR.compare(strmap.get(o1), strmap.get(o2));
1370 for(Resource pred : preds)
1371 if(graph.isSubrelationOf(pred, L0.IsRelatedTo))
1372 updatePred(content, graph, r, pred, map.get(pred));
1375 content.append("<tr><td class=\"subtitle\" colspan=\"3\">Other statements</td></tr>");
1376 for(Resource pred : preds)
1377 if(!graph.isSubrelationOf(pred, L0.IsRelatedTo))
1378 updatePred(content, graph, r, pred, map.get(pred));
1379 content.append("</table>\n");
1382 content.append("</div>\n\n");
1383 // Close #mainContent
1384 content.append("</div>\n");
1385 content.append("</body>\n</html>\n");
1388 final String finalContent = content.toString();
1389 if (!isDisposed()) {
1390 getDisplay().asyncExec(new Runnable() {
1393 if (!browser.isDisposed())
1394 browser.setText(finalContent);
1400 private String getResourceValue(ReadGraph graph, Resource r) {
1402 if (graph.hasValue(r)) {
1403 // too large array may cause application to run out of memory.
1404 //System.out.println("getValue(" + NameUtils.getSafeName(graph, r, true));
1405 Datatype type = graph.getPossibleRelatedValue(r, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
1407 Binding rviBinding = graph.getService(Databoard.class).getBindingUnchecked( RVI.class );
1408 if (type.equals( rviBinding.type() )) {
1409 RVI rvi = graph.getValue(r, rviBinding);
1411 Variable v = Variables.getConfigurationContext( graph, r );
1412 return rvi.asString(graph, v);
1413 } catch (DatabaseException dbe ) {
1414 return rvi.toString( graph );
1417 Binding b = Bindings.getBinding(type);
1418 Object v = graph.getValue(r, b);
1419 Serializer s = Bindings.getSerializerUnchecked(b);
1420 int size = s.getSize(v);
1421 if (size > RESOURCE_VALUE_MAX_SIZE) {
1422 return "Approx. " + size + " byte literal of type " + type.toSingleLineString();
1424 return b.toString(v, false);
1428 Object o = graph.getValue(r);
1433 } catch (DatabaseException e) {
1434 return e.getMessage();
1435 } catch (IOException e) {
1436 return e.getMessage();
1437 } catch (BindingException e) {
1438 return e.getMessage();
1442 private static String safeReadableString(ReadGraph g, Resource r) {
1444 return NameUtils.getSafeName(g, r);
1445 } catch(Throwable throwable) {
1446 ErrorLogger.defaultLogError(throwable);
1447 return "<font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font>";
1451 // private static String safeReadableString(IEntity t) {
1453 // return ResourceDebugUtils.getReadableNameForEntity(t);
1454 // } catch(Throwable throwable) {
1455 // throwable.printStackTrace();
1456 // return "<font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font>";
1460 private String getLinkString(Container<Resource> t) {
1461 String link = links.getLeft(t.get());
1463 link = UUID.randomUUID().toString();
1464 links.map(link, t.get());
1469 // private String getPropertyEditString(Container<Resource> t) {
1470 // String link = links.getLeft(t.get());
1471 // if(link == null) {
1472 // link = UUID.randomUUID().toString();
1473 // links.map(link, t.get());
1478 private String getStatementString(Resource _s, Resource _p, Resource _o) {
1479 String s = getLinkString(_s);
1480 String p = getLinkString(_p);
1481 String o = getLinkString(_o);
1482 return s + STATEMENT_PART_SEPARATOR + p + STATEMENT_PART_SEPARATOR + o;
1485 // private String getStatementString(Statement stm) {
1486 // String s = getLinkString(stm.getSubject());
1487 // String p = getLinkString(stm.getPredicate());
1488 // String o = getLinkString(stm.getObject());
1489 // return s + STATEMENT_PART_SEPARATOR + p + STATEMENT_PART_SEPARATOR + o;
1492 // private String toOutgoingTableRow(IEntity subject, Statement stm) {
1493 // boolean isAcquired = !subject.equals(stm.getSubject());
1495 // String plainCell = "%s";
1496 // String hrefCell = "<a href=\"%s\">%s</a>";
1497 // String formatTemplate = isAcquired
1498 // ? "<tr>\n<td class=\"acquired\">{0}</td>\n<td class=\"acquired\">{1}</td>\n<td class=\"acquired\">{1}</td>\n<td class=\"acquired\">{1}</td>\n</tr>"
1499 // : "<tr>\n<td>{1}</td>\n<td>{1}</td>\n<td>{1}</td>\n<td>{1}</td>\n</tr>";
1500 // String format = NLS.bind(formatTemplate, plainCell, hrefCell);
1501 //// System.out.println("format: " + format);
1503 // IEntity s = stm.getSubject();
1504 // IEntity p = stm.getPredicate();
1505 // IEntity o = stm.getObject();
1507 //// String timePart = "[" + timeToString(t.getBegin()) + ", " + timeToString(t.getEnd()) + "]";
1510 // return !isAcquired
1511 // ? String.format(format,
1512 // "about:blank-remove" + getStatementString(stm), "Remove",
1513 // "about:blank-link" + getLinkString(s), safeReadableString(s),
1514 // "about:blank-link" + getLinkString(p), safeReadableString(p),
1515 // "about:blank-link" + getLinkString(o), safeReadableString(o))
1516 // : String.format(format,
1518 // "about:blank-link" + getLinkString(s), safeReadableString(s),
1519 // "about:blank-link" + getLinkString(p), safeReadableString(p),
1520 // "about:blank-link" + getLinkString(o), safeReadableString(o)
1522 // } catch (Throwable throwable) {
1523 // return "<tr><td colspan=\"4\"><font color=\"red\"><i>"+throwable.getClass().getName()+"</i> "+throwable.getMessage()+"</font></td></tr>";
1527 // private String intervalToString(Interval time) {
1528 // return timeToString(time.getBegin()) + ", " + timeToString(time.getEnd());
1531 // DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
1533 // private String timeToString(long time) {
1534 // if (time == Long.MIN_VALUE)
1535 // return "-∞";
1536 // if (time == Long.MAX_VALUE)
1537 // return "+∞";
1538 // //return String.valueOf(time);
1539 // Date d = new Date(time);
1540 // return dateTimeFormat.format(d);
1543 private String getHead() {
1545 if (cssPath != null) {
1546 result = "<link href=\"" + cssPath + "\" rel=\"stylesheet\" type=\"text/css\">";