Example #1
0
 private void loadConfigurations() {
   PlugInContext pc = context.createPlugInContext();
   for (Iterator i = configurations.iterator(); i.hasNext(); ) {
     Configuration configuration = (Configuration) i.next();
     monitor.report(LOADING + " " + name(configuration) + " " + version(configuration));
     long start = secondsSince(0);
     try {
       configuration.configure(pc);
       System.out.println(
           "Loading "
               + name(configuration)
               + " "
               + version(configuration)
               + " took "
               + secondsSinceString(start)
               + "s");
     } catch (Throwable e) {
       context.getErrorHandler().handleThrowable(e);
       context
           .getWorkbench()
           .getFrame()
           .log(configuration.getClass().getName() + " " + NOT_INITIALIZED, this.getClass());
     }
   }
 }
 public void run(TaskMonitor monitor, PlugInContext context) throws Exception {
   // -- get the LM because when the Histogram will be shown, the app. focus
   //   will change and context.addLayer will not work (null pointer exc.)
   // [mmichaud 2012-04-09] to completely resolve this problem, I added the
   // new JInternalFrame is added after the addLayer method has been called
   this.currentLM = context.getLayerManager();
   monitor.allowCancellationRequests();
   if (this.selAttribute == null) {
     context.getWorkbenchFrame().warnUser(I18N.get(sNoAttributeChoosen));
     return;
   }
   javax.swing.JInternalFrame internalFrame = context.getWorkbenchFrame().getActiveInternalFrame();
   FeatureDataset result = classifyAndCreatePlot(monitor, context);
   context.getWorkbenchFrame().activateFrame(internalFrame);
   if (result == null) {
     context.getWorkbenchFrame().warnUser(I18N.get(sNotEnoughValuesWarning));
   } else if (result.size() > 0) {
     String name = this.selAttribute + "_" + this.selClassifier;
     this.currentLM.addLayer(StandardCategoryNames.WORKING, name, result);
     JInternalFrame frame = new JInternalFrame(this.sHistogram);
     frame.setLayout(new BorderLayout());
     frame.add(plot, BorderLayout.CENTER);
     frame.setClosable(true);
     frame.setResizable(true);
     frame.setMaximizable(true);
     frame.setSize(450, 450);
     context.getWorkbenchFrame().addInternalFrame(frame);
     plot = null;
   } else {
     context.getWorkbenchFrame().warnUser(sWarning);
   }
 }
  public void run(TaskMonitor monitor, PlugInContext context) throws Exception {
    if (!saveDatasetDialog.wasOKPressed()) {
      return;
    }

    AbstractOutputDriver outputDriver = (AbstractOutputDriver) saveDatasetDialog.getCurrentDriver();
    monitor.report("Saving " + layer.getName() + "...");
    outputDriver.output(layer);
  }
  public static final void install(
      ExtensionManagerDialog extensionManager,
      WorkbenchContext workbenchContext,
      ExtensionWrapper ext,
      TaskMonitor monitor)
      throws Exception {

    PlugInManager manager = workbenchContext.getWorkbench().getPlugInManager();

    monitor.report(I18N.get("deejump.pluging.manager.ExtensionHelper.Downloading-resources"));

    File[] files =
        downloadAndSaveResources(
            extensionManager.getExtensionSite(), ext, manager.getPlugInDirectory());

    URLClassLoader classLoader = new URLClassLoader(toURLs(files));

    monitor.report(I18N.get("deejump.pluging.manager.ExtensionHelper.Loading-classes"));

    // list Extension and/or Configuration classes inside the zips/jars
    List extensionClasses = new ArrayList(10);
    for (int i = 0; i < files.length; i++) {
      extensionClasses.addAll(classes(new ZipFile(files[i]), classLoader));
    }

    List configs = new ArrayList();
    for (Iterator iter = extensionClasses.iterator(); iter.hasNext(); ) {
      Class c = (Class) iter.next();
      Configuration configuration = (Configuration) c.newInstance();
      configs.add(configuration);
    }

    monitor.report(I18N.get("deejump.pluging.manager.ExtensionHelper.Loading-extensions"));

    // finally, load configs/extensions
    // this method will call extension.configure(new PlugInContext(context, null, null,
    // null, null)); )
    loadConfigurations(configs, workbenchContext);
  }
  /*
   * Se ejecuta una vez finalizado el interfaz despues de pasar por todas las pantallas.
   * (non-Javadoc)
   * @see com.vividsolutions.jump.workbench.plugin.ThreadedPlugIn#run(com.vividsolutions.jump.task.TaskMonitor, com.vividsolutions.jump.workbench.plugin.PlugInContext)
   */
  public void run(TaskMonitor monitor, PlugInContext context) throws Exception {
    try {
      monitor.report(
          I18N.get(
              PluginMobileExtracti18n, MobilePluginI18NResource.MobileModifyPanel01_deletingProy));

      ExtractionProject eProject =
          (ExtractionProject) blackboard.get(MobileModifyPanel01.SELECTED_EXTRACT_PROJECT);

      // guardamos la informacion en base de datos
      final String sUrlPrefix =
          Constants.APLICACION.getString(UserPreferenceConstants.LOCALGIS_SERVER_URL);
      AdministradorCartografiaClient administradorCartografiaClient =
          new AdministradorCartografiaClient(
              sUrlPrefix
                  + WebAppConstants.GEOPISTA_WEBAPP_NAME
                  + ServletConstants.ADMINISTRADOR_CARTOGRAFIA_SERVLET_NAME);
      administradorCartografiaClient.deleteExtractProject(eProject);

      // Borramos los datos subidos al servidor.
      httpDeleteProject(Constants.URL_DELETE_SERVER, eProject);

      String dirBase =
          UserPreferenceStore.getUserPreference(
              UserPreferenceConstants.PREFERENCES_DATA_PATH_KEY,
              UserPreferenceConstants.DEFAULT_DATA_PATH,
              true);
      dirBase += File.separator + "maps";

      String projectName = eProject.getNombreProyecto();
      String idProyecto = eProject.getIdProyecto();

      String dirMapName = projectName + "." + idProyecto;
      File dirBaseMake = new File(dirBase, dirMapName);
      if (dirBaseMake.exists()) {
        MobileUtils.deleteDir(dirBaseMake);
        logger.info("Borrando fichero local:" + dirBaseMake);
      }

    } finally {
      // borramos la cuadrícula
      LayerManager layerManager = context.getLayerManager();
      Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
      if (graticuleLayer != null) {
        layerManager.remove(graticuleLayer);
      }
    }
  }
  public static final void remove(List fileList, ExtensionWrapper ext, TaskMonitor monitor)
      throws Exception {
    List resourceList = ext.getResourceList();

    for (Iterator iter = fileList.iterator(); iter.hasNext(); ) {
      File file = (File) iter.next();
      if (file.isFile()) {

        if (resourceList.contains(file.getName())) {
          //                    System.out.println("will delete: " + file);

          monitor.report(
              I18N.get("deejump.pluging.manager.ExtensionHelper.Deleting-file") + " " + file);

          boolean deleted = false;

          try {
            deleted = file.delete();
          } catch (SecurityException e) {
            // TODO decide if re-throw here or handle or log??
            e.printStackTrace();
          }

          // TODO throw exc if false.

          // hmm no exception thrown?
          // file permissions?
          // bye bye
          System.out.println(
              I18N.get("deejump.pluging.manager.ExtensionHelper.deleted")
                  + " '"
                  + file
                  + "': "
                  + deleted);
          // ???? above hasn't worked, file locked? del on exited didn'T work...
          // put file on a list and finish it off?
          // inlcude in a plug-in, listener --> workbench.isclosed -> del file!
          //                     file.deleteOnExit();

        }
      }
    }
  }
Example #7
0
  private Collection findConfigurations(File plugInDirectory) throws Exception {
    ArrayList configurations = new ArrayList();
    long start;
    for (Iterator i = findFilesRecursively(plugInDirectory, false).iterator(); i.hasNext(); ) {
      start = secondsSince(0);
      File file = (File) i.next();
      String msg =
          I18N.getMessage(
              "com.vividsolutions.jump.workbench.plugin.PlugInManager.scan",
              new String[] {file.getName()});
      monitor.report(msg);
      try {
        configurations.addAll(findConfigurations(classes(new ZipFile(file), classLoader)));
      } catch (ZipException e) {
        // Might not be a zipfile. Eat it. [Jon Aquino]
      }
      System.out.println("Scanning " + file + " took " + secondsSinceString(start) + "s");
    }

    return configurations;
  }
Example #8
0
  private void loadPlugIns(WorkbenchProperties props) {
    PlugInContext pc = context.createPlugInContext();
    // List<String> classNames = props.getPlugInClassNames();
    Map<String, Map<String, String>> pluginSettings =
        props.getSettings(new String[] {WorkbenchProperties.KEY_PLUGIN});
    int i = 0;
    for (String className : pluginSettings.keySet()) {
      //        System.out.println(i++ + "/"+ className);
      String initSetting = pluginSettings.get(className).get(WorkbenchProperties.ATTR_INITIALIZE);
      if (initSetting instanceof String && initSetting.equals(WorkbenchProperties.ATTR_VALUE_FALSE))
        continue;

      monitor.report(LOADING + " " + className);

      Class plugInClass = null;
      try {
        long start = secondsSince(0);
        plugInClass = Class.forName(className);
        PlugIn plugIn = (PlugIn) plugInClass.newInstance();
        plugIn.initialize(pc);

        // get plugin's menu settings
        Map<String, Map> menuSettings =
            props.getSettings(
                new String[] {
                  WorkbenchProperties.KEY_PLUGIN, className, WorkbenchProperties.KEY_MENUS
                });

        // interpret menu settings
        for (Map.Entry<String, Map> entry : menuSettings.entrySet()) {

          String menuKey = entry.getKey();
          if (pc.getFeatureInstaller().fetchMenuForKey(menuKey) == null) continue;

          // install me to menu?
          String installSetting =
              props.getSetting(
                  new String[] {
                    WorkbenchProperties.KEY_PLUGIN,
                    className,
                    WorkbenchProperties.KEY_MENUS,
                    menuKey,
                    WorkbenchProperties.ATTR_INSTALL
                  });
          //            String orderSetting = props.getSetting(new String[] {
          //                WorkbenchProperties.KEY_PLUGIN, className,
          //                WorkbenchProperties.KEY_MENUS,
          //                menuKey,
          //                WorkbenchProperties.ATTR_ORDERID});
          // log (order) info
          //            context
          //                .getWorkbench()
          //                .getFrame()
          //                .log(
          //                    "install " + className + " to " + menuKey + " = "
          //                        + installSetting + " with orderid = " + orderSetting);
          // install, or not
          if (installSetting.equals(WorkbenchProperties.ATTR_VALUE_TRUE))
            pc.getFeatureInstaller().addMenuPlugin(menuKey, plugIn);
        }

        // register shortcuts of plugins
        AbstractPlugIn.registerShortcuts(plugIn);

        context
            .getWorkbench()
            .getFrame()
            .log("Loading " + className + " took " + secondsSinceString(start) + "s");

      } catch (Throwable e) {
        context.getErrorHandler().handleThrowable(e);
        context.getWorkbench().getFrame().log(className + " " + NOT_INITIALIZED, this.getClass());
      }
    }
  }
  /**
   * @param context
   * @throws IOException
   */
  private void saveTrafficRegulationInformation(PlugInContext context, TaskMonitor monitor)
      throws IOException {

    String netName = "";
    if (getSelectedLayer().getSystemId().startsWith("Arcos-")) {
      String[] a = getSelectedLayer().getSystemId().split("-");
      netName = a[1];
      System.out.println(a.length);
      for (int i = 2; i < a.length; i++) {
        netName = netName + "-" + a[i];
      }
    } else {
      netName = getSelectedLayer().getSystemId();
    }

    ArrayList<GeopistaFeature> listaFeatures = this.getSelectedsArrayListStreetFeature();
    ArrayList<Integer> listaEdgeIds = this.getSelectedsArrayListEdgesIds();

    for (int i = 0; i < listaFeatures.size(); i++) {

      monitor.report("Modificando Direccion tramo " + i + " de " + listaEdgeIds.size());

      Edge selectedEdge = searchEdgeByIdAndNetworkName(context, netName, listaEdgeIds.get(i));

      if (selectedEdge instanceof LocalGISStreetDynamicEdge) {
        // Se actualiza el StreetEdge
        ((LocalGISStreetDynamicEdge) selectedEdge).setTrafficRegulation(getTrafficRegualtion());

        RouteArrowLineStyle line =
            new RouteArrowLineStyle.BiDirect(
                (Viewport) context.getLayerViewPanel().getViewport(),
                (Graphics2D) ((LayerViewPanel) context.getLayerViewPanel()).getGraphics());
        if (this.getSelectedLayer().getStyle(RouteArrowLineStyle.class) != null) {
          getSelectedLayer().removeStyle(getSelectedLayer().getStyle(RouteArrowLineStyle.class));
        }
        getSelectedLayer().addStyle(line);

        GeopistaFeature feat = listaFeatures.get(i);

        if (feat != null) {
          // se actualiza el valor de la feature
          feat.setAttribute(
              I18N.get(
                  "regulacionTrafico",
                  "routeengine.trafficregulation.trafficregulationattributename"),
              getTrafficRegualtion().toString());
          //					this.paintBidirectTrafiicRegulation(getTrafficRegualtion());

          if (feat.getSchema().hasAttribute("pintadaRegulacionTrafico")
              && feat.getAttribute("pintadaRegulacionTrafico") != null
              && feat.getAttribute("pintadaRegulacionTrafico") instanceof Integer) {
            try {
              feat.setAttribute("pintadaRegulacionTrafico", 1);
            } catch (Exception e) {
            }
          }
        }

        context.getLayerViewPanel().repaint();
      }
      NetworkManager nManager = NetworkModuleUtilWorkbench.getNetworkManager(context);
      Network actualNetwork = nManager.getNetwork(netName);

      // intentamos insercion en la base de datos de la velocidad de la v�a
      Category categoryLayer = context.getLayerManager().getCategory(getSelectedLayer());
      if (!categoryLayer.getName().equals("")) {
        if (actualNetwork.getGraph() instanceof DynamicGraph
            && ((DynamicGraph) actualNetwork.getGraph()).getMemoryManager()
                instanceof SpatialAllInMemoryExternalSourceMemoryManager) {
          RouteConnectionFactory routeConnection = new GeopistaRouteConnectionFactoryImpl();
          LocalGISNetworkDAO lnDAO = new LocalGISNetworkDAO();
          Connection connection = null;
          try {
            connection = routeConnection.getConnection();
            lnDAO.updateStreetData(netName, (LocalGISStreetDynamicEdge) selectedEdge, connection);
          } catch (SQLException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            ConnectionUtilities.closeConnection(connection);
          }
        }
      }
    }
  }
  private FeatureDataset classifyAndCreatePlot(TaskMonitor monitor, final PlugInContext context)
      throws Exception {

    monitor.report(this.sCalculateBreaks);
    // =============== get DATA and prepare ==============/
    FeatureSchema fs = this.fc.getFeatureSchema();
    AttributeType type = null;
    if ((fs.getAttributeType(this.selAttribute) == AttributeType.DOUBLE)
        || (fs.getAttributeType(this.selAttribute) == AttributeType.INTEGER)) {
      // -- move on
      type = fs.getAttributeType(this.selAttribute);
    } else {
      // System.out.println("ClassifyAttributesPlugIn: wrong datatype of chosen attribute");
      context.getWorkbenchFrame().warnUser(sWrongDataType);
      return null;
    }

    int size = getFeatureCollectionSize(this.fc, this.selAttribute, this.nullAsZero);
    if (size < 3) {
      return null;
    }
    this.ranges = Math.min(this.ranges, size);

    double[] data = new double[size];
    double[][] plotdata = new double[2][size]; // for drawing 1-D scatter plot
    int[] fID = new int[size];
    int i = 0;
    for (Iterator iter = fc.iterator(); iter.hasNext(); ) {
      Feature f = (Feature) iter.next();
      if (f.getAttribute(this.selAttribute) == null && !nullAsZero) continue;
      fID[i] = f.getID();
      plotdata[1][i] = 1;
      Object val = f.getAttribute(this.selAttribute);
      if (type == AttributeType.DOUBLE) {
        if (val == null) data[i] = 0.0;
        else data[i] = ((Double) val).doubleValue();
      } else if (type == AttributeType.INTEGER) {
        if (val == null) data[i] = 0;
        else data[i] = ((Integer) val).intValue();
      }
      plotdata[0][i] = data[i];
      i++;
    }
    /*
    //-- some testdata
    double[][] plotdata2 = new double[2][8];
    double[] data2 = { -2, 4, 6, 5, 0, 10, 7, 1 };
    double[] axis2 =  {  1, 1, 1, 1, 1, 1, 1, 1 };
    plotdata2[0] = data2;
    plotdata2[1] = axis2;
    */

    if (monitor.isCancelRequested()) {
      return null;
    }

    // =============== find breaks according to chosen method ==============/
    double[] limits = null;

    if (this.useKmeans == false) {
      if (this.selClassifier == Classifier1D.EQUAL_NUMBER) {
        limits = Classifier1D.classifyEqualNumber(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.EQUAL_RANGE) {
        limits = Classifier1D.classifyEqualRange(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.MEAN_STDEV) {
        limits = Classifier1D.classifyMeanStandardDeviation(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.MAX_BREAKS) {
        limits = Classifier1D.classifyMaxBreaks(data, this.ranges);
      } else if (this.selClassifier == Classifier1D.JENKS_BREAKS) {
        limits = Classifier1D.classifyNaturalBreaks(data, this.ranges);
      }
    } else {
      if (this.selClassifier == Classifier1D.EQUAL_NUMBER) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 3);
      } else if (this.selClassifier == Classifier1D.EQUAL_RANGE) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 2);
      } else if (this.selClassifier == Classifier1D.MEAN_STDEV) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 4);
      } else if (this.selClassifier == Classifier1D.MAX_BREAKS) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 1);
      } else if (this.selClassifier == Classifier1D.JENKS_BREAKS) {
        limits = Classifier1D.classifyKMeansOnExistingBreaks(data, this.ranges, 5);
      }
    }

    if (monitor.isCancelRequested()) {
      return null;
    }

    monitor.report(this.sDisplayBreaks);
    // =============== plot data and class breaks ==============/
    // -- do display here - in case we later want to allow interactive editing of the limits

    // -- reformat limits
    double[][] limits2show = new double[2][limits.length];
    // -- due to bug in jmathplot add limits twice if only three classes = 2breaks are sought
    if (limits.length == 2) {
      limits2show = new double[2][limits.length * 2];
    }
    for (int j = 0; j < limits.length; j++) {
      limits2show[0][j] = limits[j]; // x-axis
      limits2show[1][j] =
          Math.floor(
              i / (4.0 * this.ranges)); // y-axis, estimate height of "bar" from number of items
      // limits2show[1][j]= 1;
      // -- due to bug in jmathplot add limits twice if only three classes are sought
      if (limits.length == 2) {
        limits2show[0][limits.length + j] = limits[j];
        limits2show[1][limits.length + j] = Math.floor(i / (4.0 * this.ranges));
      }
    }

    // =============== plot data and class breaks ==============/
    // -- create plots
    /*final Plot2DPanelOJ*/ plot = new Plot2DPanelOJ();
    plot.addHistogramPlotOJ(
        this.selAttribute, data, this.ranges * 3, context, selLayer, this.selAttribute);
    plot.addScatterPlotOJ(this.sDatapoints, plotdata, fID, context, this.selLayer);
    plot.addBarPlot(this.sClassbreaks, limits2show);
    plot.plotToolBar.setVisible(true);
    plot.setAxisLabel(0, this.selAttribute);
    plot.setAxisLabel(1, this.sCount);
    plot.addLegend("SOUTH");

    // [mmichaud 2012-04-09] Moved in run method after the addLayer method
    // to avoid the problem of the focus change

    // JInternalFrame frame = new JInternalFrame(this.sHistogram);
    // frame.setLayout(new BorderLayout());
    // frame.add(plot, BorderLayout.CENTER);
    // frame.setClosable(true);
    // frame.setResizable(true);
    // frame.setMaximizable(true);
    // frame.setSize(450, 450);
    // frame.setVisible(true);

    // context.getWorkbenchFrame().addInternalFrame(frame);

    // =============== classify data ==============/
    if (monitor.isCancelRequested()) {
      return null;
    }
    monitor.report(this.sClassifying);
    int[] classes = Classifier1D.classifyData(data, limits);
    // double[] classes = org.math.array.StatisticSample.one(data.length);
    // context.getWorkbenchFrame().warnUser("classification not yet implemented");

    // =============== add field ==============/
    if (monitor.isCancelRequested()) {
      return null;
    }
    monitor.report(sAddingField);

    FeatureDataset fd = null;
    ArrayList outData = new ArrayList();
    FeatureSchema targetFSnew = null;
    int count = 0;
    Iterator iterp = fc.iterator();
    String attname = this.selAttribute + "_" + this.selClassifier;
    while (iterp.hasNext()) {
      // count=count+1;
      //	    	if(monitor != null){
      //	    	    monitor.report("item: " + count + " of " + size);
      //	    	}
      Feature p = (Feature) iterp.next();
      Object val = p.getAttribute(this.selAttribute);
      if (val == null && !this.nullAsZero) continue;
      else count++;
      if (count == 1) {
        FeatureSchema targetFs = p.getSchema();
        targetFSnew = FeatureSchemaTools.copyFeatureSchema(targetFs);
        if (targetFSnew.hasAttribute(attname)) {
          // attribute will be overwriten
        } else {
          // add attribute
          targetFSnew.addAttribute(attname, AttributeType.INTEGER);
        }
      }
      // -- evaluate value for every polygon
      Feature fcopy = FeatureSchemaTools.copyFeature(p, targetFSnew);
      // fcopy.setAttribute(this.selClassifier, new Integer(classes[count-1]));
      fcopy.setAttribute(attname, new Integer(classes[count - 1]));
      outData.add(fcopy);
    }
    fd = new FeatureDataset(targetFSnew);
    fd.addAll(outData);
    return fd;
  }