Пример #1
0
  /**
   * This method displays the result in the result text area.
   *
   * @param result to display
   */
  private void showResult(Object result) {

    resultTextArea.setText(null);
    if (result instanceof String) {
      resultTextArea.append((String) result);
    } else if (result instanceof String[]) {
      String[] resultStringArray = (String[]) result;
      if (resultStringArray.length == 0) {
        resultTextArea.append(guiText.getString("EmptyArray"));
      } else {
        Arrays.sort(resultStringArray, String.CASE_INSENSITIVE_ORDER);
        for (String s : (String[]) resultStringArray) {
          resultTextArea.append(s);
          resultTextArea.append("\n");
        }
      }
    } else if (result instanceof ECSpec) {
      CharArrayWriter writer = new CharArrayWriter();
      try {
        SerializerUtil.serializeECSpecPretty((ECSpec) result, writer);
      } catch (IOException e) {
        showExcpetionDialog(guiText.getString("SerializationExceptionMessage"));
      }
      resultTextArea.append(writer.toString());
    } else if (result instanceof ECReports) {
      CharArrayWriter writer = new CharArrayWriter();
      try {
        SerializerUtil.serializeECReportsPretty((ECReports) result, writer);
      } catch (IOException e) {
        showExcpetionDialog(guiText.getString("SerializationExceptionMessage"));
      }
      resultTextArea.append(writer.toString());
    }
  }
Пример #2
0
  /**
   * This method adds a choose file field to the panel.
   *
   * @param panel to which the choose file field should be added
   */
  private void addChooseFileField(JPanel panel) {

    filePathField = new JTextField();

    final FileDialog fileDialog = new FileDialog(this);
    fileDialog.setModal(true);
    fileDialog.addComponentListener(
        new ComponentAdapter() {
          public void componentHidden(ComponentEvent e) {
            if (fileDialog.getFile() != null) {
              filePathField.setText(fileDialog.getDirectory() + fileDialog.getFile());
            }
          }
        });

    final JButton chooseFileButton = new JButton(guiText.getString("ChooseFileButtonLabel"));
    chooseFileButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fileDialog.setVisible(true);
          }
        });

    JPanel chooseFileButtonPanel = new JPanel();
    chooseFileButtonPanel.setLayout(new GridLayout(1, 3));
    chooseFileButtonPanel.add(new JPanel());
    chooseFileButtonPanel.add(chooseFileButton);
    chooseFileButtonPanel.add(new JPanel());

    panel.add(new JLabel(guiText.getString("FilePathLabel")));
    panel.add(filePathField);
    panel.add(chooseFileButtonPanel);
  }
Пример #3
0
  /**
   * This method creates the file menu.
   *
   * @return file menu
   */
  private Component createFileMenu() {

    JMenu fileMenuItem = new JMenu(guiText.getString("FileMenu"));

    JMenuItem exitMenuItem = new JMenuItem(guiText.getString("QuitMenuItem"));
    exitMenuItem.addMouseListener(
        new MouseAdapter() {
          public void mouseReleased(MouseEvent e) {
            System.exit(0);
          }
        });
    fileMenuItem.add(exitMenuItem);

    return fileMenuItem;
  }
Пример #4
0
  @Override
  public User getUserByLoginId(String loginid) throws SQLException {
    User user = null;
    PropertyResourceBundle prop = (PropertyResourceBundle) ResourceBundle.getBundle("kujosa");

    Connection connection = null;
    PreparedStatement stmt = null;
    try {
      connection = Database.getConnection();

      stmt = connection.prepareStatement(UserDAOQuery.GET_USER_BY_USERNAME);
      stmt.setString(1, loginid);

      ResultSet rs = stmt.executeQuery();
      if (rs.next()) {
        user = new User();
        user.setId(rs.getString("id"));
        user.setLoginid(rs.getString("loginid"));
        user.setEmail(rs.getString("email"));
        user.setFullname(rs.getString("fullname"));
        user.setFilename(rs.getString("image") + ".png");
        user.setImageURL(prop.getString("imgBaseURL") + user.getFilename());
      }
    } catch (SQLException e) {
      throw e;
    } finally {
      if (stmt != null) stmt.close();
      if (connection != null) connection.close();
    }

    return user;
  }
  @SuppressWarnings({"HardCodedStringLiteral"})
  @Nullable
  public static String getPropertyFromLaxFile(
      @NotNull final File file, @NotNull final String propertyName) {
    if (file.getName().endsWith(".properties")) {
      try {
        PropertyResourceBundle bundle;
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        try {
          bundle = new PropertyResourceBundle(fis);
        } finally {
          fis.close();
        }
        if (bundle.containsKey(propertyName)) {
          return bundle.getString(propertyName);
        }
        return null;
      } catch (IOException e) {
        return null;
      }
    }

    final String fileContent = getContent(file);

    // try to find custom config path
    final String propertyValue = findProperty(propertyName, fileContent);
    if (!StringUtil.isEmpty(propertyValue)) {
      return propertyValue;
    }

    return null;
  }
Пример #6
0
  /**
   * This method adds a notification uri field to the panel.
   *
   * @param panel to which the norification uri field should be added
   */
  private void addNotificationURIField(JPanel panel) {

    notificationUriField = new JTextField();

    panel.add(new JLabel(guiText.getString("NotificationURILabel")));
    panel.add(notificationUriField);
  }
Пример #7
0
  /**
   * This method creates the command selection panel.
   *
   * @return command selection panel
   */
  private JPanel createCommandSelectionPanel() {

    JPanel selectionPanel = new JPanel();
    selectionPanel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(guiText.getString("SelectionPanelTitle")),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    commandSelection.setMaximumRowCount(12);

    commandSelection.addItem(null);
    for (String item : getCommands()) {
      commandSelection.addItem(item);
    }

    commandSelection.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if ("comboBoxChanged".equals(e.getActionCommand())) {
              setCommandPanel(commandSelection.getSelectedIndex());
            }
          }
        });

    selectionPanel.add(commandSelection);

    return selectionPanel;
  }
Пример #8
0
 private void initConfigDecorator() {
   InputStream in =
       Q2.class
           .getClassLoader()
           .getResourceAsStream("META-INF/org/jpos/config/Q2-decorator.properties");
   try {
     if (in != null) {
       PropertyResourceBundle bundle = new PropertyResourceBundle(in);
       String ccdClass = bundle.getString("config-decorator-class");
       if (log != null) log.info("Initializing config decoration provider: " + ccdClass);
       decorator =
           (ConfigDecorationProvider) Q2.class.getClassLoader().loadClass(ccdClass).newInstance();
       decorator.initialize(getDeployDir());
     }
   } catch (IOException e) {
   } catch (Exception e) {
     if (log != null) log.error(e);
     else {
       e.printStackTrace();
     }
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException e) {
       }
     }
   }
 }
Пример #9
0
  /**
   * This method sets the command selection panel depending on the command id.
   *
   * @param command id
   */
  private void setCommandPanel(int command) {

    if (command == -1) {
      commandPanel.removeAll();
      commandPanel.setBorder(null);
      this.setVisible(false);
      this.setVisible(true);
      return;
    }

    commandPanel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(guiText.getString("Command" + command)),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    commandPanel.removeAll();

    switch (command) {
      case 4: // getECSpecNames
      case 10: // getStandardVersion
      case 11: // getVendorVersion
        commandPanel.setLayout(new GridLayout(1, 1, 5, 0));
        break;

      case 2: // undefine
      case 3: // getECSpec
      case 7: // poll
      case 9: // getSubscribers
        commandPanel.setLayout(new GridLayout(5, 1, 5, 0));
        addECSpecNameComboBox(commandPanel);
        addSeparator(commandPanel);
        break;

      case 5: // subscribe
      case 6: // unsubscribe
        commandPanel.setLayout(new GridLayout(7, 1, 5, 0));
        addECSpecNameComboBox(commandPanel);
        addNotificationURIField(commandPanel);
        addSeparator(commandPanel);
        break;

      case 8: // immediate
        commandPanel.setLayout(new GridLayout(6, 1, 5, 0));
        addChooseFileField(commandPanel);
        addSeparator(commandPanel);
        break;

      case 1: // define
        commandPanel.setLayout(new GridLayout(8, 1, 5, 0));
        addECSpecNameComboBox(commandPanel);
        addChooseFileField(commandPanel);
        addSeparator(commandPanel);
        break;
    }

    addExecuteButton(commandPanel);

    this.setVisible(false);
    this.setVisible(true);
  }
Пример #10
0
  /**
   * This method returns the names of all commands.
   *
   * @return command names
   */
  private String[] getCommands() {

    String[] commands = new String[11];
    for (int i = 1; i < 12; i++) {
      commands[i - 1] = guiText.getString("Command" + i);
    }
    return commands;
  }
Пример #11
0
  static SQLException createSQLException(
      Locale msgLocale, String messageId, Object[] messageArguments) {
    Locale currentLocale;
    int sqlcode;

    if (msgLocale == null) currentLocale = Locale.getDefault();
    else currentLocale = msgLocale;
    try {
      PropertyResourceBundle messageBundle =
          (PropertyResourceBundle)
              ResourceBundle.getBundle(
                  "SQLMXT2Messages",
                  currentLocale); // R321 changed property file name to
                                  // SQLMXT2Messages_en.properties
      MessageFormat formatter = new MessageFormat("");
      formatter.setLocale(currentLocale);
      formatter.applyPattern(messageBundle.getString(messageId + "_msg"));
      String message = formatter.format(messageArguments);
      String sqlState = messageBundle.getString(messageId + "_sqlstate");
      String sqlcodeStr = messageBundle.getString(messageId + "_sqlcode");
      if (sqlcodeStr != null) {
        try {
          sqlcode = Integer.parseInt(sqlcodeStr);
          sqlcode = -sqlcode;
        } catch (NumberFormatException e1) {
          sqlcode = -1;
        }
      } else sqlcode = -1;
      return new SQLException(message, sqlState, sqlcode);
    } catch (MissingResourceException e) {
      // If the resource bundle is not found, concatenate the messageId and the parameters
      String message;
      int i = 0;

      message = "The message id: " + messageId;
      if (messageArguments != null) {
        message = message.concat(" With parameters: ");
        while (true) {
          message = message.concat(messageArguments[i++].toString());
          if (i >= messageArguments.length) break;
          else message = message.concat(",");
        }
      }
      return new SQLException(message, "HY000", -1);
    }
  }
Пример #12
0
 /* (non-Javadoc)
  * @see java.util.ResourceBundle#handleGetObject(java.lang.String)
  */
 protected Object handleGetObject(String key) {
   String value = (String) bundle.getString(key);
   if (value == null) return null;
   try {
     return new String(value.getBytes("ISO-8859-1"), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     // Shouldn't fail - but should we still add logging message?
     return null;
   }
 }
  public static Optional<String> getLocalePrefixForLocateResource(final FacesContext facesContext) {
    String localePrefix = null;
    boolean isResourceRequest =
        facesContext.getApplication().getResourceHandler().isResourceRequest(facesContext);

    if (isResourceRequest) {
      localePrefix =
          facesContext
              .getExternalContext()
              .getRequestParameterMap()
              .get(OsgiResource.REQUEST_PARAM_LOCALE);

      if (localePrefix != null) {
        if (!ResourceValidationUtils.isValidLocalePrefix(localePrefix)) {
          return Optional.empty();
        }
        return Optional.of(localePrefix);
      }
    }

    String bundleName = facesContext.getApplication().getMessageBundle();

    if (null != bundleName) {
      Locale locale = null;

      if (isResourceRequest || facesContext.getViewRoot() == null) {
        locale = facesContext.getApplication().getViewHandler().calculateLocale(facesContext);
      } else {
        locale = facesContext.getViewRoot().getLocale();
      }

      try {
        // load resource via ServletContext because due to Classloader
        ServletContext servletContext =
            (ServletContext) facesContext.getExternalContext().getContext();
        PropertyResourceBundle resourceBundle = null;
        try {
          URL resourceUrl =
              servletContext.getResource(
                  '/' + bundleName.replace('.', '/') + '_' + locale + ".properties");
          if (resourceUrl != null) {
            resourceBundle = new PropertyResourceBundle(resourceUrl.openStream());
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
        if (resourceBundle != null) {
          localePrefix = resourceBundle.getString(ResourceHandler.LOCALE_PREFIX);
        }
      } catch (MissingResourceException e) {
        // Ignore it and return null
      }
    }
    return Optional.ofNullable(localePrefix);
  }
Пример #14
0
  /**
   * This method creates a exception dialog and sets it visible.
   *
   * @param message to display
   * @param reason to display
   */
  private void showExcpetionDialog(String message, String reason) {

    Rectangle guiBounds = this.getBounds();
    int width = getProperty("DialogWidth");
    int height = getProperty("DialogHeight");
    int xPos = guiBounds.x + (guiBounds.width - width) / 2;
    int yPos = guiBounds.y + (guiBounds.height - height) / 2;

    final JDialog dialog = new JDialog(this, true);
    dialog.setBounds(xPos, yPos, width, height);
    dialog.setLayout(new BorderLayout(10, 10));
    dialog.setTitle(guiText.getString("ExceptionDialogTitle"));

    // message label
    JLabel messageLabel = new JLabel(message);
    JPanel messageLabelPanel = new JPanel();
    messageLabelPanel.add(messageLabel);

    // reason panel
    JTextArea reasonTextArea = new JTextArea(reason);
    JScrollPane reasonScrollPane = new JScrollPane(reasonTextArea);
    reasonScrollPane.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(guiText.getString("DetailsPanelTitle")),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    reasonTextArea.setEditable(false);

    // ok button
    JButton okButton = new JButton(guiText.getString("OkButtonLabel"));
    okButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            dialog.setVisible(false);
          }
        });

    // put all together
    dialog.add(messageLabelPanel, BorderLayout.NORTH);
    dialog.add(reasonScrollPane, BorderLayout.CENTER);
    dialog.add(okButton, BorderLayout.SOUTH);
    dialog.setVisible(true);
  }
Пример #15
0
  public DBConnection(String user, String pass, Component fThis) {
    {
      try {
        url = new StringBuilder();
        url.append("jdbc:postgresql://");
        url.append(resources.getString("server"));
        url.append(":");
        url.append("5432");
        url.append("/");
        url.append(resources.getString("database"));

        System.out.println(url);
        Class.forName("org.postgresql.Driver");
        con = DriverManager.getConnection(url.toString(), user, pass);

        bError = true;
      } catch (java.sql.SQLException se) {
        JOptionPane jfo = new JOptionPane(se.getMessage(), JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = jfo.createDialog(fThis, "Message");
        dialog.setModal(true);
        dialog.setVisible(true);
        bError = false;
        // System.exit(1);
      } catch (ClassNotFoundException ce) {
        JOptionPane jfo = new JOptionPane(ce.getMessage(), JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = jfo.createDialog(fThis, "Message");
        dialog.setModal(true);
        dialog.setVisible(true);
        bError = false;
        // System.exit(1);
      } finally {
        //                try {
        //                    in.close();
        //                } catch (IOException ex) {
        //                    Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null,
        // ex);
        //                }
      }
    }
  }
Пример #16
0
  private static void processFiles(File baseDir, Filter filter) throws Exception {
    File[] propertyFiles = baseDir.listFiles(filter);

    File source = new File(baseDir.getAbsolutePath() + "/" + filter.getPrefix() + ".properties");
    System.out.println("Source: " + source);
    PropertyResourceBundle sourceBundle = new PropertyResourceBundle(new FileInputStream(source));

    for (File target : propertyFiles) {
      PropertyResourceBundle targetBundle = new PropertyResourceBundle(new FileInputStream(target));

      System.out.println("Processing: " + target);
      List<String> remaining = match(sourceBundle, targetBundle);

      // write it back

      Collections.sort(remaining);

      if (!dryRun) target.delete();

      OutputStreamWriter writer =
          dryRun ? null : new OutputStreamWriter(new FileOutputStream(target, false), "UTF-8");

      for (String remain : remaining) {
        if (dryRun) {
          System.out.println(remain + "=" + targetBundle.getString(remain));
        } else {
          writer.write(remain + "=" + targetBundle.getString(remain));
          writer.write("\n");
        }
      }

      if (writer != null) {
        writer.flush();
        writer.close();
      }

      System.out.println("\n\n");
    }
  }
 public static String getMessage(int i) {
   try {
     String s = ""; // _cs, _de, _pl
     PropertyResourceBundle props =
         new PropertyResourceBundle(
             CodeBaseManifestEntrySignedMatching.class
                 .getClassLoader()
                 .getResourceAsStream(
                     "net/sourceforge/jnlp/resources/Messages" + s + ".properties"));
     return props.getString(keys[i]);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
Пример #18
0
  /** This method initializes the gui and set it visible. */
  private void initializeGUI() {

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(getProperty("WindowWidth"), getProperty("WindowHeight"));
    this.setTitle(guiText.getString("ApplicationTitle"));
    this.setJMenuBar(createMenuBar());

    this.setLayout(new BorderLayout());
    this.add(createCommandSelectionPanel(), BorderLayout.NORTH);
    this.add(commandSuperPanel, BorderLayout.CENTER);
    this.add(resultScrollPane, BorderLayout.SOUTH);

    commandSuperPanel.setLayout(new BorderLayout());
    commandSuperPanel.add(commandPanel, BorderLayout.NORTH);

    resultScrollPane.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(guiText.getString("ResultPanelTitle")),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));

    resultTextArea.setEditable(false);

    this.setVisible(true);
  }
 /**
  * @see
  *     org.eclipse.papyrus.adltool.designer.bundle.AbstractBundleDescriptionDesigner#getBundleValue(java.lang.Object,
  *     java.lang.String)
  * @param bundleProject
  * @param key
  * @return the value that corresponds to the key
  */
 public String getBundleValue(Object bundleProject, String key) {
   String valueFromDescription = null;
   if (bundleProject instanceof IBundleProjectDescription) {
     PropertyResourceBundle propertyResourceBundle =
         getNLSFilesFor((IBundleProjectDescription) bundleProject);
     valueFromDescription = ((IBundleProjectDescription) bundleProject).getHeader(key);
     if (propertyResourceBundle != null && valueFromDescription != null) {
       if (valueFromDescription.startsWith("%")
           && (valueFromDescription.length() > 1)) { // $NON-NLS-1$
         String propertiesKey = valueFromDescription.substring(1);
         valueFromDescription = propertyResourceBundle.getString(propertiesKey);
       }
     }
   }
   return valueFromDescription;
 }
Пример #20
0
  /**
   * This method hunts down the version recorded in the current product.
   *
   * @throws IOException
   */
  private void loadVersion() {
    IProduct product = Platform.getProduct();
    if (product == null || !(UDIG_PRODUCT_ID.equals(product.getId()))) {
      // chances are someone is using the SDK with their own
      // application or product.
      String message =
          "Unable to parse version from about.mappings file. Defaulting to a blank string."; //$NON-NLS-1$
      this.getLog().log(new Status(IStatus.INFO, ID, 0, message, null));
      this.version = "";
      return;
    }
    Bundle pluginBundle = product.getDefiningBundle();

    URL mappingsURL = FileLocator.find(pluginBundle, new Path(MAPPINGS_FILENAME), null);
    if (mappingsURL != null) {
      try {
        mappingsURL = FileLocator.resolve(mappingsURL);
      } catch (IOException e) {
        mappingsURL = null;
        String message =
            "Unable to find " + mappingsURL + " Defaulting to a blank string."; // $NON-NLS-1$
        this.getLog().log(new Status(IStatus.ERROR, ID, 0, message, e));
      }
    }
    PropertyResourceBundle bundle = null;
    if (mappingsURL != null) {
      InputStream is = null;
      try {
        is = mappingsURL.openStream();
        bundle = new PropertyResourceBundle(is);
      } catch (IOException e) {
        bundle = null;
        String message =
            "Unable to parse version from about.mappings file. Defaulting to a blank string."; //$NON-NLS-1$
        this.getLog().log(new Status(IStatus.ERROR, ID, 0, message, e));
      } finally {
        try {
          if (is != null) is.close();
        } catch (IOException e) {
        }
      }
    }

    if (bundle != null) {
      this.version = bundle.getString(UDIG_VERSION_KEY);
    }
  }
  private String getWsdUrl() {
    PropertyResourceBundle resourceBundle = null;
    InputStream resourceAsStream = null;
    try {
      resourceAsStream = getServletContext().getResourceAsStream(VIEWER_PROPERTIES);
      resourceBundle = new PropertyResourceBundle(resourceAsStream);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        resourceAsStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    String wsdlLocation = resourceBundle.getString(WSDL_LOCATION);
    return wsdlLocation;
  }
Пример #22
0
  /**
   * @param id nom d'usuari a cercar
   * @return torna la entitat usuari
   * @throws SQLException
   */
  @Override
  public User getUserById(String id) throws SQLException {
    // Modelo a devolver
    User user = null;
    PropertyResourceBundle prop = (PropertyResourceBundle) ResourceBundle.getBundle("kujosa");

    Connection connection = null;
    PreparedStatement stmt = null;
    try {
      // Obtiene la conexión del DataSource
      connection = Database.getConnection();

      // Prepara la consulta
      stmt = connection.prepareStatement(UserDAOQuery.GET_USER_BY_ID);
      // Da valor a los parámetros de la consulta
      stmt.setString(1, id);

      // Ejecuta la consulta
      ResultSet rs = stmt.executeQuery();
      // Procesa los resultados
      if (rs.next()) {
        user = new User();
        user.setId(rs.getString("id"));
        user.setLoginid(rs.getString("loginid"));
        user.setEmail(rs.getString("email"));
        user.setFullname(rs.getString("fullname"));
        user.setFilename(rs.getString("image") + ".png");
        user.setImageURL(prop.getString("imgBaseURL") + user.getFilename());
        user.setAdmin(this.isAdmin(user.getId()));
      }
    } catch (SQLException e) {
      // Relanza la excepción
      throw e;
    } finally {
      // Libera la conexión
      if (stmt != null) stmt.close();
      if (connection != null) connection.close();
    }

    // Devuelve el modelo
    return user;
  }
Пример #23
0
  private UUID writeAndConvertImage(InputStream file) {
    BufferedImage image = null;
    try {
      image = ImageIO.read(file);

    } catch (IOException e) {
      throw new InternalServerErrorException("Something has been wrong when reading the file.");
    }
    UUID uuid = UUID.randomUUID();
    String filename = uuid.toString() + ".png";

    try {
      PropertyResourceBundle prb = (PropertyResourceBundle) ResourceBundle.getBundle("kujosa");
      ImageIO.write(image, "png", new File(prb.getString("uploadFolder") + filename));
    } catch (IOException e) {
      throw new InternalServerErrorException("Something has been wrong when converting the file.");
    }

    return uuid;
  }
 /**
  * This method initializes privateListPanel
  *
  * @return javax.swing.JPanel
  */
 private RoboticonListPanel getPrivateListPanel() {
   if (privateListPanel == null) {
     privateListPanel =
         new RoboticonListPanel(
             RESOURCES.getString("label.roboticons"),
             privateList,
             new String[] {
               SortOrder.NAME.toString(), SortOrder.TYPE.toString(), SortOrder.DATE.toString()
             },
             1,
             new Dimension(200, 250));
     privateListPanel.addSortOrderListener(
         new SortOrderListenerIf() {
           public void sortOrderChanged(SortOrder newOrder) {
             privateSortedRoboticonModel.setSortOrder(newOrder);
           }
         });
   }
   return privateListPanel;
 }
Пример #25
0
  /**
   * This method adds a specification name combobox to the panel.
   *
   * @param panel to which the specification name combobox should be added
   */
  private void addECSpecNameComboBox(JPanel panel) {

    specNameComboBox = new JComboBox();
    specNameComboBox.setEditable(true);
    specNameComboBox.addItem(null);

    String[] ecSpecNames;
    try {
      ecSpecNames = aleProxy.getECSpecNames(new EmptyParms());
      if (ecSpecNames != null && ecSpecNames.length > 0) {
        Arrays.sort(ecSpecNames, String.CASE_INSENSITIVE_ORDER);
        for (String specName : ecSpecNames) {
          specNameComboBox.addItem(specName);
        }
      }
    } catch (RemoteException e) {
    }

    panel.add(new JLabel(guiText.getString("SpecNameLabel")));
    panel.add(specNameComboBox);
  }
Пример #26
0
  /**
   * This method adds a execute button to the panel.
   *
   * @param panel to which the execute button should be added
   */
  private void addExecuteButton(JPanel panel) {

    if (execButtonPanel == null) {

      JButton execButton = new JButton(guiText.getString("ExecuteButtonLabel"));
      execButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              executeCommand();
            }
          });

      execButtonPanel = new JPanel();
      execButtonPanel.setLayout(new GridLayout(1, 3));
      execButtonPanel.add(new JPanel());
      execButtonPanel.add(execButton);
      execButtonPanel.add(new JPanel());
    }

    panel.add(execButtonPanel);
  }
Пример #27
0
  /**
   * This method executes the command which is selected in the command selection combobox with the
   * parameters which are set in the corresponding fields. To execute the commands, the methods of
   * the ale proxy will be invoked.
   */
  private void executeCommand() {

    Object result = null;
    String specName = null;
    String notificationURI = null;

    try {

      switch (commandSelection.getSelectedIndex()) {
        case 4: // getECSpecNames
          result = aleProxy.getECSpecNames(new EmptyParms());
          break;

        case 10: // getStandardVersion
          result = aleProxy.getStandardVersion(new EmptyParms());
          break;

        case 11: // getVendorVersion
          result = aleProxy.getVendorVersion(new EmptyParms());
          break;

        case 2: // undefine
        case 3: // getECSpec
        case 7: // poll
        case 9: // getSubscribers
          // get specName
          specName = (String) specNameComboBox.getSelectedItem();
          if (specName == null || "".equals(specName)) {
            showExcpetionDialog(guiText.getString("SpecNameNotSpecifiedDialog"));
            break;
          }

          switch (commandSelection.getSelectedIndex()) {
            case 2: // undefine
              Undefine undefineParms = new Undefine();
              undefineParms.setSpecName(specName);
              aleProxy.undefine(undefineParms);
              result = guiText.getString("SuccessfullyUndefinedMessage");
              break;

            case 3: // getECSpec
              GetECSpec getECSpecParms = new GetECSpec();
              getECSpecParms.setSpecName(specName);
              result = aleProxy.getECSpec(getECSpecParms);
              break;

            case 7: // poll
              Poll pollParms = new Poll();
              pollParms.setSpecName(specName);
              result = aleProxy.poll(pollParms);
              break;

            case 9: // getSubscribers
              GetSubscribers getSubscribersParms = new GetSubscribers();
              getSubscribersParms.setSpecName(specName);
              result = aleProxy.getSubscribers(getSubscribersParms);
              break;
          }

          break;

        case 5: // subscribe
        case 6: // unsubscribe
          // get specName
          specName = (String) specNameComboBox.getSelectedItem();
          if (specName == null || "".equals(specName)) {
            showExcpetionDialog(guiText.getString("SpecNameNotSpecifiedDialog"));
            break;
          }

          // get notificationURI
          notificationURI = notificationUriField.getText();
          if (notificationURI == null || "".equals(notificationURI)) {
            showExcpetionDialog(guiText.getString("NotificationUriNotSpecifiedDialog"));
            break;
          }

          switch (commandSelection.getSelectedIndex()) {
            case 5:
              Subscribe subscribeParms = new Subscribe();
              subscribeParms.setSpecName(specName);
              subscribeParms.setNotificationURI(notificationURI);
              aleProxy.subscribe(subscribeParms);
              result = guiText.getString("SuccessfullySubscribedMessage");
              break;

            case 6:
              Unsubscribe unsubscribeParms = new Unsubscribe();
              unsubscribeParms.setSpecName(specName);
              unsubscribeParms.setNotificationURI(notificationURI);
              aleProxy.unsubscribe(unsubscribeParms);
              result = guiText.getString("SuccessfullyUnsubscribedMessage");
              break;
          }

          break;

        case 1: // define
        case 8: // immediate
          if (commandSelection.getSelectedIndex() == 1) {
            // get specName
            specName = (String) specNameComboBox.getSelectedItem();
            if (specName == null || "".equals(specName)) {
              showExcpetionDialog(guiText.getString("SpecNameNotSpecifiedDialog"));
              break;
            }
          }

          // get filePath
          String filePath = filePathField.getText();
          if (filePath == null || "".equals(filePath)) {
            showExcpetionDialog(guiText.getString("FilePathNotSpecifiedDialog"));
            break;
          }

          // get ecSpec
          ECSpec ecSpec;
          try {
            ecSpec = getECSpecFromFile(filePath);
          } catch (FileNotFoundException e) {
            showExcpetionDialog(guiText.getString("FileNotFoundDialog"));
            break;
          } catch (Exception e) {
            showExcpetionDialog(guiText.getString("UnexpectedFileFormatDialog"));
            break;
          }

          if (commandSelection.getSelectedIndex() == 1) {
            Define defineParms = new Define();
            defineParms.setSpecName(specName);
            defineParms.setSpec(ecSpec);
            aleProxy.define(defineParms);
            result = guiText.getString("SuccessfullyDefinedMessage");
          } else {
            Immediate immediateParms = new Immediate();
            immediateParms.setSpec(ecSpec);
            result = aleProxy.immediate(immediateParms);
          }
          break;
      }

    } catch (RemoteException e) {
      if (e instanceof ALEException) {
        String reason = ((ALEException) e).getReason();
        if (e instanceof DuplicateNameException) {
          showExcpetionDialog(guiText.getString("DuplicateNameExceptionDialog"), reason);
        } else if (e instanceof DuplicateSubscriptionException) {
          showExcpetionDialog(guiText.getString("DuplicateSubscriptionExceptionDialog"), reason);
        } else if (e instanceof ECSpecValidationException) {
          showExcpetionDialog(guiText.getString("ECSpecValidationExceptionDialog"), reason);
        } else if (e instanceof ImplementationException) {
          showExcpetionDialog(guiText.getString("ImplementationExceptionDialog"), reason);
        } else if (e instanceof InvalidURIException) {
          showExcpetionDialog(guiText.getString("InvalidURIExceptionDialog"), reason);
        } else if (e instanceof NoSuchNameException) {
          showExcpetionDialog(guiText.getString("NoSuchNameExceptionDialog"), reason);
        } else if (e instanceof NoSuchSubscriberException) {
          showExcpetionDialog(guiText.getString("NoSuchSubscriberExceptionDialog"), reason);
        } else if (e instanceof SecurityException) {
          showExcpetionDialog(guiText.getString("SecurityExceptionDialog"), reason);
        }
      } else {
        if (e instanceof AxisFault
            && "java.net.ConnectException: Connection refused: connect"
                .equals(((AxisFault) e).getFaultReason())) {
          showExcpetionDialog(
              guiText.getString("ConnectionExceptionDialog"), props.getProperty("EndPoint"));
        } else {
          showExcpetionDialog(guiText.getString("UnknownExceptionDialog"), e.getMessage());
        }
      }
    }

    showResult(result);

    // update spec name combobox
    String[] ecSpecNames = null;
    try {
      ecSpecNames = aleProxy.getECSpecNames(new EmptyParms());
    } catch (RemoteException e) {
    }
    if (ecSpecNames != null
        && specNameComboBox != null
        && specNameComboBox.getSelectedObjects() != null
        && specNameComboBox.getSelectedObjects().length > 0) {
      String current = (String) specNameComboBox.getSelectedObjects()[0];
      Arrays.sort(ecSpecNames, String.CASE_INSENSITIVE_ORDER);
      specNameComboBox.removeAllItems();
      if (ecSpecNames != null && ecSpecNames.length > 0) {
        for (String name : ecSpecNames) {
          specNameComboBox.addItem(name);
        }
      }
      specNameComboBox.setSelectedItem(current);
    }
  }
/** @author Chris Bartley ([email protected]) */
public final class PropertyInspector extends BaseGUIClient {
  private static final Logger LOG = Logger.getLogger(PropertyInspector.class);

  private static final PropertyResourceBundle RESOURCES =
      (PropertyResourceBundle) PropertyResourceBundle.getBundle(PropertyInspector.class.getName());

  /** The application name (appears in the title bar) */
  private static final String APPLICATION_NAME = RESOURCES.getString("application.name");

  /** Properties file used to setup Ice for this application */
  private static final String ICE_DIRECT_CONNECT_PROPERTIES_FILE =
      "/edu/cmu/ri/mrpl/TeRK/client/propertyinspector/PropertyInspector.direct-connect.ice.properties";

  private static final String ICE_RELAY_PROPERTIES_FILE =
      "/edu/cmu/ri/mrpl/TeRK/client/propertyinspector/PropertyInspector.relay.ice.properties";

  private static final Dimension TABLE_DIMENSIONS = new Dimension(300, 300);

  private static final String COLUMN_NAME_KEY = RESOURCES.getString("table.column.name.keys");
  private static final String COLUMN_NAME_VALUE = RESOURCES.getString("table.column.name.values");

  private static final String SERVICE_NAME_QWERK = RESOURCES.getString("service.name.qwerk");
  private static final String SERVICE_NAME_ANALOG = RESOURCES.getString("service.name.analog");
  private static final String SERVICE_NAME_AUDIO = RESOURCES.getString("service.name.audio");
  private static final String SERVICE_NAME_DIGITAL_IN =
      RESOURCES.getString("service.name.digital-in");
  private static final String SERVICE_NAME_DIGITAL_OUT =
      RESOURCES.getString("service.name.digital-out");
  private static final String SERVICE_NAME_LED = RESOURCES.getString("service.name.led");
  private static final String SERVICE_NAME_MOTOR = RESOURCES.getString("service.name.motor");
  private static final String SERVICE_NAME_SERIAL = RESOURCES.getString("service.name.serial");
  private static final String SERVICE_NAME_SERVO = RESOURCES.getString("service.name.servo");
  private static final String SERVICE_NAME_VIDEO = RESOURCES.getString("service.name.video");
  private static final String[] SERVICE_NAMES =
      new String[] {
        SERVICE_NAME_QWERK,
        SERVICE_NAME_ANALOG,
        SERVICE_NAME_AUDIO,
        SERVICE_NAME_DIGITAL_IN,
        SERVICE_NAME_DIGITAL_OUT,
        SERVICE_NAME_LED,
        SERVICE_NAME_MOTOR,
        SERVICE_NAME_SERIAL,
        SERVICE_NAME_SERVO,
        SERVICE_NAME_VIDEO
      };

  private final JButton connectOrDisconnectButton = getConnectDisconnectButton();
  private final JTextField propertyKeyTextField = new JTextField(25);
  private final JTextField propertyValueTextField = new JTextField(25);
  private final JComboBox createPropertyServiceComboBox = new JComboBox(SERVICE_NAMES);
  private final JButton createPropertyButton =
      GUIConstants.createButton(RESOURCES.getString("button.label.create"));
  private final JComboBox viewPropertiesServiceComboBox = new JComboBox(SERVICE_NAMES);
  private final JButton reloadPropertiesButton =
      GUIConstants.createButton(RESOURCES.getString("button.label.reload"));
  private PropertiesTableModel propertiesTableModel = new PropertiesTableModel();
  private final JTable propertiesTable = new JTable(propertiesTableModel);

  private final Map<String, String> serviceNameToTypeIdMap;

  private final TextComponentValidator isNonEmptyValidator =
      new TextComponentValidator() {
        public boolean isValid(final JTextComponent textComponent) {
          return textComponent != null && isTextComponentNonEmpty(textComponent);
        }
      };

  private final KeyListener propertyKeyKeyListener =
      new EnableButtonIfTextFieldIsValidKeyAdapter(
          createPropertyButton, propertyKeyTextField, isNonEmptyValidator);

  private final ActionListener viewPropertiesAction = new ViewPropertiesAction();

  private final Runnable readonlyPropertyError =
      new ErrorMessageDialogRunnable(
          RESOURCES.getString("dialog.message.cannot-overwrite-read-only-property"),
          RESOURCES.getString("dialog.title.cannot-overwrite-read-only-property"));

  public static void main(final String[] args) {
    // Schedule a job for the event-dispatching thread: creating and showing this application's GUI.
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            new PropertyInspector();
          }
        });
  }

  private PropertyInspector() {
    super(APPLICATION_NAME, ICE_RELAY_PROPERTIES_FILE, ICE_DIRECT_CONNECT_PROPERTIES_FILE);
    setGUIClientHelperEventHandler(
        new GUIClientHelperEventHandlerAdapter() {
          public void executeAfterEstablishingConnectionToQwerk(final String qwerkUserId) {
            updateViewPropertiesTable();
          }

          public void toggleGUIElementState(final boolean isEnabled) {
            toggleGUIElements(isEnabled);
          }
        });

    // CONFIGURE GUI ELEMENTS
    // ========================================================================================

    this.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
    createPropertyButton.addActionListener(new CreatePropertyAction());
    final Map<String, String> tempServiceNameToTypeIdMap = new HashMap<String, String>();
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_ANALOG, AnalogInputsService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_AUDIO, AudioService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_IN, DigitalInService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_OUT, DigitalOutService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_LED, LEDService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_MOTOR, BackEMFMotorService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERIAL, SerialIOService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERVO, ServoService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_VIDEO, VideoStreamService.TYPE_ID);
    serviceNameToTypeIdMap = Collections.unmodifiableMap(tempServiceNameToTypeIdMap);

    viewPropertiesServiceComboBox.addItemListener(
        new ItemListener() {
          public void itemStateChanged(final ItemEvent itemEvent) {
            updateViewPropertiesTable();
          }
        });

    reloadPropertiesButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent actionEvent) {
            updateViewPropertiesTable();
          }
        });

    final JScrollPane propertiesTableScrollPane = new JScrollPane(propertiesTable);
    propertiesTableScrollPane.setMinimumSize(TABLE_DIMENSIONS);
    propertiesTableScrollPane.setMaximumSize(TABLE_DIMENSIONS);
    propertiesTableScrollPane.setPreferredSize(TABLE_DIMENSIONS);

    toggleGUIElements(false);
    propertyKeyTextField.addKeyListener(propertyKeyKeyListener);

    // LAYOUT GUI ELEMENTS
    // ===========================================================================================

    // create a panel to hold the connect/disconnect button and the connection state labels
    final JPanel connectionPanel = new JPanel(new SpringLayout());
    connectionPanel.add(connectOrDisconnectButton);
    connectionPanel.add(getConnectionStatePanel());
    SpringLayoutUtilities.makeCompactGrid(
        connectionPanel,
        1,
        2, // rows, cols
        0,
        0, // initX, initY
        10,
        10); // xPad, yPad

    final JPanel createPropertyPanel = new JPanel(new SpringLayout());
    createPropertyPanel.setBorder(
        BorderFactory.createTitledBorder(RESOURCES.getString("border.title.create-property")));
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service")));
    createPropertyPanel.add(createPropertyServiceComboBox);
    createPropertyPanel.add(createPropertyButton);
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.key")));
    createPropertyPanel.add(propertyKeyTextField);
    createPropertyPanel.add(Box.createGlue());
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.value")));
    createPropertyPanel.add(propertyValueTextField);
    createPropertyPanel.add(Box.createGlue());
    SpringLayoutUtilities.makeCompactGrid(
        createPropertyPanel,
        3,
        3, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    final JPanel serviceChooserPanel = new JPanel(new SpringLayout());
    serviceChooserPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service")));
    serviceChooserPanel.add(viewPropertiesServiceComboBox);
    serviceChooserPanel.add(reloadPropertiesButton);
    SpringLayoutUtilities.makeCompactGrid(
        serviceChooserPanel,
        1,
        3, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    final JPanel viewPropertiesPanel = new JPanel(new SpringLayout());
    viewPropertiesPanel.setBorder(
        BorderFactory.createTitledBorder(RESOURCES.getString("border.title.view-propertes")));
    viewPropertiesPanel.add(serviceChooserPanel);
    viewPropertiesPanel.add(propertiesTableScrollPane);
    SpringLayoutUtilities.makeCompactGrid(
        viewPropertiesPanel,
        2,
        1, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    // Layout the main content pane using SpringLayout
    getMainContentPane().setLayout(new SpringLayout());
    getMainContentPane().add(connectionPanel);
    getMainContentPane().add(createPropertyPanel);
    getMainContentPane().add(viewPropertiesPanel);
    SpringLayoutUtilities.makeCompactGrid(
        getMainContentPane(),
        3,
        1, // rows, cols
        10,
        10, // initX, initY
        10,
        10); // xPad, yPad

    pack();
    setLocationRelativeTo(null); // center the window on the screen
    setVisible(true);
  }

  private void toggleGUIElements(final boolean isEnabled) {
    propertyKeyTextField.setEnabled(isEnabled);
    propertyValueTextField.setEnabled(isEnabled);
    createPropertyServiceComboBox.setEnabled(isEnabled);
    createPropertyButton.setEnabled(isEnabled && isNonEmptyValidator.isValid(propertyKeyTextField));
    viewPropertiesServiceComboBox.setEnabled(isEnabled);
    reloadPropertiesButton.setEnabled(isEnabled);
    propertiesTable.setEnabled(isEnabled);
  }

  private PropertyManager getPropertyManagerByServiceName(final String serviceName) {
    if (SERVICE_NAME_QWERK.equals(serviceName)) {
      return getQwerkController();
    } else {
      final String serviceTypeId = serviceNameToTypeIdMap.get(serviceName);
      return getQwerkController().getServiceByTypeId(serviceTypeId);
    }
  }

  private void updateViewPropertiesTable() {
    viewPropertiesAction.actionPerformed(null);
  }

  private static boolean isTextComponentNonEmpty(final JTextComponent textField) {
    final String text1 = textField.getText();
    final String trimmedText1 = (text1 != null) ? text1.trim() : null;
    return (trimmedText1 != null) && (trimmedText1.length() > 0);
  }

  /** Retrieves the value from the specified text field as a {@link String}. */
  @SuppressWarnings({"UnusedCatchParameter"})
  private String getTextComponentValueAsString(final JTextComponent textComponent) {
    if (SwingUtilities.isEventDispatchThread()) {
      final String textFieldValue;
      try {
        final String text1 = textComponent.getText();
        textFieldValue = (text1 != null) ? text1.trim() : null;
      } catch (Exception e) {
        LOG.error("Exception while getting the value from text field. Returning null instead.", e);
        return null;
      }
      return textFieldValue;
    } else {
      final String[] textFieldValue = new String[1];
      try {
        SwingUtilities.invokeAndWait(
            new Runnable() {
              public void run() {
                textFieldValue[0] = textComponent.getText();
              }
            });
      } catch (Exception e) {
        LOG.error("Exception while getting the value from text field. Returning null instead.", e);
        return null;
      }

      return textFieldValue[0];
    }
  }

  private static interface TextComponentValidator {
    boolean isValid(final JTextComponent textComponent);
  }

  private static final class EnableButtonIfTextFieldIsValidKeyAdapter extends KeyAdapter {
    private final JButton button;
    private final JTextComponent textComponent;
    private final TextComponentValidator validator;

    private EnableButtonIfTextFieldIsValidKeyAdapter(
        final JButton button,
        final JTextComponent textComponent,
        final TextComponentValidator validator) {
      this.button = button;
      this.textComponent = textComponent;
      this.validator = validator;
    }

    public void keyReleased(final KeyEvent keyEvent) {
      button.setEnabled(validator.isValid(textComponent));
    }
  }

  private final class PropertiesTableModel extends AbstractTableModel {
    private final List<String> keys = new ArrayList<String>();
    private final List<String> values = new ArrayList<String>();

    private void update(final Map<String, String> properties) {
      keys.clear();
      values.clear();
      if (properties != null) {
        final SortedMap<String, String> sortedProperties = new TreeMap<String, String>(properties);
        keys.addAll(sortedProperties.keySet());
        values.addAll(sortedProperties.values());
      }
      fireTableDataChanged();
    }

    public int getRowCount() {
      return keys.size();
    }

    public String getColumnName(final int i) {
      return (i == 0) ? COLUMN_NAME_KEY : COLUMN_NAME_VALUE;
    }

    public int getColumnCount() {
      return 2;
    }

    public Object getValueAt(final int row, final int col) {
      if (col == 0) {
        return keys.get(row);
      } else if (col == 1) {
        return values.get(row);
      }
      return null;
    }
  }

  private final class CreatePropertyAction extends AbstractTimeConsumingAction {
    private String key;
    private String value;
    private String serviceName;
    private PropertyManager propertyManager;

    private CreatePropertyAction() {
      super(PropertyInspector.this);
    }

    protected void executeGUIActionBefore() {
      propertyKeyTextField.setEnabled(false);
      propertyValueTextField.setEnabled(false);
      createPropertyServiceComboBox.setEnabled(false);

      key = getTextComponentValueAsString(propertyKeyTextField);
      value = getTextComponentValueAsString(propertyValueTextField);
      serviceName = createPropertyServiceComboBox.getSelectedItem().toString();
      propertyManager = getPropertyManagerByServiceName(serviceName);
    }

    @SuppressWarnings({"UnusedCatchParameter"})
    protected Object executeTimeConsumingAction() {
      if (propertyManager != null) {
        try {
          propertyManager.setProperty(key, value);
        } catch (ReadOnlyPropertyException e) {
          LOG.info("Cannot overwrite read-only property [" + key + "]");
          return false;
        }
      }
      return true;
    }

    protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction) {
      if (!(Boolean) resultOfTimeConsumingAction) {
        SwingUtilities.invokeLater(readonlyPropertyError);
      }

      final String currentlyDisplayedService =
          viewPropertiesServiceComboBox.getSelectedItem().toString();
      viewPropertiesServiceComboBox.setSelectedItem(serviceName);

      // force a reload if the service name isn't different
      if (currentlyDisplayedService.equals(serviceName)) {
        updateViewPropertiesTable();
      }

      propertyKeyTextField.setEnabled(true);
      propertyValueTextField.setEnabled(true);
      createPropertyServiceComboBox.setEnabled(true);
    }
  }

  private final class ViewPropertiesAction extends AbstractTimeConsumingAction {
    private PropertyManager propertyManager;

    private ViewPropertiesAction() {
      super(PropertyInspector.this);
    }

    protected void executeGUIActionBefore() {
      viewPropertiesServiceComboBox.setEnabled(false);

      final String serviceName = viewPropertiesServiceComboBox.getSelectedItem().toString();
      propertyManager = getPropertyManagerByServiceName(serviceName);
    }

    protected Object executeTimeConsumingAction() {
      if (propertyManager != null) {
        return propertyManager.getProperties();
      }
      return null;
    }

    @SuppressWarnings({"unchecked"})
    protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction) {
      propertiesTableModel.update((Map<String, String>) resultOfTimeConsumingAction);
      viewPropertiesServiceComboBox.setEnabled(true);
    }
  }

  private class ErrorMessageDialogRunnable implements Runnable {
    private final String message;
    private final String title;

    private ErrorMessageDialogRunnable(final String message, final String title) {
      this.message = message;
      this.title = title;
    }

    public void run() {
      JOptionPane.showMessageDialog(
          PropertyInspector.this, message, title, JOptionPane.ERROR_MESSAGE);
    }
  }

  private class MyFocusTraversalPolicy extends FocusTraversalPolicy {
    public Component getComponentAfter(final Container container, final Component component) {
      if (component.equals(connectOrDisconnectButton)) {
        return getEnabledComponentAfter(container, createPropertyServiceComboBox);
      } else if (component.equals(createPropertyServiceComboBox)) {
        return getEnabledComponentAfter(container, propertyKeyTextField);
      } else if (component.equals(propertyKeyTextField)) {
        return getEnabledComponentAfter(container, propertyValueTextField);
      } else if (component.equals(propertyValueTextField)) {
        return getEnabledComponentAfter(container, createPropertyButton);
      } else if (component.equals(createPropertyButton)) {
        return getEnabledComponentAfter(container, viewPropertiesServiceComboBox);
      } else if (component.equals(viewPropertiesServiceComboBox)) {
        return getEnabledComponentAfter(container, reloadPropertiesButton);
      } else if (component.equals(reloadPropertiesButton)) {
        return getEnabledComponentAfter(container, connectOrDisconnectButton);
      }
      return null;
    }

    public Component getComponentBefore(final Container container, final Component component) {
      if (component.equals(connectOrDisconnectButton)) {
        return getEnabledComponentBefore(container, reloadPropertiesButton);
      } else if (component.equals(createPropertyServiceComboBox)) {
        return getEnabledComponentBefore(container, connectOrDisconnectButton);
      } else if (component.equals(propertyKeyTextField)) {
        return getEnabledComponentBefore(container, createPropertyServiceComboBox);
      } else if (component.equals(propertyValueTextField)) {
        return getEnabledComponentBefore(container, propertyKeyTextField);
      } else if (component.equals(createPropertyButton)) {
        return getEnabledComponentBefore(container, propertyValueTextField);
      } else if (component.equals(viewPropertiesServiceComboBox)) {
        return getEnabledComponentBefore(container, createPropertyButton);
      } else if (component.equals(reloadPropertiesButton)) {
        return getEnabledComponentBefore(container, viewPropertiesServiceComboBox);
      }
      return null;
    }

    private Component getEnabledComponentAfter(
        final Container container, final Component component) {
      return (component.isEnabled() ? component : getComponentAfter(container, component));
    }

    private Component getEnabledComponentBefore(
        final Container container, final Component component) {
      return (component.isEnabled() ? component : getComponentBefore(container, component));
    }

    public Component getFirstComponent(final Container container) {
      return connectOrDisconnectButton;
    }

    public Component getLastComponent(final Container container) {
      return createPropertyButton;
    }

    public Component getDefaultComponent(final Container container) {
      return connectOrDisconnectButton;
    }
  }
}
  private PropertyInspector() {
    super(APPLICATION_NAME, ICE_RELAY_PROPERTIES_FILE, ICE_DIRECT_CONNECT_PROPERTIES_FILE);
    setGUIClientHelperEventHandler(
        new GUIClientHelperEventHandlerAdapter() {
          public void executeAfterEstablishingConnectionToQwerk(final String qwerkUserId) {
            updateViewPropertiesTable();
          }

          public void toggleGUIElementState(final boolean isEnabled) {
            toggleGUIElements(isEnabled);
          }
        });

    // CONFIGURE GUI ELEMENTS
    // ========================================================================================

    this.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
    createPropertyButton.addActionListener(new CreatePropertyAction());
    final Map<String, String> tempServiceNameToTypeIdMap = new HashMap<String, String>();
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_ANALOG, AnalogInputsService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_AUDIO, AudioService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_IN, DigitalInService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_DIGITAL_OUT, DigitalOutService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_LED, LEDService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_MOTOR, BackEMFMotorService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERIAL, SerialIOService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_SERVO, ServoService.TYPE_ID);
    tempServiceNameToTypeIdMap.put(SERVICE_NAME_VIDEO, VideoStreamService.TYPE_ID);
    serviceNameToTypeIdMap = Collections.unmodifiableMap(tempServiceNameToTypeIdMap);

    viewPropertiesServiceComboBox.addItemListener(
        new ItemListener() {
          public void itemStateChanged(final ItemEvent itemEvent) {
            updateViewPropertiesTable();
          }
        });

    reloadPropertiesButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent actionEvent) {
            updateViewPropertiesTable();
          }
        });

    final JScrollPane propertiesTableScrollPane = new JScrollPane(propertiesTable);
    propertiesTableScrollPane.setMinimumSize(TABLE_DIMENSIONS);
    propertiesTableScrollPane.setMaximumSize(TABLE_DIMENSIONS);
    propertiesTableScrollPane.setPreferredSize(TABLE_DIMENSIONS);

    toggleGUIElements(false);
    propertyKeyTextField.addKeyListener(propertyKeyKeyListener);

    // LAYOUT GUI ELEMENTS
    // ===========================================================================================

    // create a panel to hold the connect/disconnect button and the connection state labels
    final JPanel connectionPanel = new JPanel(new SpringLayout());
    connectionPanel.add(connectOrDisconnectButton);
    connectionPanel.add(getConnectionStatePanel());
    SpringLayoutUtilities.makeCompactGrid(
        connectionPanel,
        1,
        2, // rows, cols
        0,
        0, // initX, initY
        10,
        10); // xPad, yPad

    final JPanel createPropertyPanel = new JPanel(new SpringLayout());
    createPropertyPanel.setBorder(
        BorderFactory.createTitledBorder(RESOURCES.getString("border.title.create-property")));
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service")));
    createPropertyPanel.add(createPropertyServiceComboBox);
    createPropertyPanel.add(createPropertyButton);
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.key")));
    createPropertyPanel.add(propertyKeyTextField);
    createPropertyPanel.add(Box.createGlue());
    createPropertyPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.value")));
    createPropertyPanel.add(propertyValueTextField);
    createPropertyPanel.add(Box.createGlue());
    SpringLayoutUtilities.makeCompactGrid(
        createPropertyPanel,
        3,
        3, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    final JPanel serviceChooserPanel = new JPanel(new SpringLayout());
    serviceChooserPanel.add(GUIConstants.createLabel(RESOURCES.getString("label.service")));
    serviceChooserPanel.add(viewPropertiesServiceComboBox);
    serviceChooserPanel.add(reloadPropertiesButton);
    SpringLayoutUtilities.makeCompactGrid(
        serviceChooserPanel,
        1,
        3, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    final JPanel viewPropertiesPanel = new JPanel(new SpringLayout());
    viewPropertiesPanel.setBorder(
        BorderFactory.createTitledBorder(RESOURCES.getString("border.title.view-propertes")));
    viewPropertiesPanel.add(serviceChooserPanel);
    viewPropertiesPanel.add(propertiesTableScrollPane);
    SpringLayoutUtilities.makeCompactGrid(
        viewPropertiesPanel,
        2,
        1, // rows, cols
        5,
        5, // initX, initY
        5,
        5); // xPad, yPad

    // Layout the main content pane using SpringLayout
    getMainContentPane().setLayout(new SpringLayout());
    getMainContentPane().add(connectionPanel);
    getMainContentPane().add(createPropertyPanel);
    getMainContentPane().add(viewPropertiesPanel);
    SpringLayoutUtilities.makeCompactGrid(
        getMainContentPane(),
        3,
        1, // rows, cols
        10,
        10, // initX, initY
        10,
        10); // xPad, yPad

    pack();
    setLocationRelativeTo(null); // center the window on the screen
    setVisible(true);
  }
Пример #30
0
 static {
   try {
     InputStream fis = UpmpConfig.class.getClassLoader().getResourceAsStream(CONF_FILE_NAME);
     PropertyResourceBundle props = new PropertyResourceBundle(fis);
     version = props.getString(KEY_VERSION);
     encoding = props.getString(KEY_ENCODING);
     signMethod = props.getString(KEY_SIGN_METHOD);
     txnType = props.getString(KEY_TXN_TYPE);
     txnSubType = props.getString(KEY_TXN_SUBTYPE);
     bizType = props.getString(KEY_BIZ_TYPE);
     channelType = props.getString(KEY_CHANNEL_TYPE);
     frontUrl = props.getString(KEY_FRONT_URL);
     backUrl = props.getString(KEY_BACK_URL);
     accessType = props.getString(KEY_ACCESS_TYPE);
     merId = props.getString(KEY_MERID);
     currencyCode = props.getString(KEY_CURRENCY_CODE);
     accType = props.getString(KEY_ACCTYPE);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }