The chat responses are generated using Generative AI technology for intuitive search and may not be entirely accurate. They are not intended as professional advice. For full details, including our use rights, privacy practices and potential export control restrictions, please refer to our Generative AI Service Privacy Information. As this is a test version, please let us know if something irritating comes up. Like you get recommended a chocolate fudge ice cream instead of an energy managing application. If that occurs, please use the feedback button in our contact form!
Skip to content

Traceability with endpoints

2612

The Traceability panel with upstream items, the root and its downstream tree

AspectDetails
Folderexamples/traceability
Identifiercom.example.traceability
Viewform extension tree
EndpointsGET linked-tree, POST add-comment
Placement<applicationView id="com.example.traceability.tree" label="Traceability" height="480px"/>
UsesfetchContext(), context.appEndpoint, GraalVM scripts with the tracker service

What it does

  1. The view fetches the context and calls GET {appEndpoint}/linked-tree?objectId=test/TEST-514&depth=2, optionally with role=implements to show only links of one role.
  2. linked-tree.js runs on the server: it loads the work item, walks its direct links (downstream) recursively to the requested depth and its back links (upstream) one level, marks suspect links, and returns a nested tree in one response, together with the link roles it met.
  3. The view renders upstream items, then the root with its downstream tree: role, id, title, status, and a warning chip on suspect links.
  4. A textarea and Add comment button call POST {appEndpoint}/add-comment with { objectId, text }; add-comment.js creates the comment through the Java API and saves.

Files

  • traceability/
    • manifest.json
    • server-scripts/
      • linked-tree.js GET endpoint
      • add-comment.js POST endpoint
    • src/
      • App.tsx context, endpoint calls, state
      • LinkTree.tsx role filter and tree rendering
      • polarion.ts endpointFetch helper
      • types.ts
      • main.tsx
      • styles.css
    • …

manifest.json

The serverScripts.endpoints section maps paths and methods to the script files.

manifest.json
{
  "manifestVersion": "1.0",
  "identifier": "com.example.traceability",
  "title": "Traceability",
  "description": "Shows the link tree of the current work item, computed by a server script, and adds comments through a POST endpoint.",
  "publisherName": "Example Publisher",
  "applicationVersion": "0.2.2",
  "views": {
    "formExtensions": [
      {
        "identifier": "tree",
        "title": "Traceability",
        "rootDirectory": "tree",
        "document": "index.html"
      }
    ]
  },
  "serverScripts": {
    "endpoints": [
      {
        "urlPath": "linked-tree",
        "method": "GET",
        "script": "linked-tree.js"
      },
      {
        "urlPath": "add-comment",
        "method": "POST",
        "script": "add-comment.js"
      }
    ]
  }
}

server-scripts/linked-tree.js

server-scripts/linked-tree.js
// GET /polarion/apps/com.example.traceability/rest/linked-tree?objectId=PROJECT/WI-ID&depth=2[&role=implements]
//
// Runs on the Polarion server (GraalVM JavaScript) as the logged-in user.
// Walks the work item links in both directions and returns a nested tree.
// The optional `role` filter applies to links in both directions.
//
// Globals provided by Polarion:
//   context   – IScriptContext access: context.scriptContext().services().tracker()
//   arguments – IArguments: request parameters (query string for GET, JSON body for POST)

const trackerService = context.scriptContext().services().tracker();
let result = {};

// Polarion's IArguments throws ("Argument <name> is missing in workflow definition")
// when a parameter is absent. Optional parameters are therefore read through a guard.
const scriptArguments = arguments;
function getOptionalParam(name, defaultValue) {
  try {
    const value = scriptArguments.getAsString(name);
    return value === null || value === undefined || String(value) === '' ? defaultValue : String(value);
  } catch (e) {
    return defaultValue;
  }
}

function readParameters() {
  const objectId = scriptArguments.getAsString('objectId');
  if (!objectId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  const depth = Math.min(3, Math.max(1, parseInt(getOptionalParam('depth', '2'), 10) || 2));
  const roleParam = getOptionalParam('role', '');
  const roleFilter = roleParam ? String(roleParam).trim().toLowerCase() : '';
  return { objectId, depth, roleFilter };
}

function findWorkItem(objectId) {
  const [projectId, workItemId] = objectId.split('/');
  const workItem = trackerService.getWorkItem(projectId, workItemId);
  if (workItem.isUnresolvable()) {
    throw new Error('Work item not found: ' + objectId);
  }
  return workItem;
}

/** Suspect flag of a link; defaults to false if the API call is unavailable. */
function isSuspect(link) {
  try {
    return link.isSuspect() === true;
  } catch (e) {
    return false;
  }
}

/** Id, name and opposite name of a link role, e.g. "verifies", "verifies", "is verified by". */
function roleInfo(link) {
  const role = link.getLinkRole();
  if (!role) return { id: '', name: '', oppositeName: '' };
  let oppositeName = '';
  try {
    oppositeName = role.getOppositeName() ? String(role.getOppositeName()) : '';
  } catch (e) {
    // Without an opposite name the filter matches the id and the name only.
  }
  return { id: String(role.getId()), name: String(role.getName()), oppositeName: oppositeName };
}

// Every role met while walking, so the view can offer them in its filter.
const rolesSeen = new Map();
function remember(info) {
  if (info.id && !rolesSeen.has(info.id)) {
    rolesSeen.set(info.id, info);
  }
}

/**
 * True when no role filter is set or the link role matches it (case-insensitive).
 * The filter compares the role id, its name and its opposite name, so "verifies" also
 * matches a back link that reads "is verified by" from this side.
 */
function roleMatches(info, roleFilter) {
  if (!roleFilter) return true;
  return [info.id, info.name, info.oppositeName].some((value) => value.toLowerCase() === roleFilter);
}

function toTreeNode(workitem) {
  return {
    id: workitem.getProjectId() + '/' + workitem.getId(),
    title: workitem.getTitle(),
    type: workitem.getType() ? workitem.getType().getName() : null,
    status: workitem.getStatus() ? workitem.getStatus().getName() : null,
  };
}

// Direct links ("this item implements X") become the downstream children.
// `ancestors` holds the items on the path from the root to here. Each branch gets its own
// copy, so a cycle stops the recursion but an item reached on two paths is expanded on both.
function buildDownstreamNodes(workitem, depth, ancestors, roleFilter) {
  const workItemId = workitem.getProjectId() + '/' + workitem.getId();
  if (depth <= 0 || ancestors.has(workItemId)) {
    return [];
  }
  const path = new Set(ancestors);
  path.add(workItemId);

  const downstream = [];
  // Java collections are easiest to iterate as arrays from GraalVM JavaScript.
  const direct = workitem.getLinkedWorkItemsStructsDirect().toArray();
  for (let i = 0; i < direct.length; i++) {
    const link = direct[i];
    const info = roleInfo(link);
    remember(info);
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const linkedWorkItem = link.getLinkedItem();
    const node = toTreeNode(linkedWorkItem);
    node.role = info.name;
    node.suspect = isSuspect(link);
    if (depth > 1 && !path.has(node.id)) {
      node.downstream = buildDownstreamNodes(linkedWorkItem, depth - 1, path, roleFilter);
    }
    downstream.push(node);
  }
  return downstream;
}

function buildUpstreamNodes(workItem, roleFilter) {
  const upstream = [];
  const back = workItem.getLinkedWorkItemsStructsBack().toArray();
  for (let i = 0; i < back.length; i++) {
    const link = back[i];
    const info = roleInfo(link);
    remember(info);
    // The role filter applies in both directions: a requirement filtered by "verifies"
    // shows the test cases that verify it, which are back links seen from here.
    if (!roleMatches(info, roleFilter)) {
      continue;
    }
    const node = toTreeNode(link.getLinkedItem());
    // Seen from this item a back link reads in the opposite direction ("is verified by").
    node.role = info.oppositeName || info.name;
    node.suspect = isSuspect(link);
    upstream.push(node);
  }
  return upstream;
}

try {
  const { objectId, depth, roleFilter } = readParameters();
  const workItem = findWorkItem(objectId);

  const rootWorkItemNode = toTreeNode(workItem);
  rootWorkItemNode.downstream = buildDownstreamNodes(workItem, depth, new Set(), roleFilter);
  rootWorkItemNode.upstream = buildUpstreamNodes(workItem, roleFilter);

  result = { item: rootWorkItemNode, roles: Array.from(rolesSeen.values()) };
} catch (e) {
  // An `error` key turns the response into an error response for the caller.
  result = { error: 'linked-tree failed: ' + e };
}

result;

server-scripts/add-comment.js

server-scripts/add-comment.js
// POST /polarion/apps/com.example.traceability/rest/add-comment
// Body: { "objectId": "PROJECT/WI-ID", "text": "…" }
//
// Adds a plain-text comment to the work item. Runs as the logged-in user, who
// therefore needs permission to comment on the item.

const trackerService = context.scriptContext().services().tracker();
const Text = Java.type('com.polarion.core.util.types.Text');
let result = {};

try {
  const fullId = arguments.getAsString('objectId');
  const text = arguments.getAsString('text');
  if (!fullId) {
    throw new Error('objectId parameter is required (PROJECT/WI-ID)');
  }
  if (!text || text.trim() === '') {
    throw new Error('text parameter is required');
  }

  const [projectId, workitemId] = fullId.split('/');
  const workitem = trackerService.getWorkItem(projectId, workitemId);
  if (workitem.isUnresolvable()) {
    throw new Error('Work item not found: ' + fullId);
  }

  // createComment(IText text, String title, IComment parent) returns the new
  // IComment. Saving the work item alone does not persist it; save the comment.
  const comment = workitem.createComment(Text.plain(text), 'Traceability app', null);
  comment.save();

  // The id may not be assigned yet right after save; report it when available.
  const commentId = comment.getId();
  result = { ok: true, commentId: commentId ? String(commentId) : null };
} catch (e) {
  result = { error: 'add-comment failed: ' + e };
}

result;

Note

Text.plain() comes from com.polarion.core.util.types.Text; createComment(IText, String, IComment) is the IWorkItem method and returns the new IComment, which must be saved with comment.save(). Saving the work item alone does not persist the comment.

src/polarion.ts

The endpoint helper: same token header as for REST, plus unwrapping of the { success, data, error } envelope.

src/polarion.ts
import type { PolarionContext } from "polarion-app-sdk";

/** Envelope that Polarion wraps around every server-script response. */
interface Envelope<T> {
  timestamp?: string;
  success?: boolean;
  error?: string;
  data?: T;
}

/**
 * Calls one of the application's own endpoints declared in
 * manifest.json under `serverScripts.endpoints`.
 *
 * `context.appEndpoint` is the absolute base URL of those endpoints, for example
 * `https://host/polarion/apps/com.example.traceability/rest` (no trailing slash), so `path`
 * starts with a slash, as in `restFetch`: `"/validate"`. The same
 * `X-Polarion-REST-Token` header as for the REST API authenticates the call.
 * The response envelope is unwrapped so callers only see the script's result.
 */
export async function endpointFetch<T>(context: PolarionContext, path: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);
  headers.set("X-Polarion-REST-Token", context.restToken ?? "");
  headers.set("Accept", "application/json");
  if (init.body !== undefined && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(`${context.appEndpoint}${path}`, { ...init, headers });

  // Script errors come back as HTTP 400 with the envelope, so parse the body
  // whenever it is JSON and surface the script's own message.
  const text = await response.text();
  let envelope: Envelope<T> | undefined;
  try {
    envelope = JSON.parse(text) as Envelope<T>;
  } catch {
    envelope = undefined;
  }
  if (envelope && (envelope.success === false || envelope.error)) {
    throw new Error(envelope.error ?? "Server script reported an error.");
  }
  if (!response.ok || !envelope) {
    throw new Error(`Endpoint ${response.status}: ${text}`);
  }
  return envelope.data as T;
}

src/App.tsx

src/App.tsx
import { useEffect, useRef, useState } from "react";
import { destroy, fetchContext, type PolarionContext } from "polarion-app-sdk";
import { endpointFetch } from "./polarion";
import LinkTree from "./LinkTree";
import type { AddCommentResult, LinkedTreeResult, LinkRole, TreeNode, CommentState } from "./types";

export default function App() {
  const [tree, setTree] = useState<TreeNode | null>(null);
  const [role, setRole] = useState("");
  const [roles, setRoles] = useState<LinkRole[]>([]);
  const [comment, setComment] = useState("");
  const [commentState, setCommentState] = useState<CommentState>({ kind: "idle" });
  const [error, setError] = useState<string | null>(null);

  // Keep the fetched context available to filter changes without triggering a render.
  const contextRef = useRef<PolarionContext | null>(null);
  // Changing the role quickly starts several loads; only the latest request may update the view.
  const requestRef = useRef(0);

  // Loads the linked workitem tree rooted at the selected work item. The server follows downstream
  // links recursively to the requested depth and includes direct upstream links; the role filter
  // applies to links in both directions.
  const loadTree = async (context: PolarionContext, roleFilter = "") => {
    const request = ++requestRef.current;
    setError(null);

    // Build the query from the current work item and optional role filter selected.
    const params = new URLSearchParams({
      objectId: `${context.projectId}/${context.workItemId}`,
      depth: "2",
    });
    if (roleFilter.trim() !== "") {
      params.set("role", roleFilter.trim());
    }

    try {
      // Fetch the linked tree from the server using the constructed query parameters.
      const result = await endpointFetch<LinkedTreeResult>(context, `/linked-tree?${params}`);
      // Ignore responses that finished after a more recent load was started.
      if (request !== requestRef.current) {
        return;
      }

      setTree(result.item);
      // Keep roles from previous responses so filtering does not hide other available options.
      setRoles((knownRoles) => {
        const byId = new Map(knownRoles.map((knownRole) => [knownRole.id, knownRole]));
        const resultRoles = result.roles ?? [];
        resultRoles.forEach((resultRole) => byId.set(resultRole.id, resultRole));
        return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name));
      });
    } catch (cause) {
      // Only show errors from the latest request; an outdated failure is no longer relevant.
      if (request === requestRef.current) {
        console.error("Unable to load the linked work items:", cause);
        const message = cause instanceof Error ? cause.message : String(cause);
        setError(`Unable to load the linked work items: ${message}`);
      }
    }
  };

  const addCommentHandler = async () => {
    const context = contextRef.current;
    if (!context) {
      setCommentState({ kind: "error", message: "Work item context is not available." });
      return;
    }

    setCommentState({ kind: "saving" });
    try {
      const result = await endpointFetch<AddCommentResult>(context, "/add-comment", {
        method: "POST",
        body: JSON.stringify({
          objectId: `${context.projectId}/${context.workItemId}`,
          text: comment.trim(),
        }),
      });
      if (!result.ok) {
        throw new Error("The server did not confirm that the comment was added.");
      }

      setComment("");
      setCommentState({
        kind: "success",
        message: `Comment added${result.commentId ? ` (${result.commentId})` : ""}. Reload the page to see it.`,
      });
    } catch (cause: unknown) {
      console.error("Unable to add the comment:", cause);
      const message = cause instanceof Error ? cause.message : String(cause);
      setCommentState({ kind: "error", message: `Unable to add the comment: ${message}` });
    }
  };

  // Initialize the view by fetching the context and loading the tree.
  useEffect(() => {
    let cancelled = false;

    const initialize = async () => {
      try {
        const context: PolarionContext = await fetchContext();
        if (cancelled) {
          return;
        }
        if (!context.projectId || !context.workItemId) {
          setError("This view must be placed on a work item form.");
          return;
        }

        contextRef.current = context;
        await loadTree(context);
      } catch (cause) {
        if (!cancelled) {
          console.error("Unable to fetch the Polarion context:", cause);
          const message = cause instanceof Error ? cause.message : String(cause);
          setError(`Unable to fetch the Polarion context: ${message}`);
        }
      }
    };

    initialize();

    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      requestRef.current += 1;
      destroy();
    };
  }, []);

  const applyRole = (selectedRole: string) => {
    setRole(selectedRole);
    if (contextRef.current) {
      void loadTree(contextRef.current, selectedRole);
    }
  };

  if (error) {
    return <div className="card error">{error}</div>;
  } else if (!tree) {
    return <p className="muted">Computing the link tree on the server…</p>;
  }

  return (
    <div className="card">
      <LinkTree tree={tree} roles={roles} role={role} onRoleChange={applyRole} />

      <h2>Add a comment</h2>
      <textarea rows={3} value={comment} onChange={(event) => setComment(event.target.value)} placeholder="Comment text" />
      <div className="row">
        <button onClick={addCommentHandler} disabled={commentState.kind === "saving" || comment.trim() === ""}>
          {commentState.kind === "saving" ? "Saving…" : "Add comment"}
        </button>
        {commentState.message && <span className={commentState.kind === "success" ? "ok" : "err"}>{commentState.message}</span>}
      </div>
    </div>
  );
}

Points worth noting:

  • One round trip. Fetching a two-level link tree through REST would take one request per node; the endpoint does it server-side and returns the result at once.
  • The role filter works in both directions. A link is stored on one side only: a test case verifies a requirement, a task has parent a work package. Seen from the requirement or the work package these are back links, labelled with the role's opposite name (is verified by, is parent of). The script therefore filters upstream and downstream links alike and compares the role id, its name and its opposite name. The view offers the roles found on the item in a dropdown, so nobody has to guess role ids.
  • Parameters in the right place. The GET endpoint receives objectId, depth and role in the query string; the POST endpoint receives objectId and text in the JSON body.
  • Errors are data. A failing script returns success: false with a message; the helper converts that into a thrown error, and the component shows it.
  • Writes need permission. add-comment runs as the user; without comment permission the envelope carries the Java exception message.
  • Only the latest load counts. Changing the role quickly starts several requests; a counter in requestRef lets only the most recent response update the tree, and the cleanup of the mount effect sets a cancelled flag before destroy().

src/LinkTree.tsx

The role dropdown and the tree. LinkTree receives the tree and the known roles as props and reports a new role through onRoleChange; App.tsx then reloads the tree from the endpoint. A private Node component renders one node and calls itself for the node's downstream children.

src/LinkTree.tsx
import type { LinkRole, TreeNode } from "./types";

type LinkTreeProps = {
  tree: TreeNode;
  roles: LinkRole[];
  role: string;
  onRoleChange: (role: string) => void;
};

function itemUrl(fullId: string): string {
  const [project, id] = fullId.split("/");
  return `${window.location.origin}/polarion/#/project/${project}/workitem?id=${id}`;
}

function Node({ node, level = 0, isRoot = false }: { node: TreeNode; level?: number; isRoot?: boolean }) {
  const workitemId = node.id.split("/")[1] ?? node.id;

  const className = isRoot ? "node root" : "node";
  const style = { paddingLeft: `${level * 20}px` };
  return (
    <>
      <div className={className} style={style}>
        {node.role && <span className="role">{node.role}</span>}
        <a href={itemUrl(node.id)} target="_top">
          {workitemId}
        </a>
        <span className="title">{node.title}</span>
        {node.type && <span className="chip">{node.type}</span>}
        {node.status && <span className="chip status">{node.status}</span>}
        {node.suspect && (
          <span className="chip warn" title="The linked item changed after the link was created">
            suspect
          </span>
        )}
      </div>
      {node.downstream?.map((child) => (
        <Node key={child.id} node={child} level={level + 1} />
      ))}
    </>
  );
}

export default function LinkTree({ tree, roles, role, onRoleChange }: LinkTreeProps) {
  return (
    <>
      {/* Optional role filter, passed to the GET endpoint as the `role` parameter. It offers the
          roles found on this item's links and applies to upstream and downstream links alike. */}
      <div className="row filter">
        <label htmlFor="role">Link role</label>
        <select id="role" value={role} onChange={(event) => onRoleChange(event.target.value)}>
          <option value="">All roles</option>
          {roles.map((linkRole) => (
            <option key={linkRole.id} value={linkRole.id}>
              {linkRole.oppositeName && linkRole.oppositeName !== linkRole.name ? `${linkRole.name} / ${linkRole.oppositeName}` : linkRole.name}
            </option>
          ))}
        </select>
      </div>

      <h2>Upstream (items linking to this one)</h2>
      {tree.upstream?.length ? tree.upstream.map((parent) => <Node key={parent.id} node={parent} />) : <p className="muted">No upstream links.</p>}

      <h2>This item and its downstream links</h2>
      <Node node={tree} isRoot />
      {!tree.downstream?.length && <p className="muted">No downstream links.</p>}
    </>
  );
}

Build and deploy

cd examples/traceability
npm install
npm run package          # → com.example.traceability.zip (with server-scripts/)

Upload the ZIP, add the applicationView element to a form layout, and open a work item that has links. To see upstream links, open an item that is the target of a link from another item.

Things to try

  • Return the link's own id so that the view can offer Clear suspect through the REST API.
  • Add a maxNodes parameter and stop the walk when it is reached, returning truncated: true.
  • Call the endpoint directly in the browser while logged in: https://<host>/polarion/apps/com.example.traceability/rest/linked-tree?objectId=test/TEST-514 shows the raw envelope.