public void testTwoPlatformsoverSameSDK() throws Exception {
    final File binDir = new File(getWorkDir(), "boot"); // NOI18N
    binDir.mkdir();
    final File jdocFile1 = new File(getWorkDir(), "jdoc1"); // NOI18N
    jdocFile1.mkdir();
    final File jdocFile2 = new File(getWorkDir(), "jdoc2"); // NOI18N
    jdocFile2.mkdir();
    JavaPlatformProviderImpl provider = Lookup.getDefault().lookup(JavaPlatformProviderImpl.class);
    final URL binRoot = Utilities.toURI(binDir).toURL();
    final ClassPath bootCp = ClassPathSupport.createClassPath(binRoot);
    final List<URL> javadoc1 = Collections.singletonList(Utilities.toURI(jdocFile1).toURL());
    final List<URL> javadoc2 = Collections.singletonList(Utilities.toURI(jdocFile2).toURL());
    final TestJavaPlatform platform1 = new TestJavaPlatform("platform1", bootCp); // NOI18N
    final TestJavaPlatform platform2 = new TestJavaPlatform("platform2", bootCp); // NOI18N
    platform2.setJavadoc(javadoc2);
    provider.addPlatform(platform1);
    provider.addPlatform(platform2);

    final JavadocForBinaryQuery.Result result1 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));

    platform1.setJavadoc(javadoc1);
    assertEquals(javadoc1, Arrays.asList(result1.getRoots()));

    final JavadocForBinaryQuery.Result result2 = JavadocForBinaryQuery.findJavadoc(binRoot);
    assertEquals(javadoc1, Arrays.asList(result2.getRoots()));

    platform1.setJavadoc(Collections.<URL>emptyList());
    assertEquals(javadoc2, Arrays.asList(result1.getRoots()));
    assertEquals(javadoc2, Arrays.asList(result2.getRoots()));
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  // End of variables declaration//GEN-END:variables
  @Override
  public void componentOpened() {
    // Register to the global context and declare your interest
    devices = Utilities.actionsGlobalContext().lookupResult(BrickletRotaryPoti.class);

    devices.addLookupListener(this);
  }
Exemplo n.º 3
0
 public boolean getForceStop() {
   if (Utilities.isWindows()) {
     return false;
   }
   String val = ip.getProperty(PROP_FORCE_STOP);
   return val != null ? Boolean.valueOf(val).booleanValue() : DEF_VALUE_FORCE_STOP;
 }
Exemplo n.º 4
0
  /**
   * Provides a special handling for renaming of serialized classes.
   *
   * <p>Often, as the time goes the serialized classes evolve. They can be moved to new packages,
   * renamed or changed (by a mistake) to not reflect the version of class stored in previous
   * sessions.
   *
   * <p>This method deals with some of this incompatibilites and provides the module owners a way
   * how to fix some of them.
   *
   * <p>When a class is read, the <link>Utilities.translate</link> is consulted to find out what
   * whether the name of the class is listed there and what new value is assigned to it. This allows
   * complete rename of the serialized class. For example: <code>org.netbeans.core.NbMainExplorer
   * </code> can be renamed to <code>org.netbeans.core.ui.NbExp</code> - of course supposing that
   * the new class is able to read the serialized fields of the old one.
   *
   * <p>Another useful feature of this method is the ability to supress wrong <code>serialVersionUID
   * </code>. This was causing us a lot of problems, because people were forgetting to specify the
   * <code>serialVersionUID</code> field in their sources and then it was hard to recover from it.
   * Right now we have a solution: Just use <link>Utilities.translate</link> framework to assing
   * your class <code>org.yourpackage.YourClass</code> the same name as it had e.g. <code>
   * org.yourpackage.YourClass</code>. This will be interpreted by this method as a hit to suppress
   * <code>serialVersionUID</code> and the <code>NbObjectInputStream</code> will ignore its value.
   *
   * <p>Please see <link>Utilities.translate</link> to learn how your module can provide list of
   * classes that changed name or want to suppress <code>serialVersionUID</code>.
   */
  protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
    ObjectStreamClass ose = super.readClassDescriptor();

    String name = ose.getName();
    String newN = Utilities.translate(name);

    if (name == newN) {
      // no translation
      return ose;
    }

    // otherwise reload the ObjectStreamClass to contain the local copy

    ClassLoader cl = getNBClassLoader();
    Class clazz = Class.forName(newN, false, cl);

    ObjectStreamClass newOse = ObjectStreamClass.lookup(clazz);

    // #28021 - it is possible that lookup return null. In that case the conversion
    // table contains class which is not Serializable or Externalizable.
    if (newOse == null) {
      throw new java.io.NotSerializableException(newN);
    }

    return newOse;
  }
 private File getBaseDir() throws Exception {
   File dir = getWorkDir();
   if (Utilities.isWindows()) {
     dir = new File(dir.getCanonicalPath());
   }
   return dir;
 }
  @Override
  public void actionPerformed(PhpModule phpModule) {
    // Check CakePHP project
    if (!CakePhpUtils.isCakePHP(phpModule)) {
      return;
    }

    // get EditorCookie
    Lookup lookup = Utilities.actionsGlobalContext();
    EditorCookie context = lookup.lookup(EditorCookie.class);
    if (context == null) {
      return;
    }

    Document doc = context.getDocument();
    if (doc == null) {
      return;
    }

    reformat(doc);

    // Change line feed
    if (!BaseDocument.LS_LF.equals(doc.getProperty(BaseDocument.READ_LINE_SEPARATOR_PROP))) {
      doc.putProperty(BaseDocument.READ_LINE_SEPARATOR_PROP, BaseDocument.LS_LF);
    }
  }
Exemplo n.º 7
0
  /**
   * Get the mnemonic for a keystroke.
   *
   * @param key a keystroke
   * @return mnemonic of tghe keystroke.
   */
  private static String getKeyMnemonic(KeyStroke key) {
    String sk = org.openide.util.Utilities.keyToString(key);
    StringBuffer sb = new StringBuffer();
    int mods = key.getModifiers();
    if ((mods & KeyEvent.CTRL_MASK) != 0) {
      sb.append("Ctrl+"); // NOI18N
    }
    if ((mods & KeyEvent.ALT_MASK) != 0) {
      sb.append("Alt+"); // NOI18N
    }
    if ((mods & KeyEvent.SHIFT_MASK) != 0) {
      sb.append("Shift+"); // NOI18N
    }
    if ((mods & KeyEvent.META_MASK) != 0) {
      sb.append("Meta+"); // NOI18N
    }

    int i = sk.indexOf('-'); // NOI18N
    if (i != -1) {
      sk = sk.substring(i + 1);
    }
    sb.append(sk);

    return sb.toString();
  }
 @Override
 public void panelActivated(Lookup lkp) {
   Logger.getLogger(OscillogramNavigatorPanel.class.getName()).log(Level.INFO, "pa");
   this.result = Utilities.actionsGlobalContext().lookupResult(ChannelList.class);
   this.result.addLookupListener(this);
   ExplorerUtils.activateActions(manager, true);
   resultChanged(new LookupEvent(result));
 }
Exemplo n.º 9
0
 @Override
 public Image getIcon(final int type) {
   if ((type == BeanInfo.ICON_COLOR_16x16) || (type == BeanInfo.ICON_MONO_16x16)) {
     return Utilities.loadImage("de/cismet/jpresso/project/res/today.png");
   } else {
     return null;
   }
 }
  public PropertiesViewTopComponent() {
    initComponents();
    setName(Bundle.CTL_PropertiesViewTopComponent());
    setToolTipText(Bundle.HINT_PropertiesViewTopComponent());

    global = Utilities.actionsGlobalContext().lookupResult(IEntityWrapper.class);
    global.addLookupListener(listener);
  }
Exemplo n.º 11
0
 public String getDebugType() {
   String val = ip.getProperty(PROP_DEBUG_TYPE);
   if ((DEBUG_TYPE_SHARED.equalsIgnoreCase(val) && Utilities.isWindows())
       || DEBUG_TYPE_SOCKET.equalsIgnoreCase(val)) {
     return val;
   }
   return DEF_VALUE_DEBUG_TYPE;
 }
Exemplo n.º 12
0
 public @Override boolean isNameCompatible(String simplename, JavaFileObject.Kind kind) {
   boolean res = super.isNameCompatible(simplename, kind);
   if (res) {
     return res;
   } else if (Utilities.isWindows()) {
     return nameWithoutExt.equalsIgnoreCase(simplename);
   } else {
     return false;
   }
 }
Exemplo n.º 13
0
 @Override
 public void open() {
   IPlate96 plate = Utilities.actionsGlobalContext().lookup(IPlate96.class);
   if (plate != null) {
     Lookup.getDefault()
         .lookup(IRegistryFactory.class)
         .getDefault()
         .openTopComponentFor(plate, Plate96ViewerTopComponent.class);
   }
 }
Exemplo n.º 14
0
 private void initFields(String path) {
   // Set default values
   if (path == null) {
     initComboBox(""); // NOI18N
   } else {
     if (Utilities.isWindows()) {
       path = path.replace('/', File.separatorChar);
     }
     initComboBox(path);
   }
 }
Exemplo n.º 15
0
  @NbBundle.Messages({"# {0} - tag name", "ERR_invalidPropertyName=Invalid property name: {0}"})
  private FxNode handlePropertyTag(String propName, Attributes atts) {
    PropertyValue pv;

    int errorAttrs = 0;
    for (int i = 0; i < atts.getLength(); i++) {
      String uri = atts.getURI(i);
      if (uri != null) {
        String qn = atts.getQName(i);
        errorAttrs++;
        addAttributeError(
            qn, "property-namespaced-attribute", ERR_propertyElementNamespacedAttribute(qn), qn);
      }
    }

    int stProp = FxXmlSymbols.findStaticProperty(propName);
    switch (stProp) {
      case -1:
        // simple property
        if (!Utilities.isJavaIdentifier(propName)) {
          addError(
              new ErrorMark(
                  start,
                  end,
                  "invalid-property-name",
                  ERR_invalidPropertyName(propName),
                  propName));
        }
        if (errorAttrs == atts.getLength()) {
          pv = handleSimpleProperty(propName, atts);
        } else {
          pv = handleMapProperty(propName, atts);
        }
        break;

      case -2:
        // broken name, but must create a node
        pv = accessor.makeBroken(accessor.createProperty(propName, false));
        // do not add the property to the parent, it's broken beyond repair
        addError(
            new ErrorMark(
                start, end, "invalid-property-name", ERR_invalidPropertyName(propName), propName));
        break;

      default:
        // static property, just ignore for now
        pv =
            handleStaticProperty(
                propName.substring(0, stProp), propName.substring(stProp + 1), atts);
        break;
    }

    return pv;
  }
 private void invokeSelected() {
   PopupUtil.hidePopup();
   if (Utilities.isMac()) {
     // see issue #115106
     component.requestFocus();
   }
   Object value = jList1.getSelectedValue();
   if (value instanceof CodeDeleter) {
     ((CodeDeleter) value).invoke();
   }
 }
Exemplo n.º 17
0
    private void registerFonts() {
      FontFactory.registerDirectories();
      if (Utilities.isMac()) {
        // Add user fonts folder
        String userFonts = "/" + System.getProperty("user.home") + "/Library/Fonts";
        FontFactory.registerDirectory(userFonts);

        // Adobe font folder
        String adobeFonts = "/Library/Application Support/Adobe/Fonts";
        FontFactory.registerDirectory(adobeFonts);
      }
    }
  public void testQuery() throws Exception {
    JavaPlatform platform = JavaPlatform.getDefault();
    ClassPath cp = platform.getBootstrapLibraries();
    FileObject pfo = cp.getRoots()[0];
    URL u = URLMapper.findURL(pfo, URLMapper.EXTERNAL);
    URL urls[] = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertTrue(urls[0].toString(), urls[0].toString().startsWith("http://download.oracle.com/"));

    List<URL> l = new ArrayList<URL>();
    File javadocFile = getBaseDir();
    File api = new File(javadocFile, "api");
    File index = new File(api, "index-files");
    FileUtil.toFileObject(index);
    index.mkdirs();
    l.add(Utilities.toURI(javadocFile).toURL());
    J2SEPlatformImpl platformImpl = (J2SEPlatformImpl) platform;
    platformImpl.setJavadocFolders(l);
    urls = JavadocForBinaryQuery.findJavadoc(u).getRoots();
    assertEquals(1, urls.length);
    assertEquals(Utilities.toURI(api).toURL(), urls[0]);
  }
Exemplo n.º 19
0
 private void writeCatalog() throws IOException {
   String res =
       "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
           + "<!DOCTYPE module_updates PUBLIC \"-//NetBeans//DTD Autoupdate Catalog 2.5//EN\" \"http://www.netbeans.org/dtds/autoupdate-catalog-2_5.dtd\">"
           + "<module_updates timestamp=\"00/00/19/08/03/2006\">\n";
   for (String element : moduleElements) {
     res += element;
   }
   res += "</module_updates>\n";
   if (catalogFile == null) {
     catalogFile = File.createTempFile("catalog-", ".xml", tmpDirectory);
     catalogURL = Utilities.toURI(catalogFile).toURL();
   }
   PrintWriter pw =
       new PrintWriter(new OutputStreamWriter(new FileOutputStream(catalogFile), "UTF-8"));
   pw.write(res);
   pw.close();
 }
  /**
   * Test of getSharability method, of class
   * org.netbeans.modules.masterfs.GlobalSharabilityQueryImpl.
   */
  public void testGetSharability() {
    File[] all =
        new File[] {
          new File("/myroot/mydirectory/myfile.java"),
          new File("/myroot/mydirectory/myfile.class"),
          new File("/myroot/mydirectory/myfile.xml"),
          new File("/myroot/mydirectory/.cvsignore"),
          new File("/myroot/mydirectory/CVS"),
          new File("/myroot/mydirectory/.DS_Store"),
          new File("/myroot/mydirectory/.svn"),
          new File("/myroot/mydirectory/_svn")
        };

    for (int i = 0; i < all.length; i++) {
      boolean isNotSharable =
          sq.getSharability(Utilities.toURI(all[i])) == SharabilityQuery.Sharability.NOT_SHARABLE;
      boolean isNotVisible = !vq.isVisible(all[i].getName());
      assertEquals(isNotSharable, isNotVisible);
    }
  }
Exemplo n.º 21
0
  public MeasureAction() {

    setEnabled(context != null);
    Lookup lkp = Utilities.actionsGlobalContext();

    result = lkp.lookupResult(MeasurableCookie.class);
    result.addLookupListener(
        new LookupListener() {

          @Override
          public void resultChanged(LookupEvent ev) {
            Collection<? extends MeasurableCookie> c = result.allInstances();
            if (!c.isEmpty()) {
              context = c.iterator().next();
            } else {
              context = null;
            }
            setEnabled(context != null);
          }
        });
  }
Exemplo n.º 22
0
 /** Transform message to the form that can be used on a command line. */
 public static String msg2CmdlineStr(String msg, boolean unixShell) {
   if (msg == null) return "";
   String cmd = org.openide.util.Utilities.replaceString(msg, "\\", "\\\\"); // put \\ instead of \
   if (unixShell)
     cmd =
         org.openide.util.Utilities.replaceString(
             cmd, "\"", "\\\\\\\"\\\\\\\""); // put \\\" instead of "
   else
     cmd =
         org.openide.util.Utilities.replaceString(cmd, "\"", "\\\\\\\""); // put \\\" instead of "
   if (org.openide.util.Utilities.isUnix() || unixShell) {
     cmd = org.openide.util.Utilities.replaceString(cmd, "$", "\\$"); // put \$ instead of $
     // cmd = org.openide.util.Utilities.replaceString(cmd, "!", "\\!"); // put \! instead of !
     cmd = org.openide.util.Utilities.replaceString(cmd, "`", "\\`"); // put \` instead of `
   }
   return cmd;
 }
Exemplo n.º 23
0
 /**
  * Fixes sun.boot.class.path property if it contains resolved symbolic link. On Suse the jdk is
  * symlinked and during update the link is changed
  */
 private String fixSymLinks(String key, String value) {
   if (Utilities.isUnix() && propertiesToFix.contains(key)) {
     try {
       String[] pathElements = value.split(File.pathSeparator);
       boolean changed = false;
       for (Iterator it = this.getInstallFolders().iterator(); it.hasNext(); ) {
         File f = FileUtil.toFile((FileObject) it.next());
         if (f != null) {
           String path = f.getAbsolutePath();
           String canonicalPath = f.getCanonicalPath();
           if (!path.equals(canonicalPath)) {
             for (int i = 0; i < pathElements.length; i++) {
               if (pathElements[i].startsWith(canonicalPath)) {
                 pathElements[i] = path + pathElements[i].substring(canonicalPath.length());
                 changed = true;
               }
             }
           }
         }
       }
       if (changed) {
         StringBuffer sb = new StringBuffer();
         for (int i = 0; i < pathElements.length; i++) {
           if (i > 0) {
             sb.append(File.pathSeparatorChar);
           }
           sb.append(pathElements[i]);
         }
         return sb.toString();
       }
     } catch (IOException ioe) {
       // Return the original value
     }
   }
   return value;
 }
Exemplo n.º 24
0
 public void testFileOwner() throws Exception {
   assertEquals("correct project from projfile FileObject", p, FileOwnerQuery.getOwner(projfile));
   URI u = Utilities.toURI(FileUtil.toFile(projfile));
   assertEquals("correct project from projfile URI " + u, p, FileOwnerQuery.getOwner(u));
   assertEquals(
       "correct project from projfile2 FileObject", p, FileOwnerQuery.getOwner(projfile2));
   assertEquals(
       "correct project from projfile2 URI",
       p,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projfile2))));
   assertEquals("correct project from projdir FileObject", p, FileOwnerQuery.getOwner(projdir));
   assertEquals(
       "correct project from projdir URI",
       p,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(projdir))));
   // Check that it loads the project even though we have not touched it yet:
   Project p2 = FileOwnerQuery.getOwner(subprojfile);
   Project subproj = ProjectManager.getDefault().findProject(subprojdir);
   assertEquals("correct project from subprojdir FileObject", subproj, p2);
   assertEquals(
       "correct project from subprojdir URI",
       subproj,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojdir))));
   assertEquals(
       "correct project from subprojfile FileObject",
       subproj,
       FileOwnerQuery.getOwner(subprojfile));
   assertEquals(
       "correct project from subprojfile URI",
       subproj,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(subprojfile))));
   assertEquals(
       "no project from randomfile FileObject", null, FileOwnerQuery.getOwner(randomfile));
   assertEquals(
       "no project from randomfile URI",
       null,
       FileOwnerQuery.getOwner(Utilities.toURI(FileUtil.toFile(randomfile))));
   assertEquals("no project in C:\\", null, FileOwnerQuery.getOwner(URI.create("file:/C:/")));
 }
 // Variables declaration - do not modify//GEN-BEGIN:variables
 // End of variables declaration//GEN-END:variables
 @Override
 public void componentOpened() {
   result = Utilities.actionsGlobalContext().lookupResult(Clustering.class);
   result.addLookupListener(this);
 }
Exemplo n.º 26
0
  private File prepareNBM(
      String codeName,
      String releaseVersion,
      String implVersion,
      String specVersion,
      boolean visible,
      String dependency)
      throws Exception {
    String moduleName = codeName.substring(codeName.lastIndexOf(".") + 1);
    String moduleFile = codeName.replace(".", "-");
    String moduleDir = codeName.replace(".", "/") + "/";
    File nbm = File.createTempFile(moduleFile + "-", ".nbm", tmpDirectory);

    final String MODULE_NAME_PROP = "OpenIDE-Module-Name";

    File jar = new File(tmpDirectory, "x.jar");
    jar.getParentFile().mkdirs();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar));
    int idx = moduleDir.indexOf("/");
    while (idx != -1) {
      jos.putNextEntry(new ZipEntry(moduleDir.substring(0, idx + 1)));
      idx = moduleDir.indexOf("/", idx + 1);
    }

    jos.putNextEntry(new ZipEntry(moduleDir + "Bundle.properties"));
    jos.write(new String(MODULE_NAME_PROP + "=" + moduleName).getBytes("UTF-8"));
    jos.putNextEntry(new ZipEntry("META-INF/"));
    jos.putNextEntry(new ZipEntry("META-INF/manifest.mf"));
    jos.write(
        getManifest(
                codeName, releaseVersion, implVersion, moduleDir, specVersion, visible, dependency)
            .getBytes("UTF-8"));
    jos.close();
    File ext = new File(jar.getParentFile(), jar.getName() + ".external");
    FileOutputStream os = new FileOutputStream(ext);
    os.write(("CRC: " + UpdateTracking.getFileCRC(jar) + "\n").getBytes());
    os.write(("URL: " + Utilities.toURI(jar).toString() + "\n").getBytes());
    os.close();

    Manifest mf = new Manifest();
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

    jos = new JarOutputStream(new FileOutputStream(nbm), mf);
    jos.putNextEntry(new ZipEntry("Info/"));
    jos.putNextEntry(new ZipEntry("Info/info.xml"));
    jos.write(
        createInfoXML(
                visible,
                codeName,
                releaseVersion,
                implVersion,
                moduleName,
                Utilities.toURI(nbm).toURL().toString(),
                specVersion,
                dependency)
            .getBytes("UTF-8"));

    jos.putNextEntry(new ZipEntry("netbeans/"));
    jos.putNextEntry(new ZipEntry("netbeans/modules/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/Modules/"));
    jos.putNextEntry(new ZipEntry("netbeans/config/Modules/" + moduleFile + ".xml"));

    jos.write(getConfigXML(codeName, moduleFile, specVersion).getBytes("UTF-8"));

    jos.putNextEntry(new ZipEntry("netbeans/modules/" + moduleFile + ".jar.external"));

    FileInputStream fis = new FileInputStream(ext);
    FileUtil.copy(fis, jos);
    fis.close();
    ext.delete();
    jos.close();
    nbms.add(nbm);

    return nbm;
  }
 public ImportVectorDataNodeFromCsvAction() {
   this(Utilities.actionsGlobalContext());
 }
 public Pause() {
   this(Utilities.actionsGlobalContext());
 }
/** @author todd */
class OnlineStatusIndicator {
  private static Image OPEN_IMAGE = Utilities.loadImage(SessionNode.OPEN_ICON);
  private static Image CLOSED_IMAGE = Utilities.loadImage(SessionNode.CLOSED_ICON);
  private static Image AWAY_IMAGE = Utilities.loadImage(SessionNode.AWAY_ICON);
  private static Image BUSY_IMAGE = Utilities.loadImage(SessionNode.BUSY_ICON);
  private static Image IDLE_IMAGE = Utilities.loadImage(SessionNode.IDLE_ICON);
  private static OnlineStatusIndicator instance;

  ////////////////////////////////////////////////////////////////////////////
  // Instance fields
  ////////////////////////////////////////////////////////////////////////////
  private JLabel label;
  private Helper helper;
  private int currentStatus = CollabPrincipal.STATUS_UNKNOWN;

  Component getComponent() {
    return label;
  }

  /** */
  protected OnlineStatusIndicator() {
    helper = new Helper();
    label = new JLabel();
    label.addMouseListener(helper);
    initListening(1);
  }

  private void initListening(final int level) {
    CollabManager man = CollabManager.getDefault();
    if (man == null) {
      // manager not yet registered. This is a transient condition during
      // module enablement because of manager registration mechanism.
      // Retry 5s later
      assert level < 10;

      RequestProcessor.getDefault()
          .post(
              new Runnable() {
                public void run() {
                  initListening(level + 1);
                }
              },
              level * 5000);
    } else {
      man.addPropertyChangeListener(helper);
      attachListeners();
      updateStatus();
    }
  }

  private void setStatus(int value) {
    currentStatus = value;
    SwingUtilities.invokeLater(helper);
  }

  /** */
  protected void updateStatus() {
    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      int sharedStatus = CollabPrincipal.STATUS_OFFLINE;
      boolean unilateral = true;

      CollabSession[] sessions = manager.getSessions();

      for (int i = 0; i < sessions.length; i++) {
        int status = sessions[i].getUserPrincipal().getStatus();

        if (sharedStatus == CollabPrincipal.STATUS_OFFLINE) {
          sharedStatus = status;
        }

        if (status != sharedStatus) {
          unilateral = false;
        }
      }

      if (unilateral) {
        // This will occur if either:
        // 1) No sessions were found
        // 2) All available sessions had the same status
        setStatus(sharedStatus);
      } else {
        // Assume at least one session is online
        setStatus(CollabPrincipal.STATUS_ONLINE);
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  // Helper methods
  ////////////////////////////////////////////////////////////////////////////

  /** */
  public static String getStatusDescription(int status) {
    final String description;

    switch (status) {
      case CollabPrincipal.STATUS_AWAY:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusAway"); // NOI18N

        break;

      case CollabPrincipal.STATUS_BUSY:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusBusy"); // NOI18N

        break;

      case CollabPrincipal.STATUS_IDLE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusIdle"); // NOI18N

        break;

      case CollabPrincipal.STATUS_OFFLINE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusOffline"); // NOI18N

        break;

      case CollabPrincipal.STATUS_ONLINE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusOnline"); // NOI18N

        break;

      default:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusUnknown"); // NOI18N
    }

    return description;
  }

  /** */
  public static Image getStatusIcon(int status) {
    final Image statusIcon;

    switch (status) {
      case CollabPrincipal.STATUS_AWAY:
        statusIcon = AWAY_IMAGE;

        break;

      case CollabPrincipal.STATUS_BUSY:
        statusIcon = BUSY_IMAGE;

        break;

      case CollabPrincipal.STATUS_IDLE:
        statusIcon = IDLE_IMAGE;

        break;

      case CollabPrincipal.STATUS_OFFLINE:
        statusIcon = CLOSED_IMAGE;

        break;

      case CollabPrincipal.STATUS_ONLINE:
        statusIcon = OPEN_IMAGE;

        break;

      default:
        statusIcon = CLOSED_IMAGE;
    }

    return statusIcon;
  }

  /** */
  protected static String getStatusToolTip() {
    StringBuffer result = new StringBuffer("<html>"); // NOI18N
    result.append("<table cellspacing=\"0\" border=\"0\">"); // NOI18N

    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      Set sessions =
          new TreeSet(
              new Comparator() {
                public int compare(Object o1, Object o2) {
                  String s1 = ((CollabSession) o1).getUserPrincipal().getDisplayName();
                  String s2 = ((CollabSession) o2).getUserPrincipal().getDisplayName();

                  return s1.compareTo(s2);
                }
              });

      sessions.addAll(Arrays.asList(manager.getSessions()));

      if (sessions.size() == 0) {
        result.append("<tr><td>"); // NOI18N
        result.append(getStatusDescription(CollabPrincipal.STATUS_OFFLINE));
        result.append("</td></tr>"); // NOI18N
      } else {
        for (Iterator i = sessions.iterator(); i.hasNext(); ) {
          CollabPrincipal principal = ((CollabSession) i.next()).getUserPrincipal();

          result.append("<tr>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append("<b>"); // NOI18N
          result.append(principal.getDisplayName());
          result.append(": "); // NOI18N
          result.append("</b>"); // NOI18N
          result.append("</td>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append(getStatusDescription(principal.getStatus()));
          result.append("</td>"); // NOI18N
          result.append("</tr>"); // NOI18N
        }
      }
    }

    result.append("</table>"); // NOI18N

    return result.toString();
  }

  ////////////////////////////////////////////////////////////////////////////
  // Management methods
  ////////////////////////////////////////////////////////////////////////////

  /** */
  static synchronized OnlineStatusIndicator getDefault() {
    if (instance == null) {
      instance = new OnlineStatusIndicator();
    }

    return instance;
  }

  /** */
  private void attachListeners() {
    // Add the listener from each collab session principal
    CollabSession[] sessions = CollabManager.getDefault().getSessions();

    for (int i = 0; i < sessions.length; i++) {
      sessions[i].getUserPrincipal().removePropertyChangeListener(helper);
      sessions[i].getUserPrincipal().addPropertyChangeListener(helper);
    }
  }

  private class Helper extends MouseAdapter implements PropertyChangeListener, Runnable {
    public void mouseClicked(MouseEvent event) {
      CollabExplorerPanel.getInstance().open();
      CollabExplorerPanel.getInstance().requestActive();
    }

    public void propertyChange(PropertyChangeEvent event) {
      // session list changed
      if (event.getSource() instanceof CollabManager) {
        attachListeners();
      }

      // either session list or session status changed
      updateStatus();
    }

    public void run() {
      Image statusIcon = getStatusIcon(currentStatus);
      label.setIcon(new ImageIcon(statusIcon));
      label.setToolTipText(getStatusToolTip());
    }
  }
}
Exemplo n.º 30
0
 @Override
 public Action[] getActions(boolean context) {
   return new ApplyInferenceRuleAction[] {
     new ApplyInferenceRuleAction(Utilities.actionsGlobalContext())
   };
 }