@Override
    public void connectController(String host, int port) {
      if (host == null) {
        host = defaultControllerHost;
      }

      if (port < 0) {
        port = defaultControllerPort;
      }

      try {
        ModelControllerClient newClient = ModelControllerClient.Factory.create(host, port);
        if (this.client != null) {
          disconnectController();
        }

        List<String> nodeTypes = Util.getNodeTypes(newClient, new DefaultOperationRequestAddress());
        if (!nodeTypes.isEmpty()) {
          domainMode = nodeTypes.contains("server-group");
          printLine(
              "Connected to "
                  + (domainMode ? "domain controller at " : "standalone controller at ")
                  + host
                  + ":"
                  + port);
          client = newClient;
          this.controllerHost = host;
          this.controllerPort = port;
        } else {
          printLine("The controller is not available at " + host + ":" + port);
        }
      } catch (UnknownHostException e) {
        printLine("Failed to resolve host '" + host + "': " + e.getLocalizedMessage());
      }
    }
Esempio n. 2
0
  // ============================================================================
  // ==
  public static String generateUUID(Object o) {
    StringBuffer tmpBuffer = new StringBuffer(16);
    if (hexServerIP_ == null) {
      InetAddress localInetAddress = null;
      try {
        // get the inet address
        localInetAddress = InetAddress.getLocalHost();
      } catch (java.net.UnknownHostException uhe) {
        // System .err .println(
        // "ContentSetUtil: Could not get the local IP address using InetAddress.getLocalHost()!"
        // );
        // todo: find better way to get around this...
        LOG.error(uhe.getLocalizedMessage(), uhe);
        return null;
      }
      byte serverIP[] = localInetAddress.getAddress();
      hexServerIP_ = hexFormat(getInt(serverIP), 8);
    }
    String hashcode = hexFormat(System.identityHashCode(o), 8);
    tmpBuffer.append(hexServerIP_);
    tmpBuffer.append(hashcode);

    long timeNow = System.currentTimeMillis();
    int timeLow = (int) timeNow & 0xFFFFFFFF;
    int node = seeder_.nextInt();

    StringBuffer guid = new StringBuffer(32);
    guid.append(hexFormat(timeLow, 8));
    guid.append(tmpBuffer.toString());
    guid.append(hexFormat(node, 8));
    return guid.toString();
  }
Esempio n. 3
0
  /**
   * Creates a {@link Connection} with {@link Connection.Modality#Synchronous} semantics suitable
   * for use by synchronous (blocking) JRedis clients.
   *
   * <p>[TODO: this method should be using connection spec!]
   *
   * @param host
   * @param port
   * @param redisVersion
   * @return
   */
  protected Connection createSynchConnection(String host, int port, RedisVersion redisVersion) {
    InetAddress address = null;
    Connection synchConnection = null;
    try {

      address = InetAddress.getByName(host);
      synchConnection = new SynchConnection(address, port, redisVersion);
      Assert.notNull(synchConnection, "connection delegate", ClientRuntimeException.class);
    } catch (NotSupportedException e) {
      Log.log("Can not support redis protocol '%s'", redisVersion);
      throw e;
    } catch (ProviderException e) {
      Log.bug("Couldn't create the handler delegate.  => " + e.getLocalizedMessage());
      throw e;
    } catch (ClientRuntimeException e) {
      String msg = e.getMessage() + "\nMake sure your server is running.";
      Log.error("Error creating connection -> " + e.getLocalizedMessage());
      setConnection(new FaultedConnection(msg));
    } catch (UnknownHostException e) {
      String msg = "Couldn't obtain InetAddress for " + host;
      Log.problem(msg + "  => " + e.getLocalizedMessage());
      throw new ClientRuntimeException(msg, e);
    }
    return synchConnection;
  }
Esempio n. 4
0
  static {
    if (NONPROXY_HOSTS.length() > 0) {
      StringTokenizer s = new StringTokenizer(NONPROXY_HOSTS, "|"); // $NON-NLS-1$
      while (s.hasMoreTokens()) {
        String t = s.nextToken();
        if (t.indexOf('*') == 0) { // e.g. *.apache.org // $NON-NLS-1$
          nonProxyHostSuffix.add(t.substring(1));
        } else {
          nonProxyHostFull.add(t); // e.g. www.apache.org
        }
      }
    }
    nonProxyHostSuffixSize = nonProxyHostSuffix.size();

    InetAddress inet = null;
    String localHostOrIP = JMeterUtils.getPropDefault("httpclient.localaddress", ""); // $NON-NLS-1$
    if (localHostOrIP.length() > 0) {
      try {
        inet = InetAddress.getByName(localHostOrIP);
        log.info("Using localAddress " + inet.getHostAddress());
      } catch (UnknownHostException e) {
        log.warn(e.getLocalizedMessage());
      }
    } else {
      // Get hostname
      localHostOrIP = JMeterUtils.getLocalHostName();
    }
    localAddress = inet;
    localHost = localHostOrIP;
    log.info("Local host = " + localHost);
  }
Esempio n. 5
0
    /**
     * For test Server Address if it available
     *
     * @param value String from Server Address form
     * @return OK if ping, ERROR otherwise
     */
    public FormValidation doCheckServerAddress(@QueryParameter String value) {

      try {

        if (value == null || value.matches("\\s*")) {
          return FormValidation.warning("Set Address");
        }

        if (value.startsWith("$")) {
          return FormValidation.ok();
        }

        new Socket(value, 22).close();

      } catch (UnknownHostException e) {
        return FormValidation.error("Unknown Host\t" + value + "\t" + e.getLocalizedMessage());
      } catch (IOException e) {
        return FormValidation.error(
            "Input Output Exception while connecting to \t"
                + value
                + "\t"
                + e.getLocalizedMessage());
      }
      return FormValidation.ok();
    }
 @Override
 public void actionPerformed(ActionEvent ev) {
   try {
     Conexao.getConexao()
         .conectarCliente(campoIP.getText(), Integer.parseInt(campoPorta.getText()));
   } catch (UnknownHostException ex) {
     atualizaStatusCl(ex.getLocalizedMessage());
   } catch (IOException ex) {
     atualizaStatusCl(ex.getLocalizedMessage());
   }
   Jogador.getJogador().setNome(campoNome.getText());
   Main.mostraConfigGrid();
 }
  protected void performRuntime(
      OperationContext context,
      ModelNode operation,
      ModelNode model,
      ServiceVerificationHandler verificationHandler,
      List<ServiceController<?>> newControllers)
      throws OperationFailedException {
    // Resolve any expressions and re-validate
    final ModelNode resolvedOp = operation.resolve();
    runtimeValidator.validate(resolvedOp);

    PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
    String name = address.getLastElement().getValue();

    try {
      newControllers.add(installBindingService(context, resolvedOp, name));
    } catch (UnknownHostException e) {
      throw new OperationFailedException(new ModelNode().set(e.getLocalizedMessage()));
    }
  }
Esempio n. 8
0
 /**
  * 指定のホスト/ポートに接続する。既に接続されている場合は切断、Socketの際生成を行う
  *
  * @param host
  * @param port
  * @return 成功時は0。失敗時は負の値
  */
 public int connect(String host, int port) {
   InetSocketAddress addr = new InetSocketAddress(host, port);
   try {
     if (clientSock != null && clientSock.isConnected()) {
       clientSock.close();
     }
     clientSock = new Socket();
     clientSock.connect(addr);
     // TODO: 接続が失われた際の再接続方法を考えておく必要がある
   } catch (SocketException e) {
     Log.d("moku99", e.getLocalizedMessage());
     return -1;
   } catch (UnknownHostException e) {
     Log.d("moku99", e.getLocalizedMessage());
     return -2;
   } catch (IOException e) {
     Log.d("moku99", e.getLocalizedMessage());
     return -3;
   }
   return 0;
 }
Esempio n. 9
0
 public void conectar() {
   try {
     this.socket = new Socket(this.host, this.PUERTO);
     this.isEntrada = socket.getInputStream();
     this.osSalida = socket.getOutputStream();
     this.disEntrada = new DataInputStream(isEntrada);
     this.dosSalida = new DataOutputStream(osSalida);
   } catch (UnknownHostException ex) {
     JOptionPane.showMessageDialog(
         null,
         "UnknownHostException: " + ex.getLocalizedMessage(),
         "Error conectar()",
         JOptionPane.ERROR_MESSAGE);
   } catch (IOException ex) {
     JOptionPane.showMessageDialog(
         null,
         "IOException: " + ex.getLocalizedMessage(),
         "Error conectar()",
         JOptionPane.ERROR_MESSAGE);
   }
 }
Esempio n. 10
0
  @Override
  public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET)
      throw new NetworkInterfaceNotSupportedException(
          "Unsupported interface type, only TYPE_INET currently supported");

    /*
     * TODO: Use it or loose it.
     * Commented out because it is not currently used in this monitor
     */
    // get parameters
    // int retry = ParameterMap.getKeyedInteger(parameters, "retry", DEFAULT_RETRY);
    // int timeout = ParameterMap.getKeyedInteger(parameters, "timeout", DEFAULT_TIMEOUT);

    // Extract the address
    //
    InetAddress ipv4Addr = (InetAddress) iface.getAddress();

    // Default is a failed status
    //
    PollStatus serviceStatus = PollStatus.unavailable();

    // Attempt to retrieve NetBIOS name of this interface in order
    // to determine if SMB is supported.
    //
    NbtAddress nbtAddr = null;

    /*
     * This try block was updated to reflect the behavior of the plugin.
     */
    final String hostAddress = InetAddressUtils.str(ipv4Addr);

    final boolean doNodeStatus =
        ParameterMap.getKeyedBoolean(parameters, DO_NODE_STATUS, DO_NODE_STATUS_DEFAULT);

    try {
      nbtAddr = NbtAddress.getByName(hostAddress);

      if (doNodeStatus) {
        nbtAddr.getNodeType();
      }

      if (!nbtAddr.getHostName().equals(hostAddress)) serviceStatus = PollStatus.available();

    } catch (UnknownHostException uhE) {
      serviceStatus =
          logDown(
              Level.DEBUG,
              "Unknown host exception generated for "
                  + hostAddress
                  + ", reason: "
                  + uhE.getLocalizedMessage());
    } catch (RuntimeException rE) {
      serviceStatus = logDown(Level.ERROR, "Unexpected runtime exception", rE);
    } catch (Throwable e) {
      serviceStatus = logDown(Level.DEBUG, "Unexpected exception", e);
    }

    //
    // return the status of the service
    //
    return serviceStatus;
  }
  /* (non-Javadoc)
   * @see com.aptana.ide.core.io.vfs.IConnectionFileManager#connect(org.eclipse.core.runtime.IProgressMonitor)
   */
  public void connect(IProgressMonitor monitor) throws CoreException {
    Assert.isTrue(ftpClient != null, Messages.FTPConnectionFileManager_not_initialized);
    monitor = Policy.monitorFor(monitor);
    try {
      cwd = null;
      cleanup();

      ConnectionContext context = CoreIOPlugin.getConnectionContext(this);

      if (messageLogWriter == null) {
        if (context != null) {
          Object object = context.get(ConnectionContext.COMMAND_LOG);
          if (object instanceof PrintWriter) {
            messageLogWriter = (PrintWriter) object;
          } else if (object instanceof OutputStream) {
            messageLogWriter = new PrintWriter((OutputStream) object);
          }
        }
        if (messageLogWriter == null) {
          messageLogWriter = FTPPlugin.getDefault().getFTPLogWriter();
        }
        if (messageLogWriter != null) {
          messageLogWriter.println(StringUtils.format("---------- FTP {0} ----------", host));
          setMessageLogger(ftpClient, messageLogWriter);
        }
      } else {
        messageLogWriter.println(
            StringUtils.format("---------- RECONNECTING - FTP {0} ----------", host));
      }

      monitor.beginTask(
          Messages.FTPConnectionFileManager_establishing_connection, IProgressMonitor.UNKNOWN);
      ftpClient.setRemoteHost(host);
      ftpClient.setRemotePort(port);
      while (true) {
        monitor.subTask(Messages.FTPConnectionFileManager_connecting);
        ftpClient.connect();
        if (password.length == 0
            && !IFTPConstants.LOGIN_ANONYMOUS.equals(login)
            && (context == null || !context.getBoolean(ConnectionContext.NO_PASSWORD_PROMPT))) {
          getOrPromptPassword(
              StringUtils.format(Messages.FTPConnectionFileManager_ftp_auth, host),
              Messages.FTPConnectionFileManager_specify_password);
        }
        Policy.checkCanceled(monitor);
        monitor.subTask(Messages.FTPConnectionFileManager_authenticating);
        try {
          ftpClient.login(login, String.copyValueOf(password));
        } catch (FTPException e) {
          Policy.checkCanceled(monitor);
          if (ftpClient.getLastValidReply() == null
              || "331".equals(ftpClient.getLastValidReply().getReplyCode())) { // $NON-NLS-1$
            if (context != null && context.getBoolean(ConnectionContext.NO_PASSWORD_PROMPT)) {
              throw new CoreException(
                  new Status(
                      Status.ERROR,
                      FTPPlugin.PLUGIN_ID,
                      StringUtils.format("Authentication failed: {0}", e.getLocalizedMessage()),
                      e));
            }
            promptPassword(
                StringUtils.format(Messages.FTPConnectionFileManager_ftp_auth, host),
                Messages.FTPConnectionFileManager_invalid_password);
            safeQuit();
            continue;
          }
          throw e;
        }
        break;
      }

      Policy.checkCanceled(monitor);
      changeCurrentDir(basePath);

      ftpClient.setType(
          IFTPConstants.TRANSFER_TYPE_ASCII.equals(transferType)
              ? FTPTransferType.ASCII
              : FTPTransferType.BINARY);

      if ((hasServerInfo
              || (context != null && context.getBoolean(ConnectionContext.QUICK_CONNECT)))
          && !(context != null && context.getBoolean(ConnectionContext.DETECT_TIMEZONE))) {
        return;
      }
      getherServerInfo(context, monitor);

    } catch (OperationCanceledException e) {
      safeQuit();
      throw e;
    } catch (CoreException e) {
      safeQuit();
      throw e;
    } catch (UnknownHostException e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              "Host name not found: " + e.getLocalizedMessage(),
              e));
    } catch (FileNotFoundException e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              "Remote folder not found: " + e.getLocalizedMessage(),
              e));
    } catch (Exception e) {
      safeQuit();
      throw new CoreException(
          new Status(
              Status.ERROR,
              FTPPlugin.PLUGIN_ID,
              Messages.FTPConnectionFileManager_connection_failed + e.getLocalizedMessage(),
              e));
    } finally {
      monitor.done();
    }
  }
  private static IStatus collectServerInfos(
      String address,
      int port,
      final SpecialAddress special,
      final List<RemoteR> infos,
      final SubMonitor progress) {
    try {
      if (special != null) {
        address = special.fPublicHost;
        port = special.fPort;
      }
      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Resolving_message, address));
      final InetAddress inetAddress = InetAddress.getByName(address);
      final String hostname = inetAddress.getHostName();
      final String hostip = inetAddress.getHostAddress();
      progress.worked(1);
      if (progress.isCanceled()) {
        return Status.CANCEL_STATUS;
      }

      progress.subTask(
          NLS.bind(Messages.RRemoteConsoleSelectionDialog_task_Connecting_message, hostname));
      final Registry registry;
      if (special != null) {
        final RMIClientSocketFactory socketFactory = special.getSocketFactory(progress.newChild(5));
        RjsComConfig.setRMIClientSocketFactory(socketFactory);
        registry = LocateRegistry.getRegistry(special.fPrivateHost, port, socketFactory);
      } else {
        RjsComConfig.setRMIClientSocketFactory(null);
        registry = LocateRegistry.getRegistry(address, port);
      }
      final String rmiBase =
          (port == Registry.REGISTRY_PORT)
              ? "//" + address + '/'
              : //$NON-NLS-1$
              "//" + address + ':' + port + '/'; // $NON-NLS-1$
      final String[] names = registry.list();
      for (final String name : names) {
        try {
          final Remote remote = registry.lookup(name);
          if (remote instanceof Server) {
            final Server server = (Server) remote;
            final ServerInfo info = server.getInfo();
            final String rmiAddress = rmiBase + name;
            final RemoteR r = new RemoteR(hostname, hostip, rmiAddress, info);
            infos.add(r);
          }
        } catch (final Exception e) {
        }
      }
      return Status.OK_STATUS;
    } catch (final RemoteException e) {
      return new Status(IStatus.WARNING, RConsoleUIPlugin.PLUGIN_ID, address);
    } catch (final UnknownHostException e) {
      return new Status(
          IStatus.ERROR,
          RConsoleUIPlugin.PLUGIN_ID,
          "Unknown host: " + e.getLocalizedMessage()); // $NON-NLS-1$
    } catch (final CoreException e) {
      return e.getStatus();
    } finally {
      RjsComConfig.clearRMIClientSocketFactory();
    }
  }