コード例 #1
0
ファイル: Plotter.java プロジェクト: susotajuraj/jdk8u-jdk
    @Override
    public String getAccessibleName() {
      String name = super.getAccessibleName();

      if (seqs.size() > 0 && seqs.get(0).size > 0) {
        String keyValueList = "";
        for (Sequence seq : seqs) {
          if (seq.isPlotted) {
            String value = "null";
            if (seq.size > 0) {
              if (unit == Unit.BYTES) {
                value = Resources.format(Messages.SIZE_BYTES, seq.value(seq.size - 1));
              } else {
                value =
                    getFormattedValue(seq.value(seq.size - 1), false)
                        + ((unit == Unit.PERCENT) ? "%" : "");
              }
            }
            // Assume format string ends with newline
            keyValueList +=
                Resources.format(Messages.PLOTTER_ACCESSIBLE_NAME_KEY_AND_VALUE, seq.key, value);
          }
        }
        name += "\n" + keyValueList + ".";
      } else {
        name += "\n" + Messages.PLOTTER_ACCESSIBLE_NAME_NO_DATA;
      }
      return name;
    }
コード例 #2
0
ファイル: Plotter.java プロジェクト: susotajuraj/jdk8u-jdk
  @Override
  public JPopupMenu getComponentPopupMenu() {
    if (popupMenu == null) {
      popupMenu = new JPopupMenu(Messages.CHART_COLON);
      timeRangeMenu = new JMenu(Messages.PLOTTER_TIME_RANGE_MENU);
      timeRangeMenu.setMnemonic(Resources.getMnemonicInt(Messages.PLOTTER_TIME_RANGE_MENU));
      popupMenu.add(timeRangeMenu);
      menuRBs = new JRadioButtonMenuItem[rangeNames.length];
      ButtonGroup rbGroup = new ButtonGroup();
      for (int i = 0; i < rangeNames.length; i++) {
        menuRBs[i] = new JRadioButtonMenuItem(rangeNames[i]);
        rbGroup.add(menuRBs[i]);
        menuRBs[i].addActionListener(this);
        if (viewRange == rangeValues[i]) {
          menuRBs[i].setSelected(true);
        }
        timeRangeMenu.add(menuRBs[i]);
      }

      popupMenu.addSeparator();

      saveAsMI = new JMenuItem(Messages.PLOTTER_SAVE_AS_MENU_ITEM);
      saveAsMI.setMnemonic(Resources.getMnemonicInt(Messages.PLOTTER_SAVE_AS_MENU_ITEM));
      saveAsMI.addActionListener(this);
      popupMenu.add(saveAsMI);
    }
    return popupMenu;
  }
コード例 #3
0
ファイル: GraphicMaster.java プロジェクト: oshogbo/Memo
  public static Bitmap[] load(String src, int width, int height) {
    Bitmap[] texture = null;
    InputStream is = null;
    AssetManager am = resources.getAssets();
    String[] nameOfBoxs = null;

    try {
      nameOfBoxs = am.list(src);
    } catch (IOException e) {
      Log.d("GraphicMaster", "Culd not find folder " + src);
    }

    Log.d("GraphicMaster", "NameOfBoxs.length = " + nameOfBoxs.length);
    texture = new Bitmap[nameOfBoxs.length];

    for (int i = 0; i < nameOfBoxs.length; i++) {
      try {
        is = resources.getAssets().open(src + "/" + nameOfBoxs[i]);

        texture[i] = BitmapFactory.decodeStream(is);

        /*	if(width > 0 && height > 0)
        texture[i] = Bitmap.createScaledBitmap(texture[i], width, height, false);*/

        Log.d(
            "GraphicMaster",
            "Scaled from "
                + new Integer((int) (texture[i].getWidth())).toString()
                + " "
                + new Integer((int) (texture[i].getHeight())).toString()
                + " to "
                + new Integer((int) (texture[i].getWidth() * GameSettings.widthM)).toString()
                + " "
                + new Integer((int) (GameSettings.heightM * texture[i].getWidth())).toString());

        Log.d(
            "GraphicMaster",
            "Scale"
                + new Double(GameSettings.widthM).toString()
                + " "
                + new Double(GameSettings.heightM).toString());

        if (GameSettings.widthM != 1 && GameSettings.heightM != 1)
          texture[i] =
              Bitmap.createScaledBitmap(
                  texture[i],
                  (int) (texture[i].getWidth() * GameSettings.widthM),
                  (int) (texture[i].getHeight() * GameSettings.heightM),
                  false);

      } catch (IOException e) {
        Log.d("GraphicMaster", "Culd not read: " + src + nameOfBoxs[i]);
      }
    }

    return texture;
  }
コード例 #4
0
  private void setupHomeDir(String homeString) {
    if (homeString == null) {
      homeString = sysProps.getProperty("swingri.home");
    }

    if (homeString != null) {
      dataDir = new File(homeString);
    } else {
      userHome = new File(sysProps.getProperty("user.home"));
      String dataDirStr = props.getString("application.datadir", DEFAULT_HOME_DIR);
      dataDir = new File(userHome, dataDirStr);
    }

    if (!dataDir.isDirectory()) {
      String path = dataDir.getAbsolutePath();
      boolean create;
      if (props.hasUserRejectedCreatingLocalDataDir()) {
        create = false;
      } else if (getBoolean("application.showLocalStorageDialogs", true)) {
        create =
            Resources.showConfirmDialog(
                null,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.createNewDirectory",
                path);
        if (!create) props.setUserRejectedCreatingLocalDataDir();
      } else {
        // Always create local-storage directory if show user prompt dialog setting is false.
        create = true;
      }

      if (!create) {
        dataDir = null;
      } else {
        dataDir.mkdirs();
        if (!dataDir.isDirectory()) {
          // check to make sure that dialog should be shown on the error.
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.failedCreation",
                dataDir.getAbsolutePath());
          }
          dataDir = null;
        }
      }
    }
  }
コード例 #5
0
  private boolean setupDefaultProperties() {
    fontProps = new Properties();

    // create program properties with default
    try {
      // If you application needs to look at other font directories
      // they can be added via the readSystemFonts method.
      fontManager.readSystemFonts(null);
      fontProps = fontManager.getFontProperties();

    } catch (Exception ex) {
      if (getBoolean("application.showLocalStorageDialogs", true)) {
        Resources.showMessageDialog(
            null,
            JOptionPane.ERROR_MESSAGE,
            messageBundle,
            "fontManager.properties.title",
            "manager.properties.session.readError",
            ex);
      } // log the error
      if (logger.isLoggable(Level.WARNING)) {
        logger.log(Level.WARNING, "Error loading default properties", ex);
      }
      return false;
    }
    return true;
  }
コード例 #6
0
 public synchronized void saveProperties() {
   if (ownLock()) {
     try {
       FileOutputStream out = new FileOutputStream(propertyFile);
       try {
         fontProps.store(out, "-- ICEpf Font properties --");
       } finally {
         out.close();
       }
       recordMofifTime();
     } catch (IOException ex) {
       // check to make sure the storage relate dialogs can be shown
       if (getBoolean("application.showLocalStorageDialogs", true)) {
         Resources.showMessageDialog(
             null,
             JOptionPane.ERROR_MESSAGE,
             messageBundle,
             "fontManager.properties.title",
             "manager.properties.saveError",
             ex);
       }
       // log the error
       if (logger.isLoggable(Level.WARNING)) {
         logger.log(Level.WARNING, "Error saving font properties cache", ex);
       }
     }
   }
 }
コード例 #7
0
ファイル: Template.java プロジェクト: ndeloof/code-story-http
 public Template(String uri) {
   Path existing = Resources.findExistingPath(uri);
   if (existing == null) {
     throw new IllegalArgumentException("Template not found " + uri);
   }
   this.path = existing;
 }
コード例 #8
0
ファイル: List.java プロジェクト: JohnLeM/basex
  /**
   * Lists resources of the specified database.
   *
   * @return success flag
   * @throws IOException I/O exception
   */
  private boolean listDB() throws IOException {
    final String db = args[0];
    final String path = args[1] != null ? args[1] : "";
    if (!Databases.validName(db)) return error(NAME_INVALID_X, db);

    final Table table = new Table();
    table.description = RESOURCES;
    table.header.add(INPUT_PATH);
    table.header.add(TYPE);
    table.header.add(MimeTypes.CONTENT_TYPE);
    table.header.add(SIZE);

    try {
      // add xml documents
      final Data data = Open.open(db, context);
      final Resources res = data.resources;
      final IntList il = res.docs(path);
      final int ds = il.size();
      for (int i = 0; i < ds; i++) {
        final int pre = il.get(i);
        final TokenList tl = new TokenList(3);
        final byte[] file = data.text(pre, true);
        tl.add(file);
        tl.add(DataText.M_XML);
        tl.add(MimeTypes.APP_XML);
        tl.add(data.size(pre, Data.DOC));
        table.contents.add(tl);
      }
      // add binary resources
      for (final byte[] file : res.binaries(path)) {
        final String f = string(file);
        final TokenList tl = new TokenList(3);
        tl.add(file);
        tl.add(DataText.M_RAW);
        tl.add(MimeTypes.get(f));
        tl.add(data.meta.binary(f).length());
        table.contents.add(tl);
      }
      Close.close(data, context);
    } catch (final IOException ex) {
      return error(Util.message(ex));
    }
    out.println(table.sort().finish());
    return true;
  }
コード例 #9
0
  @Test
  @SuppressWarnings("unchecked")
  public void parse_object() throws IOException {
    List<Object> members =
        (List<Object>) parser.parse(resources.sourceFile(Paths.get("_data", "members.yml")));

    assertThat(members).hasSize(3);
    assertThat((Map<String, Object>) members.get(0))
        .containsExactly(entry("name", "Tom Preston-Werner"), entry("github", "mojombo"));
  }
コード例 #10
0
  /** The default constructor for the SSH protocol provider. */
  public ProtocolProviderServiceSSHImpl() {
    logger.trace("Creating a ssh provider.");

    try {
      // converting to milliseconds
      connectionTimeout = Integer.parseInt(Resources.getString("connectionTimeout")) * 1000;
    } catch (NumberFormatException ex) {
      logger.error("Connection Timeout set to 30 seconds");
    }
  }
コード例 #11
0
ファイル: Plotter.java プロジェクト: susotajuraj/jdk8u-jdk
  private void saveDataToFile(File file) {
    try {
      PrintStream out = new PrintStream(new FileOutputStream(file));

      // Print header line
      out.print("Time");
      for (Sequence seq : seqs) {
        out.print("," + seq.name);
      }
      out.println();

      // Print data lines
      if (seqs.size() > 0 && seqs.get(0).size > 0) {
        for (int i = 0; i < seqs.get(0).size; i++) {
          double excelTime = toExcelTime(times.time(i));
          out.print(String.format(Locale.ENGLISH, "%.6f", excelTime));
          for (Sequence seq : seqs) {
            out.print("," + getFormattedValue(seq.value(i), false));
          }
          out.println();
        }
      }

      out.close();
      JOptionPane.showMessageDialog(
          this,
          Resources.format(
              Messages.FILE_CHOOSER_SAVED_FILE, file.getAbsolutePath(), file.length()));
    } catch (IOException ex) {
      String msg = ex.getLocalizedMessage();
      String path = file.getAbsolutePath();
      if (msg.startsWith(path)) {
        msg = msg.substring(path.length()).trim();
      }
      JOptionPane.showMessageDialog(
          this,
          Resources.format(Messages.FILE_CHOOSER_SAVE_FAILED_MESSAGE, path, msg),
          Messages.FILE_CHOOSER_SAVE_FAILED_TITLE,
          JOptionPane.ERROR_MESSAGE);
    }
  }
コード例 #12
0
  public synchronized void loadProperties() {

    if (dataDir != null) {
      propertyFile = new File(dataDir, USER_FILENAME);
      // load font properties from last invocation
      if (propertyFile.exists()) {
        try {
          InputStream in = new FileInputStream(propertyFile);
          try {
            fontProps.load(in);
            fontManager.setFontProperties(fontProps);
          } finally {
            in.close();
          }
        } catch (IOException ex) {
          // check to make sure the storage relate dialogs can be shown
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.session.readError",
                ex);
          }
          // log the error
          if (logger.isLoggable(Level.WARNING)) {
            logger.log(Level.WARNING, "Error loading font properties cache", ex);
          }
        } catch (IllegalArgumentException e) {
          // propblem parsing fontProps, reread teh file
          setupDefaultProperties();
          saveProperties();
        }
      }
      // If no font data, then read font data and save the new file.
      else {
        setupDefaultProperties();
        saveProperties();
      }
    }
  }
コード例 #13
0
ファイル: SummaryTab.java プロジェクト: summerpulse/openjdk7
    public void updateCPUInfo(Result result) {
      if (prevUpTime > 0L && result.upTime > prevUpTime) {
        // elapsedCpu is in ns and elapsedTime is in ms.
        long elapsedCpu = result.processCpuTime - prevProcessCpuTime;
        long elapsedTime = result.upTime - prevUpTime;
        // cpuUsage could go higher than 100% because elapsedTime
        // and elapsedCpu are not fetched simultaneously. Limit to
        // 99% to avoid Plotter showing a scale from 0% to 200%.
        float cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * result.nCPUs));

        getPlotter()
            .addValues(result.timeStamp, Math.round(cpuUsage * Math.pow(10.0, CPU_DECIMALS)));
        getInfoLabel()
            .setText(
                Resources.format(
                    Messages.CPU_USAGE_FORMAT, String.format("%." + CPU_DECIMALS + "f", cpuUsage)));
      }
      this.prevUpTime = result.upTime;
      this.prevProcessCpuTime = result.processCpuTime;
    }
コード例 #14
0
ファイル: Plotter.java プロジェクト: susotajuraj/jdk8u-jdk
    @Override
    public void approveSelection() {
      File file = getSelectedFile();
      if (file != null) {
        FileFilter filter = getFileFilter();
        if (filter != null && filter instanceof FileNameExtensionFilter) {
          String[] extensions = ((FileNameExtensionFilter) filter).getExtensions();

          boolean goodExt = false;
          for (String ext : extensions) {
            if (file.getName().toLowerCase().endsWith("." + ext.toLowerCase())) {
              goodExt = true;
              break;
            }
          }
          if (!goodExt) {
            file = new File(file.getParent(), file.getName() + "." + extensions[0]);
          }
        }

        if (file.exists()) {
          String okStr = Messages.FILE_CHOOSER_FILE_EXISTS_OK_OPTION;
          String cancelStr = Messages.FILE_CHOOSER_FILE_EXISTS_CANCEL_OPTION;
          int ret =
              JOptionPane.showOptionDialog(
                  this,
                  Resources.format(Messages.FILE_CHOOSER_FILE_EXISTS_MESSAGE, file.getName()),
                  Messages.FILE_CHOOSER_FILE_EXISTS_TITLE,
                  JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.WARNING_MESSAGE,
                  null,
                  new Object[] {okStr, cancelStr},
                  okStr);
          if (ret != JOptionPane.OK_OPTION) {
            return;
          }
        }
        setSelectedFile(file);
      }
      super.approveSelection();
    }
コード例 #15
0
  private void setupLock() {
    if (dataDir == null) {
      lockDir = null;
    } else {
      File dir = new File(dataDir, LOCK_FILE);
      if (!dir.mkdir()) {

        dir.delete();
        if (!dir.mkdir()) {
          dir = null;
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.session.nolock",
                LOCK_FILE);
          }
        }
      }
      lockDir = dir;
    }
  }
コード例 #16
0
/**
 * A SSH implementation of the ProtocolProviderService.
 *
 * @author Shobhit Jindal
 */
public class ProtocolProviderServiceSSHImpl implements ProtocolProviderService {
  private static final Logger logger = Logger.getLogger(ProtocolProviderServiceSSHImpl.class);

  /** The name of this protocol. */
  public static final String SSH_PROTOCOL_NAME = ProtocolNames.SSH;

  //    /**
  //     * The identifier for SSH Stack
  //     * Java Secure Channel JSch
  //     */
  //    JSch jsch = new JSch();

  /** The test command given after each command to determine the reply length of the command */
  private final String testCommand = Resources.getString("testCommand");

  /** A reference to the protocol provider of UIService */
  private static ServiceReference ppUIServiceRef;

  /** Connection timeout to a remote server in milliseconds */
  private static int connectionTimeout = 30000;

  /** A reference to UI Service */
  private static UIService uiService;

  /** The id of the account that this protocol provider represents. */
  private AccountID accountID = null;

  /** We use this to lock access to initialization. */
  private Object initializationLock = new Object();

  /** The hashtable with the operation sets that we support locally. */
  private final Hashtable supportedOperationSets = new Hashtable();

  private OperationSetBasicInstantMessagingSSHImpl basicInstantMessaging;

  private OperationSetFileTransferSSHImpl fileTranfer;

  /** A list of listeners interested in changes in our registration state. */
  private Vector registrationStateListeners = new Vector();

  /** Indicates whether or not the provider is initialized and ready for use. */
  private boolean isInitialized = false;

  /** The logo corresponding to the ssh protocol. */
  private ProtocolIconSSHImpl sshIcon = new ProtocolIconSSHImpl();

  /**
   * The registration state of SSH Provider is taken to be registered by default as it doesn't
   * correspond to the state on remote server
   */
  private RegistrationState currentRegistrationState = RegistrationState.REGISTERED;

  /** The default constructor for the SSH protocol provider. */
  public ProtocolProviderServiceSSHImpl() {
    logger.trace("Creating a ssh provider.");

    try {
      // converting to milliseconds
      connectionTimeout = Integer.parseInt(Resources.getString("connectionTimeout")) * 1000;
    } catch (NumberFormatException ex) {
      logger.error("Connection Timeout set to 30 seconds");
    }
  }

  /**
   * Initializes the service implementation, and puts it in a sate where it could interoperate with
   * other services. It is strongly recomended that properties in this Map be mapped to property
   * names as specified by <tt>AccountProperties</tt>.
   *
   * @param userID the user id of the ssh account we're currently initializing
   * @param accountID the identifier of the account that this protocol provider represents.
   * @see net.java.sip.communicator.service.protocol.AccountID
   */
  protected void initialize(String userID, AccountID accountID) {
    synchronized (initializationLock) {
      this.accountID = accountID;

      // initialize the presence operationset
      OperationSetPersistentPresenceSSHImpl persistentPresence =
          new OperationSetPersistentPresenceSSHImpl(this);

      supportedOperationSets.put(
          OperationSetPersistentPresence.class.getName(), persistentPresence);

      // register it once again for those that simply need presence and
      // won't be smart enough to check for a persistent presence
      // alternative
      supportedOperationSets.put(OperationSetPresence.class.getName(), persistentPresence);

      // initialize the IM operation set
      basicInstantMessaging = new OperationSetBasicInstantMessagingSSHImpl(this);

      supportedOperationSets.put(
          OperationSetBasicInstantMessaging.class.getName(), basicInstantMessaging);

      // initialze the file transfer operation set
      fileTranfer = new OperationSetFileTransferSSHImpl(this);

      supportedOperationSets.put(OperationSetFileTransfer.class.getName(), fileTranfer);

      isInitialized = true;
    }
  }

  /**
   * Determines whether a vaild session exists for the contact of remote machine.
   *
   * @param sshContact ID of SSH Contact
   * @return <tt>true</tt> if the session is connected <tt>false</tt> otherwise
   */
  public boolean isSessionValid(ContactSSH sshContact) {
    Session sshSession = sshContact.getSSHSession();
    if (sshSession != null) if (sshSession.isConnected()) return true;

    // remove reference to an unconnected SSH Session, if any
    sshContact.setSSHSession(null);
    return false;
  }

  /**
   * Determines whether the contact is connected to shell of remote machine as a precheck for any
   * further operation
   *
   * @param sshContact ID of SSH Contact
   * @return <tt>true</tt> if the contact is connected <tt>false</tt> if the contact is not
   *     connected
   */
  public boolean isShellConnected(ContactSSH sshContact) {
    // a test command may also be run here

    if (isSessionValid(sshContact)) {
      return (sshContact.getShellChannel() != null);
    }

    /*
     * Above should be return(sshContact.getShellChannel() != null
     *                     && sshContact.getShellChannel().isConnected());
     *
     * but incorrect reply from stack for isConnected()
     */

    return false;
  }

  /**
   * Creates a shell channel to the remote machine a new jsch session is also created if the current
   * one is invalid
   *
   * @param sshContact the contact of the remote machine
   * @param firstMessage the first message
   */
  public void connectShell(final ContactSSH sshContact, final Message firstMessage) {
    sshContact.setConnectionInProgress(true);

    final UIService uiService = this.uiService;

    final Thread newConnection =
        new Thread(
            (new Runnable() {
              public void run() {
                OperationSetPersistentPresenceSSHImpl persistentPresence =
                    (OperationSetPersistentPresenceSSHImpl)
                        sshContact.getParentPresenceOperationSet();

                persistentPresence.changeContactPresenceStatus(
                    sshContact, SSHStatusEnum.CONNECTING);

                try {
                  if (!isSessionValid(sshContact)) createSSHSessionAndLogin(sshContact);

                  createShellChannel(sshContact);

                  // initalizing the reader and writers of ssh contact

                  persistentPresence.changeContactPresenceStatus(
                      sshContact, SSHStatusEnum.CONNECTED);

                  showWelcomeMessage(sshContact);

                  sshContact.setMessageType(sshContact.CONVERSATION_MESSAGE_RECEIVED);

                  sshContact.setConnectionInProgress(false);

                  Thread.sleep(1500);

                  sshContact.setCommandSent(true);

                  basicInstantMessaging.sendInstantMessage(sshContact, firstMessage);
                }
                // rigoruos Exception Checking in future
                catch (Exception ex) {
                  persistentPresence.changeContactPresenceStatus(
                      sshContact, SSHStatusEnum.NOT_AVAILABLE);

                  ex.printStackTrace();
                } finally {
                  sshContact.setConnectionInProgress(false);
                }
              }
            }));

    newConnection.start();
  }

  /**
   * Creates a channel for shell type in the current session channel types = shell, sftp, exec(X
   * forwarding), direct-tcpip(stream forwarding) etc
   *
   * @param sshContact ID of SSH Contact
   */
  public void createShellChannel(ContactSSH sshContact) throws IOException {
    try {
      Channel shellChannel = sshContact.getSSHSession().openChannel("shell");

      // initalizing the reader and writers of ssh contact
      sshContact.initializeShellIO(shellChannel.getInputStream(), shellChannel.getOutputStream());

      ((ChannelShell) shellChannel)
          .setPtyType(sshContact.getSSHConfigurationForm().getTerminalType());

      // initializing the shell
      shellChannel.connect(1000);

      sshContact.setShellChannel(shellChannel);

      sshContact.sendLine("export PS1=");
    } catch (JSchException ex) {
      sshContact.setSSHSession(null);
      throw new IOException("Unable to create shell channel to remote" + " server");
    }
  }

  /**
   * Closes the Shell channel are associated IO Streams
   *
   * @param sshContact ID of SSH Contact
   */
  public void closeShellChannel(ContactSSH sshContact) throws JSchException, IOException {
    sshContact.closeShellIO();
    sshContact.getShellChannel().disconnect();
    sshContact.setShellChannel(null);
  }

  /**
   * Creates a SSH Session with a remote machine and tries to login according to the details
   * specified by Contact An appropriate message is shown to the end user in case the login fails
   *
   * @param sshContact ID of SSH Contact
   * @throws JSchException if a JSch is unable to create a SSH Session with the remote machine
   * @throws InterruptedException if the thread is interrupted before session connected or is timed
   *     out
   * @throws OperationFailedException if not of above reasons :-)
   */
  public void createSSHSessionAndLogin(ContactSSH sshContact)
      throws JSchException, OperationFailedException, InterruptedException {
    logger.info("Creating a new SSH Session to " + sshContact.getHostName());

    // creating a new JSch Stack identifier for contact
    JSch jsch = new JSch();

    String knownHosts = (String) accountID.getAccountProperties().get("KNOWN_HOSTS_FILE");

    if (!knownHosts.equals("Optional")) jsch.setKnownHosts(knownHosts);

    String identitiyKey = (String) accountID.getAccountProperties().get("IDENTITY_FILE");

    String userName = sshContact.getUserName();

    // use the name of system user if the contact has not supplied SSH
    // details
    if (userName.equals("")) userName = System.getProperty("user.name");

    if (!identitiyKey.equals("Optional")) jsch.addIdentity(identitiyKey);

    // creating a new session for the contact
    Session session =
        jsch.getSession(
            userName, sshContact.getHostName(), sshContact.getSSHConfigurationForm().getPort());

    /**
     * Creating and associating User Info with the session User Info passes authentication from
     * sshContact to SSH Stack
     */
    SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact);

    session.setUserInfo(sshUserInfo);

    /** initializing the session */
    session.connect(connectionTimeout);

    int count = 0;

    // wait for session to get connected
    while (!session.isConnected() && count <= 30000) {
      Thread.sleep(1000);
      count += 1000;
      logger.trace("SSH:" + sshContact.getHostName() + ": Sleep zzz .. ");
    }

    // if timeout have exceeded
    if (count > 30000) {
      sshContact.setSSHSession(null);
      JOptionPane.showMessageDialog(
          null, "SSH Connection attempt to " + sshContact.getHostName() + " timed out");

      // error codes are not defined yet
      throw new OperationFailedException(
          "SSH Connection attempt to " + sshContact.getHostName() + " timed out", 2);
    }

    sshContact.setJSch(jsch);
    sshContact.setSSHSession(session);

    logger.info("A new SSH Session to " + sshContact.getHostName() + " Created");
  }

  /**
   * Closes the SSH Session associated with the contact
   *
   * @param sshContact ID of SSH Contact
   */
  void closeSSHSession(ContactSSH sshContact) {
    sshContact.getSSHSession().disconnect();
    sshContact.setSSHSession(null);
  }

  /**
   * Presents the login welcome message to user
   *
   * @param sshContact ID of SSH Contact
   */
  public void showWelcomeMessage(ContactSSH sshContact) throws IOException {
    /*      //sending the command
            sshContact.sendLine(testCommand);

            String reply = "", line = "";

            // message is extracted until the test Command ie echoed back
            while(line.indexOf(testCommand) == -1)
            {
                reply += line + "\n";
                line = sshContact.getLine();
            }

            uiService.getPopupDialog().showMessagePopupDialog
                    (reply,"Message from " + sshContact.getDisplayName(),
                    uiService.getPopupDialog().INFORMATION_MESSAGE);

            if(line.startsWith(testCommand))
                while(!sshContact.getLine().contains(testCommand));

            //one line output of testCommand
            sshContact.getLine();
    */
    logger.debug("SSH: Welcome message shown");
  }

  /**
   * Returns a reference to UIServce for accessing UI related services
   *
   * @return uiService a reference to UIService
   */
  public static UIService getUIService() {
    return uiService;
  }

  /**
   * Registers the specified listener with this provider so that it would receive notifications on
   * changes of its state or other properties such as its local address and display name.
   *
   * @param listener the listener to register.
   */
  public void addRegistrationStateChangeListener(RegistrationStateChangeListener listener) {
    synchronized (registrationStateListeners) {
      if (!registrationStateListeners.contains(listener)) registrationStateListeners.add(listener);
    }
  }

  /**
   * Removes the specified registration listener so that it won't receive further notifications when
   * our registration state changes.
   *
   * @param listener the listener to remove.
   */
  public void removeRegistrationStateChangeListener(RegistrationStateChangeListener listener) {
    synchronized (registrationStateListeners) {
      registrationStateListeners.remove(listener);
    }
  }

  /**
   * Creates a <tt>RegistrationStateChangeEvent</tt> corresponding to the specified old and new
   * states and notifies all currently registered listeners.
   *
   * @param oldState the state that the provider had before the change occurred
   * @param newState the state that the provider is currently in.
   * @param reasonCode a value corresponding to one of the REASON_XXX fields of the
   *     RegistrationStateChangeEvent class, indicating the reason for this state transition.
   * @param reason a String further explaining the reason code or null if no such explanation is
   *     necessary.
   */
  private void fireRegistrationStateChanged(
      RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) {
    RegistrationStateChangeEvent event =
        new RegistrationStateChangeEvent(this, oldState, newState, reasonCode, reason);

    logger.debug(
        "Dispatching " + event + " to " + registrationStateListeners.size() + " listeners.");

    Iterator listeners = null;
    synchronized (registrationStateListeners) {
      listeners = new ArrayList(registrationStateListeners).iterator();
    }

    while (listeners.hasNext()) {
      RegistrationStateChangeListener listener = (RegistrationStateChangeListener) listeners.next();

      listener.registrationStateChanged(event);
    }

    logger.trace("Done.");
  }

  /**
   * Returns the AccountID that uniquely identifies the account represented by this instance of the
   * ProtocolProviderService.
   *
   * @return the id of the account represented by this provider.
   */
  public AccountID getAccountID() {
    return accountID;
  }

  /**
   * Returns the operation set corresponding to the specified class or null if this operation set is
   * not supported by the provider implementation.
   *
   * @param opsetClass the <tt>Class</tt> of the operation set that we're looking for.
   * @return returns an OperationSet of the specified <tt>Class</tt> if the undelying implementation
   *     supports it or null otherwise.
   */
  public OperationSet getOperationSet(Class opsetClass) {
    return (OperationSet) getSupportedOperationSets().get(opsetClass.getName());
  }

  /**
   * Returns the short name of the protocol that the implementation of this provider is based upon
   * (like SIP, Jabber, ICQ/AIM, or others for example).
   *
   * @return a String containing the short name of the protocol this service is implementing (most
   *     often that would be a name in ProtocolNames).
   */
  public String getProtocolName() {
    return SSH_PROTOCOL_NAME;
  }

  /**
   * Returns the protocol display name. This is the name that would be used by the GUI to display
   * the protocol name.
   *
   * @return a String containing the display name of the protocol this service is implementing
   */
  public String getProtocolDisplayName() {
    return SSH_PROTOCOL_NAME;
  }

  /**
   * Returns the state of the registration of this protocol provider with the corresponding
   * registration service.
   *
   * @return ProviderRegistrationState
   */
  public RegistrationState getRegistrationState() {
    return currentRegistrationState;
  }

  /**
   * Returns an array containing all operation sets supported by the current implementation.
   *
   * @return a java.util.Map containing instance of all supported operation sets mapped against
   *     their class names (e.g. OperationSetPresence.class.getName()) .
   */
  public Map getSupportedOperationSets() {
    // Copy the map so that the caller is not able to modify it.
    return (Map) supportedOperationSets.clone();
  }

  /**
   * Indicates whether or not this provider is registered
   *
   * @return true if the provider is currently registered and false otherwise.
   */
  public boolean isRegistered() {
    return currentRegistrationState.equals(RegistrationState.REGISTERED);
  }

  /**
   * Starts the registration process.
   *
   * @param authority the security authority that will be used for resolving any security challenges
   *     that may be returned during the registration or at any moment while wer're registered.
   * @throws OperationFailedException with the corresponding code it the registration fails for some
   *     reason (e.g. a networking error or an implementation problem).
   */
  public void register(SecurityAuthority authority) throws OperationFailedException {
    RegistrationState oldState = currentRegistrationState;
    currentRegistrationState = RegistrationState.REGISTERED;

    // get a reference to UI Service via its Service Reference
    ppUIServiceRef = SSHActivator.getBundleContext().getServiceReference(UIService.class.getName());

    uiService = (UIService) SSHActivator.getBundleContext().getService(ppUIServiceRef);

    fireRegistrationStateChanged(
        oldState, currentRegistrationState, RegistrationStateChangeEvent.REASON_USER_REQUEST, null);
  }

  /**
   * Makes the service implementation close all open sockets and release any resources that it might
   * have taken and prepare for shutdown/garbage collection.
   */
  public void shutdown() {
    if (!isInitialized) {
      return;
    }
    logger.trace("Killing the SSH Protocol Provider.");

    if (isRegistered()) {
      try {
        // do the unregistration
        unregister();
      } catch (OperationFailedException ex) {
        // we're shutting down so we need to silence the exception here
        logger.error("Failed to properly unregister before shutting down. " + getAccountID(), ex);
      }
    }

    isInitialized = false;
  }

  /**
   * Ends the registration of this protocol provider with the current registration service.
   *
   * @throws OperationFailedException with the corresponding code it the registration fails for some
   *     reason (e.g. a networking error or an implementation problem).
   */
  public void unregister() throws OperationFailedException {
    RegistrationState oldState = currentRegistrationState;
    currentRegistrationState = RegistrationState.UNREGISTERED;

    fireRegistrationStateChanged(
        oldState, currentRegistrationState, RegistrationStateChangeEvent.REASON_USER_REQUEST, null);
  }

  /**
   * Returns the ssh protocol icon.
   *
   * @return the ssh protocol icon
   */
  public ProtocolIcon getProtocolIcon() {
    return sshIcon;
  }
}
コード例 #17
0
ファイル: SummaryTab.java プロジェクト: summerpulse/openjdk7
  synchronized Result formatSummary() {
    Result result = new Result();
    ProxyClient proxyClient = vmPanel.getProxyClient();
    if (proxyClient.isDead()) {
      return null;
    }

    buf = new StringBuilder();
    append("<table cellpadding=1>");

    try {
      RuntimeMXBean rmBean = proxyClient.getRuntimeMXBean();
      CompilationMXBean cmpMBean = proxyClient.getCompilationMXBean();
      ThreadMXBean tmBean = proxyClient.getThreadMXBean();
      MemoryMXBean memoryBean = proxyClient.getMemoryMXBean();
      ClassLoadingMXBean clMBean = proxyClient.getClassLoadingMXBean();
      OperatingSystemMXBean osMBean = proxyClient.getOperatingSystemMXBean();
      com.sun.management.OperatingSystemMXBean sunOSMBean =
          proxyClient.getSunOperatingSystemMXBean();

      append("<tr><td colspan=4>");
      append("<center><b>" + Messages.SUMMARY_TAB_TAB_NAME + "</b></center>");
      String dateTime = headerDateTimeFormat.format(System.currentTimeMillis());
      append("<center>" + dateTime + "</center>");

      append(newDivider);

      { // VM info
        append(newLeftTable);
        append(Messages.CONNECTION_NAME, vmPanel.getDisplayName());
        append(
            Messages.VIRTUAL_MACHINE,
            Resources.format(
                Messages.SUMMARY_TAB_VM_VERSION, rmBean.getVmName(), rmBean.getVmVersion()));
        append(Messages.VENDOR, rmBean.getVmVendor());
        append(Messages.NAME, rmBean.getName());
        append(endTable);

        append(newRightTable);
        result.upTime = rmBean.getUptime();
        append(Messages.UPTIME, formatTime(result.upTime));
        if (sunOSMBean != null) {
          result.processCpuTime = sunOSMBean.getProcessCpuTime();
          append(Messages.PROCESS_CPU_TIME, formatNanoTime(result.processCpuTime));
        }

        if (cmpMBean != null) {
          append(Messages.JIT_COMPILER, cmpMBean.getName());
          append(
              Messages.TOTAL_COMPILE_TIME,
              cmpMBean.isCompilationTimeMonitoringSupported()
                  ? formatTime(cmpMBean.getTotalCompilationTime())
                  : Messages.UNAVAILABLE);
        } else {
          append(Messages.JIT_COMPILER, Messages.UNAVAILABLE);
        }
        append(endTable);
      }

      append(newDivider);

      { // Threads and Classes
        append(newLeftTable);
        int tlCount = tmBean.getThreadCount();
        int tdCount = tmBean.getDaemonThreadCount();
        int tpCount = tmBean.getPeakThreadCount();
        long ttCount = tmBean.getTotalStartedThreadCount();
        String[] strings1 =
            formatLongs(
                tlCount, tpCount,
                tdCount, ttCount);
        append(Messages.LIVE_THREADS, strings1[0]);
        append(Messages.PEAK, strings1[1]);
        append(Messages.DAEMON_THREADS, strings1[2]);
        append(Messages.TOTAL_THREADS_STARTED, strings1[3]);
        append(endTable);

        append(newRightTable);
        long clCount = clMBean.getLoadedClassCount();
        long cuCount = clMBean.getUnloadedClassCount();
        long ctCount = clMBean.getTotalLoadedClassCount();
        String[] strings2 = formatLongs(clCount, cuCount, ctCount);
        append(Messages.CURRENT_CLASSES_LOADED, strings2[0]);
        append(Messages.TOTAL_CLASSES_LOADED, strings2[2]);
        append(Messages.TOTAL_CLASSES_UNLOADED, strings2[1]);
        append(null, "");
        append(endTable);
      }

      append(newDivider);

      { // Memory
        MemoryUsage u = memoryBean.getHeapMemoryUsage();

        append(newLeftTable);
        String[] strings1 = formatKByteStrings(u.getUsed(), u.getMax());
        append(Messages.CURRENT_HEAP_SIZE, strings1[0]);
        append(Messages.MAXIMUM_HEAP_SIZE, strings1[1]);
        append(endTable);

        append(newRightTable);
        String[] strings2 = formatKByteStrings(u.getCommitted());
        append(Messages.COMMITTED_MEMORY, strings2[0]);
        append(
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_LABEL,
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_VALUE,
            memoryBean.getObjectPendingFinalizationCount());
        append(endTable);

        append(newTable);
        Collection<GarbageCollectorMXBean> garbageCollectors =
            proxyClient.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
          String gcName = garbageCollectorMBean.getName();
          long gcCount = garbageCollectorMBean.getCollectionCount();
          long gcTime = garbageCollectorMBean.getCollectionTime();

          append(
              Messages.GARBAGE_COLLECTOR,
              Resources.format(
                  Messages.GC_INFO,
                  gcName,
                  gcCount,
                  (gcTime >= 0) ? formatTime(gcTime) : Messages.UNAVAILABLE),
              4);
        }
        append(endTable);
      }

      append(newDivider);

      { // Operating System info
        append(newLeftTable);
        String osName = osMBean.getName();
        String osVersion = osMBean.getVersion();
        String osArch = osMBean.getArch();
        result.nCPUs = osMBean.getAvailableProcessors();
        append(Messages.OPERATING_SYSTEM, osName + " " + osVersion);
        append(Messages.ARCHITECTURE, osArch);
        append(Messages.NUMBER_OF_PROCESSORS, result.nCPUs + "");

        if (pathSeparator == null) {
          // Must use separator of remote OS, not File.pathSeparator
          // from this local VM. In the future, consider using
          // RuntimeMXBean to get the remote system property.
          pathSeparator = osName.startsWith("Windows ") ? ";" : ":";
        }

        if (sunOSMBean != null) {
          String[] kbStrings1 = formatKByteStrings(sunOSMBean.getCommittedVirtualMemorySize());

          String[] kbStrings2 =
              formatKByteStrings(
                  sunOSMBean.getTotalPhysicalMemorySize(),
                  sunOSMBean.getFreePhysicalMemorySize(),
                  sunOSMBean.getTotalSwapSpaceSize(),
                  sunOSMBean.getFreeSwapSpaceSize());

          append(Messages.COMMITTED_VIRTUAL_MEMORY, kbStrings1[0]);
          append(endTable);

          append(newRightTable);
          append(Messages.TOTAL_PHYSICAL_MEMORY, kbStrings2[0]);
          append(Messages.FREE_PHYSICAL_MEMORY, kbStrings2[1]);
          append(Messages.TOTAL_SWAP_SPACE, kbStrings2[2]);
          append(Messages.FREE_SWAP_SPACE, kbStrings2[3]);
        }

        append(endTable);
      }

      append(newDivider);

      { // VM arguments and paths
        append(newTable);
        String args = "";
        java.util.List<String> inputArguments = rmBean.getInputArguments();
        for (String arg : inputArguments) {
          args += arg + " ";
        }
        append(Messages.VM_ARGUMENTS, args, 4);
        append(Messages.CLASS_PATH, rmBean.getClassPath(), 4);
        append(Messages.LIBRARY_PATH, rmBean.getLibraryPath(), 4);
        append(
            Messages.BOOT_CLASS_PATH,
            rmBean.isBootClassPathSupported() ? rmBean.getBootClassPath() : Messages.UNAVAILABLE,
            4);
        append(endTable);
      }
    } catch (IOException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    } catch (UndeclaredThrowableException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    }

    append("</table>");

    result.timeStamp = System.currentTimeMillis();
    result.summary = buf.toString();

    return result;
  }