private void writeNodes(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception {
    if (cancel) {
      return;
    }
    xmlWriter.writeStartElement(NODES);

    AttributeColumn dynamicCol =
        dynamicCol = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);

    NodeIterable nodeIterable = exportHierarchy ? graph.getNodesTree() : graph.getNodes();
    for (Node node : nodeIterable) {
      xmlWriter.writeStartElement(NODE);

      String id = node.getNodeData().getId();
      xmlWriter.writeAttribute(NODE_ID, id);
      if (node.getNodeData().getLabel() != null && !node.getNodeData().getLabel().isEmpty()) {
        xmlWriter.writeAttribute(NODE_LABEL, node.getNodeData().getLabel());
      }

      if (exportHierarchy) {
        Node parent = graph.getParent(node);
        if (parent != null) {
          xmlWriter.writeAttribute(NODE_PID, parent.getNodeData().getId());
        }
      }

      if (exportDynamic && dynamicCol != null && visibleInterval != null) {
        TimeInterval timeInterval =
            (TimeInterval) node.getNodeData().getAttributes().getValue(dynamicCol.getIndex());
        if (timeInterval != null) {
          writeTimeInterval(xmlWriter, timeInterval);
        }
      }

      if (exportAttributes && node.getNodeData().getAttributes() != null) {
        AttributeRow attributeRow = (AttributeRow) node.getNodeData().getAttributes();
        writeAttValues(xmlWriter, attributeRow, visibleInterval);
      }

      if (exportSize) {
        writeNodeSize(xmlWriter, node);
      }

      if (exportPosition) {
        writeNodePosition(xmlWriter, node);
      }

      if (exportColors) {
        writeNodeColor(xmlWriter, node);
      }

      xmlWriter.writeEndElement();
      Progress.progress(progress);
      if (cancel) {
        break;
      }
    }

    xmlWriter.writeEndElement();
  }
  @Override
  public void execute(GraphModel graphModel, AttributeModel attributeModel) {
    // Graph graph = graphModel.getGraphVisible();
    HierarchicalGraph graph = null;
    // get visible graph
    if (directed) {
      graph = graphModel.getHierarchicalDirectedGraphVisible();
    } else {
      graph = graphModel.getHierarchicalUndirectedGraphVisible();
    }

    // lock graph
    graph.readLock();
    try {
      Progress.start(progressTicket, graph.getNodeCount());
      // all coefficients
      nodeCoefficients = new double[graph.getNodeCount()];

      // attribute column
      AttributeTable nodeTable = attributeModel.getNodeTable();
      AttributeColumn clusteringColumn = nodeTable.getColumn("newClusteringCoefficient");
      if (clusteringColumn == null) {
        clusteringColumn =
            nodeTable.addColumn(
                "newClusteringCoefficient",
                "Local Clustering Coefficient",
                AttributeType.DOUBLE,
                AttributeOrigin.COMPUTED,
                0.0);
      }

      int i = 0;
      // for each node
      for (Node e : graph.getNodes()) {
        // compute coefficient
        double coeficient = 0.0;
        double denominator = (graph.getDegree(e) * (graph.getDegree(e) - 1));
        if (!directed) {
          denominator /= 2;
        }
        double numerator = 0.0;
        // get neighbors as list
        List<Node> n2 = Arrays.asList(graph.getNeighbors(e).toArray());
        List<Node> neighbors2 = new ArrayList<Node>(n2);
        for (Node neighbor1 : graph.getNeighbors(e)) {
          neighbors2.remove(neighbor1);
          // count edges betwwen neighbors
          for (Node neighbor2 : neighbors2) {
            if (graph.getEdge(neighbor1, neighbor2) != null
                || graph.getEdge(neighbor2, neighbor1) != null) {
              numerator++;
            }
          }
        }
        // compute coefficient
        if (denominator > 0) {
          coeficient = numerator / denominator;
        } else {
          coeficient = 0.0;
        }
        averageCoefficient += coeficient;
        nodeCoefficients[i] = coeficient;
        i++;
        // set attribute
        AttributeRow row = (AttributeRow) e.getNodeData().getAttributes();
        row.setValue(clusteringColumn, coeficient);
        Progress.progress(progressTicket);
        if (cancel) {
          break;
        }
      }
      if (graph.getNodeCount() > 0) {
        averageCoefficient = averageCoefficient / graph.getNodeCount();
      }

      graph.readUnlockAll();
    } catch (Exception e) {
      e.printStackTrace();
      // Unlock graph
      graph.readUnlockAll();
    }
  }
    @Override
    public BaseFont getBaseFont(java.awt.Font font) {
      try {
        if (font != null) {
          BaseFont baseFont = null;
          if (!font.getFontName().equals(FontFactory.COURIER)
              && !font.getFontName().equals(FontFactory.COURIER_BOLD)
              && !font.getFontName().equals(FontFactory.COURIER_OBLIQUE)
              && !font.getFontName().equals(FontFactory.COURIER_BOLDOBLIQUE)
              && !font.getFontName().equals(FontFactory.HELVETICA)
              && !font.getFontName().equals(FontFactory.HELVETICA_BOLD)
              && !font.getFontName().equals(FontFactory.HELVETICA_BOLDOBLIQUE)
              && !font.getFontName().equals(FontFactory.HELVETICA_OBLIQUE)
              && !font.getFontName().equals(FontFactory.SYMBOL)
              && !font.getFontName().equals(FontFactory.TIMES_ROMAN)
              && !font.getFontName().equals(FontFactory.TIMES_BOLD)
              && !font.getFontName().equals(FontFactory.TIMES_ITALIC)
              && !font.getFontName().equals(FontFactory.TIMES_BOLDITALIC)
              && !font.getFontName().equals(FontFactory.ZAPFDINGBATS)
              && !font.getFontName().equals(FontFactory.COURIER_BOLD)
              && !font.getFontName().equals(FontFactory.COURIER_BOLD)
              && !font.getFontName().equals(FontFactory.COURIER_BOLD)) {

            com.itextpdf.text.Font itextFont =
                FontFactory.getFont(
                    font.getFontName(), BaseFont.IDENTITY_H, font.getSize(), font.getStyle());
            baseFont = itextFont.getBaseFont();
            if (baseFont == null && !PDFRenderTargetImpl.fontRegistered) {

              if (progressTicket != null) {
                String displayName = progressTicket.getDisplayName();
                Progress.setDisplayName(
                    progressTicket,
                    NbBundle.getMessage(
                        PDFRenderTargetImpl.class, "PDFRenderTargetImpl.font.registration"));
                registerFonts();
                Progress.setDisplayName(progressTicket, displayName);
              }

              itextFont =
                  FontFactory.getFont(
                      font.getFontName(), BaseFont.IDENTITY_H, font.getSize(), font.getStyle());
              baseFont = itextFont.getBaseFont();

              PDFRenderTargetImpl.fontRegistered = true;
            }
          } else {
            com.itextpdf.text.Font itextFont =
                FontFactory.getFont(
                    font.getFontName(), BaseFont.IDENTITY_H, font.getSize(), font.getStyle());
            baseFont = itextFont.getBaseFont();
          }

          if (baseFont != null) {
            return baseFont;
          }
          return BaseFont.createFont();
        }
        return BaseFont.createFont();
      } catch (Exception e) {
        Exceptions.printStackTrace(e);
      }
      return null;
    }
  private void writeEdges(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception {
    if (cancel) {
      return;
    }
    xmlWriter.writeStartElement(EDGES);

    AttributeColumn dynamicCol =
        dynamicCol = attributeModel.getEdgeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);

    EdgeIterable edgeIterable =
        exportHierarchy ? graph.getEdgesTree() : graph.getEdgesAndMetaEdges();
    for (Edge edge : edgeIterable) {
      xmlWriter.writeStartElement(EDGE);

      if (edge.getEdgeData().getId() != null
          && !edge.getEdgeData().getId().equals(Integer.toString(edge.getId()))) {
        xmlWriter.writeAttribute(EDGE_ID, edge.getEdgeData().getId());
      }
      xmlWriter.writeAttribute(EDGE_SOURCE, edge.getSource().getNodeData().getId());
      xmlWriter.writeAttribute(EDGE_TARGET, edge.getTarget().getNodeData().getId());

      if (edge.isDirected() && graphModel.isMixed()) {
        xmlWriter.writeAttribute(EDGE_TYPE, "directed");
      } else if (!edge.isDirected() && graphModel.isMixed()) {
        xmlWriter.writeAttribute(EDGE_TYPE, "undirected");
      }

      String label = edge.getEdgeData().getLabel();
      if (label != null && !label.isEmpty()) {
        xmlWriter.writeAttribute(EDGE_LABEL, label);
      }

      float weight = edge.getWeight();
      if (weight != 1f) {
        xmlWriter.writeAttribute(EDGE_WEIGHT, "" + weight);
      }

      if (exportDynamic && dynamicCol != null && visibleInterval != null) {
        TimeInterval timeInterval =
            (TimeInterval) edge.getEdgeData().getAttributes().getValue(dynamicCol.getIndex());
        if (timeInterval != null) {
          writeTimeInterval(xmlWriter, timeInterval);
        }
      }

      if (exportColors) {
        writeEdgeColor(xmlWriter, edge);
      }

      if (exportAttributes && edge.getEdgeData().getAttributes() != null) {
        AttributeRow attributeRow = (AttributeRow) edge.getEdgeData().getAttributes();
        writeAttValues(xmlWriter, attributeRow, visibleInterval);
      }

      xmlWriter.writeEndElement();
      Progress.progress(progress);
      if (cancel) {
        break;
      }
    }

    xmlWriter.writeEndElement();
  }
  public boolean execute() {
    attributeModel = workspace.getLookup().lookup(AttributeModel.class);
    graphModel = workspace.getLookup().lookup(GraphModel.class);
    HierarchicalGraph graph = null;
    if (exportVisible) {
      graph = graphModel.getHierarchicalGraphVisible();
    } else {
      graph = graphModel.getHierarchicalGraph();
    }
    Progress.start(progress);
    graph.readLock();

    // Options
    if (normalize) {
      calculateMinMax(graph);
    }

    // Calculate progress units count
    int max = 0;
    if (exportHierarchy) {
      for (Node n : graph.getNodesTree()) {
        max++;
      }
      for (Edge e : graph.getEdgesTree()) {
        max++;
      }
    } else {
      max = graph.getNodeCount();
      for (Edge e : graph.getEdgesAndMetaEdges()) {
        max++;
      }
    }
    Progress.switchToDeterminate(progress, max);

    try {
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.FALSE);

      XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer);
      xmlWriter = new IndentingXMLStreamWriter(xmlWriter);

      xmlWriter.writeStartDocument("UTF-8", "1.0");
      xmlWriter.setPrefix("", GEXF_NAMESPACE);
      xmlWriter.writeStartElement(GEXF_NAMESPACE, GEXF);
      xmlWriter.writeNamespace("", GEXF_NAMESPACE);
      xmlWriter.writeAttribute(GEXF_VERSION, "1.1");

      if (exportColors || exportPosition || exportSize) {
        xmlWriter.writeNamespace(VIZ, VIZ_NAMESPACE);
      }
      xmlWriter.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
      xmlWriter.writeAttribute("xsi:schemaLocation", GEXF_NAMESPACE_LOCATION);

      if (exportDynamic) {
        DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
        dynamicModel = dynamicController != null ? dynamicController.getModel(workspace) : null;
        visibleInterval =
            dynamicModel == null
                ? null
                : exportVisible
                    ? dynamicModel.getVisibleInterval()
                    : new TimeInterval(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
      }

      writeMeta(xmlWriter);
      writeGraph(xmlWriter, graph);

      xmlWriter.writeEndElement();
      xmlWriter.writeEndDocument();
      xmlWriter.close();

    } catch (Exception e) {
      graph.readUnlockAll();
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }
      throw new RuntimeException(e);
    }

    graph.readUnlock();

    Progress.finish(progress);
    return !cancel;
  }
  private void exportData(Graph graph) throws Exception {
    int max = graph.getNodeCount();

    Progress.start(progressTicket, max);

    if (!list) {
      if (header) {
        writer.append(SEPARATOR);
        Node[] nodes = graph.getNodes().toArray();
        for (int i = 0; i < nodes.length; i++) {
          writeMatrixNode(nodes[i], i < nodes.length - 1);
        }
        writer.append(EOL);
      }
    }

    if (list) {
      Node[] nodes = graph.getNodes().toArray();
      for (int i = 0; i < nodes.length; i++) {
        Node n = nodes[i];
        List<Node> neighbours = new ArrayList<Node>();
        for (Edge e : graph.getEdges(n)) {
          if (!e.isDirected() || (e.isDirected() && n == e.getSource())) {
            Node m = graph.getOpposite(n, e);
            neighbours.add(m);
          }
        }

        for (Edge e : ((HierarchicalGraph) graph).getMetaEdges(n)) {
          if (!e.isDirected() || (e.isDirected() && n == e.getSource())) {
            Node m = graph.getOpposite(n, e);
            neighbours.add(m);
          }
        }

        writeListNode(n, !neighbours.isEmpty());
        for (int j = 0; j < neighbours.size(); j++) {
          writeListNode(neighbours.get(j), j < neighbours.size() - 1);
        }
        writer.append(EOL);
      }
    } else {
      if (graph instanceof DirectedGraph) {
        DirectedGraph directedGraph = (DirectedGraph) graph;
        Node[] nodes = graph.getNodes().toArray();
        for (Node n : nodes) {
          if (cancel) {
            break;
          }
          writeMatrixNode(n, true);
          for (int j = 0; j < nodes.length; j++) {
            Node m = nodes[j];
            Edge e = directedGraph.getEdge(n, m);
            e = e == null ? ((HierarchicalDirectedGraph) directedGraph).getMetaEdge(n, m) : e;
            writeEdge(e, j < nodes.length - 1);
          }
          Progress.progress(progressTicket);
          writer.append(EOL);
        }
      } else if (graph instanceof UndirectedGraph) {
        UndirectedGraph undirectedGraph = (UndirectedGraph) graph;
        Node[] nodes = graph.getNodes().toArray();
        for (Node n : nodes) {
          if (cancel) {
            break;
          }
          writeMatrixNode(n, true);
          for (int j = 0; j < nodes.length; j++) {
            Node m = nodes[j];
            Edge e = undirectedGraph.getEdge(n, m);
            e = e == null ? ((HierarchicalUndirectedGraph) undirectedGraph).getMetaEdge(n, m) : e;
            writeEdge(e, j < nodes.length - 1);
          }
          Progress.progress(progressTicket);
          writer.append(EOL);
        }
      } else {
        MixedGraph mixedGraph = (MixedGraph) graph;
        Node[] nodes = graph.getNodes().toArray();
        for (Node n : graph.getNodes()) {
          if (cancel) {
            break;
          }
          writeMatrixNode(n, true);
          for (int j = 0; j < nodes.length; j++) {
            Node m = nodes[j];
            Edge e = mixedGraph.getEdge(n, m);
            e = e == null ? ((HierarchicalMixedGraph) mixedGraph).getMetaEdge(n, m) : e;
            writeEdge(e, j < nodes.length - 1);
          }
          Progress.progress(progressTicket);
          writer.append(EOL);
        }
      }
    }

    graph.readUnlockAll();

    Progress.finish(progressTicket);
  }
 public void progress() {
   Progress.progress(progressTicket);
 }
 public void start(int iterations) {
   Progress.start(progressTicket, iterations);
 }
Esempio n. 9
0
  protected void process(ContainerUnloader container, Workspace workspace) {
    // Architecture
    GraphController graphController = Lookup.getDefault().lookup(GraphController.class);
    graphModel = graphController.getGraphModel(workspace);

    // Get graph
    Graph graph = graphModel.getGraph();
    GraphFactory factory = graphModel.factory();

    // Time Format & Time zone
    graphModel.setTimeFormat(container.getTimeFormat());
    graphModel.setTimeZone(container.getTimeZone());

    // Progress
    Progress.start(progressTicket, container.getNodeCount() + container.getEdgeCount());

    // Attributes - Creates columns for properties
    flushColumns(container);

    // Counters
    int addedNodes = 0, addedEdges = 0;

    // Create all nodes
    ElementIdType elementIdType = container.getElementIdType();
    for (NodeDraft draftNode : container.getNodes()) {
      String idString = draftNode.getId();
      Object id = toElementId(elementIdType, idString);
      Node node = graph.getNode(id);
      if (node == null) {
        node = factory.newNode(id);
        addedNodes++;
      }
      flushToNode(draftNode, node);

      graph.addNode(node);

      Progress.progress(progressTicket);
    }

    // Create all edges and push to data structure
    for (EdgeDraft draftEdge : container.getEdges()) {
      String idString = draftEdge.getId();
      Object id = toElementId(elementIdType, idString);
      String sourceId = draftEdge.getSource().getId();
      String targetId = draftEdge.getTarget().getId();
      Node source = graph.getNode(toElementId(elementIdType, sourceId));
      Node target = graph.getNode(toElementId(elementIdType, targetId));
      Object type = draftEdge.getType();
      int edgeType = graphModel.addEdgeType(type);

      Edge edge = graph.getEdge(source, target, edgeType);
      if (edge == null) {
        switch (container.getEdgeDefault()) {
          case DIRECTED:
            edge = factory.newEdge(id, source, target, edgeType, draftEdge.getWeight(), true);
            break;
          case UNDIRECTED:
            edge = factory.newEdge(id, source, target, edgeType, draftEdge.getWeight(), false);
            break;
          case MIXED:
            boolean directed =
                draftEdge.getDirection() == null
                    || !draftEdge.getDirection().equals(EdgeDirection.UNDIRECTED);
            edge = factory.newEdge(id, source, target, edgeType, draftEdge.getWeight(), directed);
            break;
        }
        addedEdges++;
      }
      flushToEdge(draftEdge, edge);

      graph.addEdge(edge);

      Progress.progress(progressTicket);
    }

    // Report
    int touchedNodes = container.getNodeCount();
    int touchedEdges = container.getEdgeCount();
    if (touchedNodes != addedNodes || touchedEdges != addedEdges) {
      Logger.getLogger(getClass().getSimpleName())
          .log(
              Level.INFO,
              "# Nodes loaded: {0} ({1} added)",
              new Object[] {touchedNodes, addedNodes});
      Logger.getLogger(getClass().getSimpleName())
          .log(
              Level.INFO,
              "# Edges loaded: {0} ({1} added)",
              new Object[] {touchedEdges, addedEdges});
    } else {
      Logger.getLogger(getClass().getSimpleName())
          .log(Level.INFO, "# Nodes loaded: {0}", new Object[] {touchedNodes});
      Logger.getLogger(getClass().getSimpleName())
          .log(Level.INFO, "# Edges loaded: {0}", new Object[] {touchedEdges});
    }

    Progress.finish(progressTicket);
  }