public void script() {
    // Init a project - and therefore a workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    // Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);

    // Import file
    Container container;
    try {
      File file =
          new File(
              getClass().getResource("/org/gephi/toolkit/demos/resources/polblogs.gml").toURI());
      container = importController.importFile(file);
      container.getLoader().setEdgeDefault(EdgeDefault.DIRECTED); // Force DIRECTED
      container.setAllowAutoNode(false); // Don't create missing nodes
    } catch (Exception ex) {
      ex.printStackTrace();
      return;
    }

    // Append imported data to GraphAPI
    importController.process(container, new DefaultProcessor(), workspace);

    // List node columns
    AttributeController ac = Lookup.getDefault().lookup(AttributeController.class);
    AttributeModel model = ac.getModel();
    for (AttributeColumn col : model.getNodeTable().getColumns()) {
      System.out.println(col);
    }

    // Add boolean column
    AttributeColumn testCol = model.getNodeTable().addColumn("test", AttributeType.BOOLEAN);

    // Write values to nodes
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
    for (Node n : graphModel.getGraph().getNodes()) {
      n.getNodeData().getAttributes().setValue(testCol.getIndex(), Boolean.TRUE);
    }

    // Iterate values - fastest
    AttributeColumn sourceCol = model.getNodeTable().getColumn("source");
    for (Node n : graphModel.getGraph().getNodes()) {
      System.out.println(n.getNodeData().getAttributes().getValue(sourceCol.getIndex()));
    }

    // Iterate values - normal
    for (Node n : graphModel.getGraph().getNodes()) {
      System.out.println(n.getNodeData().getAttributes().getValue("source"));
    }
  }
Exemplo n.º 2
0
  public void script() {

    NetworkLayer nl = MultiLayerNetwork.getSelected();

    if (pc == null) pc = Lookup.getDefault().lookup(ProjectController.class);

    // Init a project - and therefore a workspace
    Project pro = pc.getCurrentProject();

    if (pro == null) {
      pc.newProject();
      pro = pc.getCurrentProject();
    }

    Workspace workspace = pc.newWorkspace(pro);

    // Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);
    GraphModel graphModel =
        Lookup.getDefault().lookup(GraphController.class).getGraphModel(workspace);
    //        AttributeModel attributeModel =
    // Lookup.getDefault().lookup(AttributeController.class).getModel();

    // Import database
    EdgeListHiveDatabaseImpl db = new EdgeListHiveDatabaseImpl();

    db.setDBName("default"); // !!!
    db.setHost("127.0.0.1");
    //       db.setHost( HadoopClusterDefaults.HIVE_SERVER_IP );
    db.setPort(10000); // !!!

    db.setUsername("kamir");
    db.setPasswd("8cwrr");

    db.setSQLDriver(new HiveJDBCDriver());

    String tab = "edgelist_es_de_erfurt2";

    db.setNodeQuery(
        "SELECT UNIQUE( " + tab + ".source ) AS id, " + tab + ".source AS label FROM " + tab);
    db.setEdgeQuery(
        "SELECT "
            + tab
            + ".source AS source, "
            + tab
            + ".target AS target "
            + tab
            + ".q0 AS weight FROM "
            + tab);

    ImporterEdgeList edgeListImporter = new ImporterEdgeList();

    Container container = null;

    String url = SQLUtils.getUrl(db.getSQLDriver(), db.getHost(), db.getPort(), db.getDBName());

    System.out.println(url);

    javax.swing.JOptionPane.showMessageDialog(null, "Go ... Hive! \n> " + url);

    try {
      container = importController.importDatabase(db, edgeListImporter);

      //            container.setAllowAutoNode(false);      //Don't create missing nodes
      container.getLoader().setEdgeDefault(EdgeDirectionDefault.UNDIRECTED); // Force UNDIRECTED

      // Append imported data to GraphAPI
      importController.process(container, new DefaultProcessor(), workspace);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      if (container != null) System.out.println(container.getReport().getText());
    }

    // See if graph is well imported
    UndirectedGraph graph = graphModel.getUndirectedGraph();
    System.out.println("Nodes: " + graph.getNodeCount());
    System.out.println("Edges: " + graph.getEdgeCount());

    // Layout - 100 Yifan Hu passes
    //        YifanHuLayout layout = new YifanHuLayout(null, new StepDisplacement(1f));
    //        layout.setGraphModel(graphModel);
    //        layout.resetPropertiesValues();
    //        layout.initAlgo();
    //        for (int i = 0; i < 100 && layout.canAlgo(); i++) {
    //            layout.goAlgo();
    //        }
    //        layout.endAlgo();

  }
  private void finishImport(Container[] containers) {
    Report finalReport = new Report();
    for (Container container : containers) {
      if (container.verify()) {
        Report report = container.getReport();
        report.close();
        finalReport.append(report);
      } else {
        // TODO
      }
    }
    finalReport.close();

    // Report panel
    ReportPanel reportPanel = new ReportPanel();
    reportPanel.setData(finalReport, containers);
    DialogDescriptor dd =
        new DialogDescriptor(
            reportPanel, NbBundle.getMessage(DesktopImportControllerUI.class, "ReportPanel.title"));
    Object response = DialogDisplayer.getDefault().notify(dd);
    reportPanel.destroy();
    finalReport.clean();
    for (Container c : containers) {
      c.getReport().clean();
    }
    if (!response.equals(NotifyDescriptor.OK_OPTION)) {
      return;
    }
    final Processor processor = reportPanel.getProcessor();

    // Project
    Workspace workspace = null;
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    ProjectControllerUI pcui = Lookup.getDefault().lookup(ProjectControllerUI.class);
    if (pc.getCurrentProject() == null) {
      pcui.newProject();
      workspace = pc.getCurrentWorkspace();
    }

    // Process
    final ProcessorUI pui = getProcessorUI(processor);
    final ValidResult validResult = new ValidResult();
    if (pui != null) {
      try {
        final JPanel panel = pui.getPanel();
        if (panel != null) {
          SwingUtilities.invokeAndWait(
              new Runnable() {
                @Override
                public void run() {
                  String title =
                      NbBundle.getMessage(
                          DesktopImportControllerUI.class,
                          "DesktopImportControllerUI.processor.ui.dialog.title");

                  pui.setup(processor);
                  final DialogDescriptor dd2 = new DialogDescriptor(panel, title);
                  if (panel instanceof ValidationPanel) {
                    ValidationPanel vp = (ValidationPanel) panel;
                    vp.addChangeListener(
                        new ChangeListener() {
                          @Override
                          public void stateChanged(ChangeEvent e) {
                            dd2.setValid(!((ValidationPanel) e.getSource()).isProblem());
                          }
                        });
                    dd2.setValid(!vp.isProblem());
                  }
                  Object result = DialogDisplayer.getDefault().notify(dd2);
                  if (result.equals(NotifyDescriptor.CANCEL_OPTION)
                      || result.equals(NotifyDescriptor.CLOSED_OPTION)) {
                    validResult.setResult(false);
                  } else {
                    pui.unsetup(); // true
                    validResult.setResult(true);
                  }
                }
              });
        }
      } catch (InterruptedException ex) {
        Exceptions.printStackTrace(ex);
      } catch (InvocationTargetException ex) {
        Exceptions.printStackTrace(ex);
      }
    }
    if (validResult.isResult()) {
      controller.process(containers, processor, workspace);

      // StatusLine notify
      StatusDisplayer.getDefault()
          .setStatusText(
              NbBundle.getMessage(
                  DesktopImportControllerUI.class,
                  "DesktopImportControllerUI.status.multiImportSuccess",
                  containers.length));
    }
  }
  @Override
  public void importWizard(final WizardImporter importer) {
    try {
      if (importer == null) {
        NotifyDescriptor.Message msg =
            new NotifyDescriptor.Message(
                NbBundle.getMessage(
                    DesktopImportControllerUI.class,
                    "DesktopImportControllerUI.error_no_matching_db_importer"),
                NotifyDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(msg);
        return;
      }

      String containerSource =
          NbBundle.getMessage(
              DesktopImportControllerUI.class, "DesktopImportControllerUI.wizardSource", "");
      ImporterUI ui = controller.getUI(importer);
      if (ui != null) {
        String title =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.wizard.ui.dialog.title",
                ui.getDisplayName());
        JPanel panel = ui.getPanel();
        ui.setup(new WizardImporter[] {importer});
        final DialogDescriptor dd = new DialogDescriptor(panel, title);
        if (panel instanceof ValidationPanel) {
          ValidationPanel vp = (ValidationPanel) panel;
          vp.addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  dd.setValid(!((ValidationPanel) e.getSource()).isProblem());
                }
              });
        }

        Object result = DialogDisplayer.getDefault().notify(dd);
        if (result.equals(NotifyDescriptor.CANCEL_OPTION)
            || result.equals(NotifyDescriptor.CLOSED_OPTION)) {
          ui.unsetup(false);
          return;
        }
        ui.unsetup(true);
        containerSource = ui.getDisplayName();
      }
      ImporterWizardUI wizardUI = controller.getWizardUI(importer);
      if (wizardUI != null) {
        containerSource = wizardUI.getCategory() + ":" + wizardUI.getDisplayName();
      }

      LongTask task = null;
      if (importer instanceof LongTask) {
        task = (LongTask) importer;
      }

      // Execute task
      final String source = containerSource;
      String taskName =
          NbBundle.getMessage(
              DesktopImportControllerUI.class,
              "DesktopImportControllerUI.taskName",
              containerSource);
      executor.execute(
          task,
          new Runnable() {
            @Override
            public void run() {
              try {
                Container container = controller.importWizard(importer);
                if (container != null) {
                  container.setSource(source);
                  finishImport(container);
                }
              } catch (Exception ex) {
                throw new RuntimeException(ex);
              }
            }
          },
          taskName,
          errorHandler);
    } catch (Exception ex) {
      Logger.getLogger("").log(Level.WARNING, "", ex);
    }
  }
  @Override
  public void importFile(final Reader reader, String importerName) {
    try {
      final FileImporter importer = controller.getFileImporter(importerName);
      if (importer == null) {
        NotifyDescriptor.Message msg =
            new NotifyDescriptor.Message(
                NbBundle.getMessage(
                    getClass(), "DesktopImportControllerUI.error_no_matching_file_importer"),
                NotifyDescriptor.WARNING_MESSAGE);
        DialogDisplayer.getDefault().notify(msg);
        return;
      }

      ImporterUI ui = controller.getUI(importer);
      if (ui != null) {
        ui.setup(new FileImporter[] {importer});
        String title =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.file.ui.dialog.title",
                ui.getDisplayName());
        JPanel panel = ui.getPanel();
        final DialogDescriptor dd = new DialogDescriptor(panel, title);
        if (panel instanceof ValidationPanel) {
          ValidationPanel vp = (ValidationPanel) panel;
          vp.addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  dd.setValid(!((ValidationPanel) e.getSource()).isProblem());
                }
              });
        }

        Object result = DialogDisplayer.getDefault().notify(dd);
        if (!result.equals(NotifyDescriptor.OK_OPTION)) {
          ui.unsetup(false);
          return;
        }
        ui.unsetup(true);
      }

      LongTask task = null;
      if (importer instanceof LongTask) {
        task = (LongTask) importer;
      }

      // Execute task
      final String containerSource =
          NbBundle.getMessage(
              DesktopImportControllerUI.class,
              "DesktopImportControllerUI.streamSource",
              importerName);
      String taskName =
          NbBundle.getMessage(
              DesktopImportControllerUI.class,
              "DesktopImportControllerUI.taskName",
              containerSource);
      executor.execute(
          task,
          new Runnable() {
            @Override
            public void run() {
              try {
                Container container = controller.importFile(reader, importer);
                if (container != null) {
                  container.setSource(containerSource);
                  finishImport(container);
                }
              } catch (Exception ex) {
                throw new RuntimeException(ex);
              }
            }
          },
          taskName,
          errorHandler);
    } catch (Exception ex) {
      Logger.getLogger("").log(Level.WARNING, "", ex);
    }
  }
  @Override
  public void importFiles(FileObject[] fileObjects) {
    try {
      Map<ImporterUI, List<FileImporter>> importerUIs =
          new HashMap<ImporterUI, List<FileImporter>>();
      List<FileImporter> importers = new ArrayList<FileImporter>();
      for (FileObject fileObject : fileObjects) {
        FileImporter importer = controller.getFileImporter(FileUtil.toFile(fileObject));
        if (importer == null) {
          NotifyDescriptor.Message msg =
              new NotifyDescriptor.Message(
                  NbBundle.getMessage(
                      getClass(), "DesktopImportControllerUI.error_no_matching_file_importer"),
                  NotifyDescriptor.WARNING_MESSAGE);
          DialogDisplayer.getDefault().notify(msg);
          return;
        }
        importers.add(importer);
        ImporterUI ui = controller.getUI(importer);
        if (ui != null) {
          List<FileImporter> l = importerUIs.get(ui);
          if (l == null) {
            l = new ArrayList<FileImporter>();
            importerUIs.put(ui, l);
          }
          l.add(importer);
        }

        // MRU
        MostRecentFiles mostRecentFiles = Lookup.getDefault().lookup(MostRecentFiles.class);
        mostRecentFiles.addFile(fileObject.getPath());
      }

      for (Map.Entry<ImporterUI, List<FileImporter>> entry : importerUIs.entrySet()) {
        ImporterUI ui = entry.getKey();
        String title =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.file.ui.dialog.title",
                ui.getDisplayName());
        JPanel panel = ui.getPanel();
        ui.setup(entry.getValue().toArray(new FileImporter[0]));
        final DialogDescriptor dd = new DialogDescriptor(panel, title);
        if (panel instanceof ValidationPanel) {
          ValidationPanel vp = (ValidationPanel) panel;
          vp.addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  dd.setValid(!((ValidationPanel) e.getSource()).isProblem());
                }
              });
        }

        Object result = DialogDisplayer.getDefault().notify(dd);
        if (!result.equals(NotifyDescriptor.OK_OPTION)) {
          ui.unsetup(false);
          return;
        }
        ui.unsetup(true);
      }

      final List<Container> result = new ArrayList<Container>();
      for (int i = 0; i < importers.size(); i++) {
        final FileImporter importer = importers.get(i);
        FileObject fileObject = fileObjects[i];
        LongTask task = null;
        if (importer instanceof LongTask) {
          task = (LongTask) importer;
        }

        // Execute task
        fileObject = getArchivedFile(fileObject);
        final String containerSource = fileObject.getNameExt();
        final InputStream stream = fileObject.getInputStream();
        String taskName =
            NbBundle.getMessage(
                DesktopImportControllerUI.class,
                "DesktopImportControllerUI.taskName",
                containerSource);
        executor.execute(
            task,
            new Runnable() {
              @Override
              public void run() {
                try {
                  Container container = controller.importFile(stream, importer);
                  if (container != null) {
                    container.setSource(containerSource);
                    result.add(container);
                  }
                } catch (Exception ex) {
                  throw new RuntimeException(ex);
                }
              }
            },
            taskName,
            errorHandler);
      }
      executor.execute(
          null,
          new Runnable() {

            @Override
            public void run() {
              if (!result.isEmpty()) {
                finishImport(result.toArray(new Container[0]));
              }
            }
          });
    } catch (Exception ex) {
      Logger.getLogger("").log(Level.WARNING, "", ex);
    }
  }
Exemplo n.º 7
0
  @Test
  public void testPNG() {
    try {

      // Init a project - and therefore a workspace
      ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
      pc.newProject();
      Workspace workspace = pc.getCurrentWorkspace();

      // Append container to graph structure
      String sample = "/org/gephi/desktop/welcome/samples/Les Miserables.gexf";
      final InputStream stream = WelcomeTopComponent.class.getResourceAsStream(sample);
      ImportController importController = Lookup.getDefault().lookup(ImportController.class);
      FileImporter fileImporter = importController.getFileImporter(".gexf");
      Container container = importController.importFile(stream, fileImporter);

      importController.process(container, new DefaultProcessor(), workspace);

      // Add self loop
      GraphController graphController = Lookup.getDefault().lookup(GraphController.class);
      Graph graph = graphController.getModel().getGraph();
      Node node = graph.getNode(12);
      System.out.println("Self loop " + node.getNodeData().getLabel());
      graph.addEdge(graphController.getModel().factory().newEdge(node, node, 31, true));

      // Set label edges
      for (Edge edge : graphController.getModel().getGraph().getEdges()) {
        edge.getEdgeData().setLabel("Label test");
      }

      // svg document

      // attribute ???
      AttributeController attributeController =
          Lookup.getDefault().lookup(AttributeController.class);
      AttributeModel attributeModel = null;

      // preview
      PreviewController previewController = Lookup.getDefault().lookup(PreviewController.class);
      PreviewModel previewModel = previewController.getModel(workspace);
      PreviewProperties previewProperties = previewModel.getProperties();
      previewController.refreshPreview(workspace);

      previewModel.getProperties().putValue("width", 1000);
      previewModel.getProperties().putValue("height", 1000);
      ProcessingTarget target =
          (ProcessingTarget)
              previewController.getRenderTarget(RenderTarget.PROCESSING_TARGET, workspace);

      previewProperties.putValue(LegendModel.LEGEND_PROPERTIES, new LegendModel(workspace));

      LegendModel legendManager = previewProperties.getValue(LegendModel.LEGEND_PROPERTIES);
      Integer itemIndex = legendManager.getCurrentIndex();

      // creating item
      Item item = addGroupsItem(itemIndex, graph, attributeModel);
      //            Item item = addTextItem(itemIndex, graph, attributeModel);

      // add item
      LegendController.getInstance().addItemToLegendModel(workspace, item);

      // render
      previewController.refreshPreview(workspace);
      previewController.render(target);

      File fileToSave = new File("/Volumes/edubecks/edubecks/Untitled.png");
      OutputStream fos = new FileOutputStream(fileToSave);
      Writer writer = new OutputStreamWriter(fos, "UTF-8");

      //            // saving
      //            int width = 1000;
      //            int height = 1000;
      //            PGraphicsJava2D pg2 = (PGraphicsJava2D) target.getGraphics();
      //            BufferedImage img = new BufferedImage(width, height,
      // BufferedImage.TYPE_INT_ARGB);
      //
      //            System.out.println("@Var: pg2.pixels: "+pg2.pixels);
      //            img.setRGB(0, 0, width, height, pg2.pixels, 0, width);
      //            ImageIO.write(img, "png", fileToSave);
      //            stream.close();

      PNGExporter pngExporter = new PNGExporter();
      //            pngExporter.setHeight(2000);
      //            pngExporter.setWidth(2000);
      pngExporter.setWorkspace(workspace);
      pngExporter.setOutputStream(fos);
      pngExporter.execute();

    } catch (Exception e) {
      Exceptions.printStackTrace(e);
    }
  }