void launchWorkerNode(Container container) throws IOException, YarnException {
    Map<String, String> env = System.getenv();
    ContainerLaunchContext workerContext = Records.newRecord(ContainerLaunchContext.class);

    LocalResource workerJar = Records.newRecord(LocalResource.class);
    setupWorkerJar(workerJar);
    workerContext.setLocalResources(Collections.singletonMap("socialite.jar", workerJar));
    System.out.println("[Master] workerJar:" + workerJar);

    Map<String, String> workerEnv = new HashMap<String, String>(env);
    setupWorkerEnv(workerEnv);
    workerContext.setEnvironment(workerEnv);

    String opts = "-Dsocialite.master=" + NetUtils.getHostname().split("/")[1] + " ";
    opts += "-Dsocialite.worker.num_threads=" + ClusterConf.get().getNumWorkerThreads() + " ";
    workerContext.setCommands(
        Collections.singletonList(
            "$JAVA_HOME/bin/java -ea "
                + env.get("JVM_OPTS")
                + " "
                + env.get("SOCIALITE_OPTS")
                + " "
                + opts
                + " "
                + "socialite.dist.worker.WorkerNode"
                + " 1>"
                + ApplicationConstants.LOG_DIR_EXPANSION_VAR
                + "/stdout"
                + " 2>"
                + ApplicationConstants.LOG_DIR_EXPANSION_VAR
                + "/stderr"));
    nmClient.startContainer(container, workerContext);
    L.info("Launched worker node (container:" + container.getId() + ")");
  }
 protected int runEclipse(String message, File location, String[] args, File extensions) {
   File root = new File(Activator.getBundleContext().getProperty("java.home"));
   root = new File(root, "bin");
   File exe = new File(root, "javaw.exe");
   if (!exe.exists()) exe = new File(root, "java");
   assertTrue("Java executable not found in: " + exe.getAbsolutePath(), exe.exists());
   List<String> command = new ArrayList<String>();
   Collections.addAll(
       command,
       new String[] {
         (new File(location == null ? output : location, getExeFolder() + "eclipse"))
             .getAbsolutePath(),
         "--launcher.suppressErrors",
         "-nosplash",
         "-vm",
         exe.getAbsolutePath()
       });
   Collections.addAll(command, args);
   Collections.addAll(command, new String[] {"-vmArgs", "-Dosgi.checkConfiguration=true"});
   // command-line if you want to run and allow a remote debugger to connect
   if (debug)
     Collections.addAll(
         command,
         new String[] {
           "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787"
         });
   int result = run(message, command.toArray(new String[command.size()]));
   // 13 means that we wrote something out in the log file.
   // so try and parse it and fail via that message if we can.
   if (result == 13) parseExitdata(message);
   return result;
 }
  /** Default constructor. */
  protected SIPTransactionStack() {
    super();
    this.transactionTableSize = -1;
    // a set of methods that result in dialog creation.
    this.dialogCreatingMethods = new HashSet<String>();
    // Standard set of methods that create dialogs.
    this.dialogCreatingMethods.add(Request.REFER);
    this.dialogCreatingMethods.add(Request.INVITE);
    this.dialogCreatingMethods.add(Request.SUBSCRIBE);
    // Notify may or may not create a dialog. This is handled in
    // the code.
    // Create the transaction collections

    clientTransactions = Collections.synchronizedList(new ArrayList<SIPClientTransaction>());
    serverTransactions = Collections.synchronizedList(new ArrayList<SIPServerTransaction>());
    // Dialog dable.
    this.dialogTable = new Hashtable<String, SIPDialog>();

    clientTransactionTable = new Hashtable<String, SIPTransaction>();
    serverTransactionTable = new Hashtable<String, SIPTransaction>();

    // Start the timer event thread.

    this.timer = new Timer();
    this.pendingRecordScanner = new Thread(new PendingRecordScanner(this));
    this.pendingRecordScanner.setDaemon(true);
    this.pendingTransactions = new HashSet<SIPServerTransaction>();
    pendingRecords = Collections.synchronizedList(new ArrayList<PendingRecord>());
    pendingRecordScanner.setName("PendingRecordScanner");
    pendingRecordScanner.start();
    // endif
    //

  }
  static void logPlugins() {
    List<String> loadedBundled = new ArrayList<String>();
    List<String> disabled = new ArrayList<String>();
    List<String> loadedCustom = new ArrayList<String>();

    for (IdeaPluginDescriptor descriptor : ourPlugins) {
      final String version = descriptor.getVersion();
      String s = descriptor.getName() + (version != null ? " (" + version + ")" : "");
      if (descriptor.isEnabled()) {
        if (descriptor.isBundled() || SPECIAL_IDEA_PLUGIN.equals(descriptor.getName()))
          loadedBundled.add(s);
        else loadedCustom.add(s);
      } else {
        disabled.add(s);
      }
    }

    Collections.sort(loadedBundled);
    Collections.sort(loadedCustom);
    Collections.sort(disabled);

    getLogger().info("Loaded bundled plugins: " + StringUtil.join(loadedBundled, ", "));
    if (!loadedCustom.isEmpty()) {
      getLogger().info("Loaded custom plugins: " + StringUtil.join(loadedCustom, ", "));
    }
    if (!disabled.isEmpty()) {
      getLogger().info("Disabled plugins: " + StringUtil.join(disabled, ", "));
    }
  }
Beispiel #5
0
  public static void convertFormToConfiguration(
      final StoredConfigurationImpl storedConfiguration,
      final Map<String, String> ldapForm,
      final Map<String, String> incomingLdapForm)
      throws PwmUnrecoverableException {
    {
      final String newLdapURI = getLdapUrlFromFormConfig(ldapForm);
      final StringArrayValue newValue = new StringArrayValue(Collections.singletonList(newLdapURI));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_SERVER_URLS, LDAP_PROFILE_KEY, newValue, null);
    }

    { // proxy/admin account
      final String ldapAdminDN = ldapForm.get(PARAM_LDAP_PROXY_DN);
      final String ldapAdminPW = ldapForm.get(PARAM_LDAP_PROXY_PW);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapAdminDN), null);
      final PasswordValue passwordValue =
          new PasswordValue(PasswordData.forStringValue(ldapAdminPW));
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_PROXY_USER_PASSWORD, LDAP_PROFILE_KEY, passwordValue, null);
    }

    storedConfiguration.writeSetting(
        PwmSetting.LDAP_CONTEXTLESS_ROOT,
        LDAP_PROFILE_KEY,
        new StringArrayValue(Collections.singletonList(ldapForm.get(PARAM_LDAP_CONTEXT))),
        null);

    {
      final String ldapContext = ldapForm.get(PARAM_LDAP_CONTEXT);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_CONTEXTLESS_ROOT,
          LDAP_PROFILE_KEY,
          new StringArrayValue(Collections.singletonList(ldapContext)),
          null);
    }

    {
      final String ldapTestUserDN = ldapForm.get(PARAM_LDAP_TEST_USER);
      storedConfiguration.writeSetting(
          PwmSetting.LDAP_TEST_USER_DN, LDAP_PROFILE_KEY, new StringValue(ldapTestUserDN), null);
    }

    { // set admin query
      final String groupDN = ldapForm.get(PARAM_LDAP_ADMIN_GROUP);
      final List<UserPermission> userPermissions =
          Collections.singletonList(
              new UserPermission(UserPermission.Type.ldapGroup, null, null, groupDN));
      storedConfiguration.writeSetting(
          PwmSetting.QUERY_MATCH_PWM_ADMIN, new UserPermissionValue(userPermissions), null);
    }

    // set context based on ldap dn
    if (incomingLdapForm.containsKey(PARAM_APP_SITEURL)) {
      ldapForm.put(PARAM_APP_SITEURL, incomingLdapForm.get(PARAM_APP_SITEURL));
    }
    storedConfiguration.writeSetting(
        PwmSetting.PWM_SITE_URL, new StringValue(ldapForm.get(PARAM_APP_SITEURL)), null);
  }
Beispiel #6
0
  public String detectPPP() {
    try {
      List<String> linkPPP = new ArrayList<String>();
      List<String> linkDSL = new ArrayList<String>();
      Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

      // System.out.println("NETS VALUES"+" "+nets);

      // System.out.println("INITIALY VALUES"+" "+linkPPP);

      for (NetworkInterface netInf : Collections.list(nets)) {
        // System.out.println("netInf VALUES"+" "+netInf);

        if (!netInf.isLoopback()) {
          if (netInf.isPointToPoint()) {
            // System.out.println("in point to point");
            // System.out.println("netInf VALUES"+" "+netInf);
            Enumeration<InetAddress> inetAdd = netInf.getInetAddresses();
            // System.out.println("inetAdd VALUES"+" "+inetAdd);
            for (InetAddress inet : Collections.list(inetAdd)) {
              // System.out.println("inet vales in the ineer loop"+" "+inet);
              // System.out.println("linkPPP vales before add in the ineer loop"+" "+linkPPP);
              linkPPP.add(inet.getHostAddress()); // 				
              // System.out.println("linkPPP vales after add in the ineer loop"+" "+linkPPP);
              // System.out.println("IP:"+" "+inet.getHostAddress());
            }
          } else {
            Enumeration<InetAddress> inetAdd = netInf.getInetAddresses();
            for (InetAddress inet : Collections.list(inetAdd)) {
              linkDSL.add(inet.getHostAddress());
            }
          }
        }
      }
      // System.out.println("FINAL VALUE of linkPPP"+" "+linkPPP.get(0));
      // System.out.println("FINAL VALUES DSL"+" "+linkDSL);
      int i = linkPPP.size();
      if (i != 0) {
        // System.out.println("linkPPP"+" "+linkPPP.get(i-1));
        return linkPPP.get(i - 1) + ",y";
        // return linkPPP.get(0)+",y";
      } else if (linkDSL.size() != 0) return linkDSL.get(i - 1) + ",n";
      // return linkDSL.get(0)+",n";
      else return "127.0.0.1,n";
    } catch (SocketException e) {
      // e.printStackTrace();
      System.err.println("exception in ");
    }

    return "127.0.0.1,n";
  }
Beispiel #7
0
  /**
   * Unchoke connected peers.
   *
   * <p>This is one of the "clever" places of the BitTorrent client. Every
   * OPTIMISTIC_UNCHOKING_FREQUENCY seconds, we decide which peers should be unchocked and
   * authorized to grab pieces from us.
   *
   * <p>Reciprocation (tit-for-tat) and upload capping is implemented here by carefully choosing
   * which peers we unchoke, and which peers we choke.
   *
   * <p>The four peers with the best download rate and are interested in us get unchoked. This
   * maximizes our download rate as we'll be able to get data from there four "best" peers quickly,
   * while allowing these peers to download from us and thus reciprocate their generosity.
   *
   * <p>Peers that have a better download rate than these four downloaders but are not interested
   * get unchoked too, we want to be able to download from them to get more data more quickly. If
   * one becomes interested, it takes a downloader's place as one of the four top downloaders (i.e.
   * we choke the downloader with the worst upload rate).
   *
   * @param optimistic Whether to perform an optimistic unchoke as well.
   */
  private synchronized void unchokePeers(boolean optimistic) {
    // Build a set of all connected peers, we don't care about peers we're
    // not connected to.
    List<SharingPeer> bound = new ArrayList<SharingPeer>(getConnectedPeers());
    Collections.sort(bound, this.getPeerRateComparator());
    Collections.reverse(bound);

    if (bound.size() == 0) {
      logger.trace("No connected peers, skipping unchoking.");
      return;
    } else {
      logger.trace("Running unchokePeers() on {} connected peers.", bound.size());
    }

    int downloaders = 0;
    Set<SharingPeer> choked = new HashSet<SharingPeer>();

    // We're interested in the top downloaders first, so use a descending
    // set.
    for (SharingPeer peer : bound) {
      if (downloaders < Client.MAX_DOWNLOADERS_UNCHOKE) {
        // Unchoke up to MAX_DOWNLOADERS_UNCHOKE interested peers
        if (peer.isChoking()) {
          if (peer.isInterested()) {
            downloaders++;
          }

          peer.unchoke();
        }
        continue;
      }
      // Choke everybody else
      choked.add(peer);
    }

    // Actually choke all chosen peers (if any), except the eventual
    // optimistic unchoke.
    if (choked.size() > 0) {
      SharingPeer randomPeer =
          choked.toArray(new SharingPeer[0])[this.random.nextInt(choked.size())];

      for (SharingPeer peer : choked) {
        if (optimistic && peer == randomPeer) {
          logger.debug("Optimistic unchoke of {}.", peer);
          continue;
        }

        peer.choke();
      }
    }
  }
  private List<String> getServerInterfaces() {

    List<String> bindInterfaces = new ArrayList<String>();

    String interfaceName = JiveGlobals.getXMLProperty("network.interface");
    String bindInterface = null;
    if (interfaceName != null) {
      if (interfaceName.trim().length() > 0) {
        bindInterface = interfaceName;
      }
    }

    int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

    if (bindInterface == null) {
      try {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netInterface : Collections.list(nets)) {
          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
          for (InetAddress address : Collections.list(addresses)) {
            if ("127.0.0.1".equals(address.getHostAddress())) {
              continue;
            }
            if (address.getHostAddress().startsWith("0.")) {
              continue;
            }
            Socket socket = new Socket();
            InetSocketAddress remoteAddress =
                new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort);
            try {
              socket.connect(remoteAddress);
              bindInterfaces.add(address.getHostAddress());
              break;
            } catch (IOException e) {
              // Ignore this address. Let's hope there is more addresses to validate
            }
          }
        }
      } catch (SocketException e) {
        // We failed to discover a valid IP address where the admin console is running
        return null;
      }
    } else {
      bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
  }
Beispiel #9
0
 static {
   Set<EncodingRule> rules = new HashSet<EncodingRule>();
   rules.add(new EncodingRule("*", "%2A"));
   rules.add(new EncodingRule("+", "%20"));
   rules.add(new EncodingRule("%7E", "~"));
   ENCODING_RULES = Collections.unmodifiableSet(rules);
 }
  /**
   * Build the resource map from the KML Model's <i>ResourceMap</i> element.
   *
   * @param model Model from which to create the resource map.
   * @return Map that relates relative paths in the COLLADA document to paths relative to the KML
   *     document.
   */
  protected Map<String, String> createResourceMap(KMLModel model) {
    Map<String, String> map = new HashMap<String, String>();

    KMLResourceMap resourceMap = model.getResourceMap();
    if (resourceMap == null) return Collections.emptyMap();

    for (KMLAlias alias : resourceMap.getAliases()) {
      if (alias != null
          && !WWUtil.isEmpty(alias.getSourceRef())
          && !WWUtil.isEmpty(alias.getTargetHref())) {
        map.put(alias.getSourceRef(), alias.getTargetHref());
      }
    }

    return map.size() > 0 ? map : Collections.<String, String>emptyMap();
  }
  void _pickInitial() throws MongoException {
    if (_curAddress != null) return;

    // we need to just get a server to query for ismaster
    _pickCurrent();

    try {
      _logger.info("current address beginning of _pickInitial: " + _curAddress);

      DBObject im = isMasterCmd();
      if (_isMaster(im)) return;

      synchronized (_allHosts) {
        Collections.shuffle(_allHosts);
        for (ServerAddress a : _allHosts) {
          if (_curAddress == a) continue;

          _logger.info("remote [" + _curAddress + "] -> [" + a + "]");
          _set(a);

          im = isMasterCmd();
          if (_isMaster(im)) return;

          _logger.severe("switched to: " + a + " but isn't master");
        }

        throw new MongoException("can't find master");
      }
    } catch (Exception e) {
      _logger.log(Level.SEVERE, "can't pick initial master, using random one", e);
    }
  }
  /* 接続している全員にmessageを送信するメソッド  『POST』*/
  public void post(String message) throws IOException {
    int flag1 = 1; // フラグ(送信者表示時に利用)

    System.out.println(message);
    List names = new ArrayList(); // 送信者リストを作る

    // チャットに参加しているユーザ全員にメッセージを送信する

    for (int i = 0; i < clients.size(); i++) {
      ChatClientHandler handler = (ChatClientHandler) clients.get(i);
      if (handler != this) { // 自分以外のユーザで
        names.add(handler.getClientName()); // 送信者リストに名前追加
        handler.send("[" + this.getClientName() + "]" + message); // メッセージを送信
      }
    }

    Collections.sort(names); // 送信者リストをソート

    String returnMessage = ""; // 初期化

    for (int i = 0; i < names.size(); i++) { //
      if (flag1 == 0) // 2人目以降、前に「,」つける
      returnMessage = returnMessage + ",";
      returnMessage = returnMessage + names.get(i); // 送信者リストに名前を追加
      flag1 = 0; // 2人目以降フラグをおろす
    }
    this.send("<< To. " + returnMessage + ">>");
  }
  public boolean perform(
      String[] strings,
      List clients,
      List rejectList,
      Map groups,
      ChatClientHandler_345387 myHandler)
      throws IOException {
    // ユーザの名前を入れてソートするためのListを宣言(ローカル変数)
    List names = new ArrayList();

    // 全クライアントのListに加える
    for (int i = 0; i < clients.size(); i++) {
      ChatClientHandler_345387 handler = (ChatClientHandler_345387) clients.get(i);
      names.add(handler.getClientName());
    }

    // ソートする
    Collections.sort(names);

    // 接続中のクライアント名をコンマで区切って昇順に一行で表示
    String returnMessage = "";
    for (int i = 0; i < names.size(); i++) {
      returnMessage += names.get(i) + ",";
    }
    myHandler.send(returnMessage);

    System.out.println(myHandler.getClientName() + ": users: " + returnMessage);

    return true;
  }
Beispiel #14
0
  /** Re Initialize the stack instance. */
  protected void reInit() {
    super.reInit();
    clientTransactions = Collections.synchronizedList(new ArrayList<SIPClientTransaction>());
    serverTransactions = Collections.synchronizedList(new ArrayList<SIPServerTransaction>());
    pendingTransactions = new HashSet<SIPServerTransaction>();
    pendingRecords = Collections.synchronizedList(new ArrayList<PendingRecord>());
    clientTransactionTable = new Hashtable<String, SIPTransaction>();
    serverTransactionTable = new Hashtable<String, SIPTransaction>();
    // Dialog dable.
    this.dialogTable = new Hashtable<String, SIPDialog>();

    this.timer = new Timer();
    pendingRecordScanner = new Thread(new PendingRecordScanner(this));
    pendingRecordScanner.setDaemon(true);
    pendingRecordScanner.setName("PendingRecordScanner");
    pendingRecordScanner.start();
  }
Beispiel #15
0
 public void addTick(Cam c) {
   tickArr.add(new Tick(hs1.getSliderPos(), hsYPos, c, hs1.getPosInSeconds()));
   // set the older ticks to inactive
   for (int i = 0; i < tickArr.size() - 1; i++) {
     tickArr.get(i).setToInActive();
   }
   // sort the ticks in case one was placed before an existing tick
   Collections.sort(tickArr);
 }
Beispiel #16
0
  public String _sort(String args[]) {
    verifyCommand(args, _sortHelp, null, 2, Integer.MAX_VALUE);

    List<String> result = new ArrayList<String>();
    for (int i = 1; i < args.length; i++) {
      Processor.split(args[i], result);
    }
    Collections.sort(result);
    return Processor.join(result);
  }
Beispiel #17
0
  public static Map<String, String> defaultForm(PwmSettingTemplate template) {
    final Map<String, String> defaultLdapForm = new HashMap<>();

    try {
      final String defaultLdapUrlString =
          ((List<String>) PwmSetting.LDAP_SERVER_URLS.getDefaultValue(template).toNativeObject())
              .get(0);
      final URI uri = new URI(defaultLdapUrlString);

      defaultLdapForm.put(PARAM_LDAP_HOST, uri.getHost());
      defaultLdapForm.put(PARAM_LDAP_PORT, String.valueOf(uri.getPort()));
      defaultLdapForm.put(
          PARAM_LDAP_SECURE, "ldaps".equalsIgnoreCase(uri.getScheme()) ? "true" : "false");

      defaultLdapForm.put(
          PARAM_LDAP_ADMIN_DN,
          (String) PwmSetting.LDAP_PROXY_USER_DN.getDefaultValue(template).toNativeObject());
      defaultLdapForm.put(PARAM_LDAP_ADMIN_PW, "");

      defaultLdapForm.put(
          PARAM_LDAP_CONTEXT,
          ((List<String>)
                  PwmSetting.LDAP_CONTEXTLESS_ROOT.getDefaultValue(template).toNativeObject())
              .get(0));
      defaultLdapForm.put(
          PARAM_LDAP_TEST_USER,
          (String) PwmSetting.LDAP_TEST_USER_DN.getDefaultValue(template).toNativeObject());
      {
        List<UserPermission> userPermissions =
            (List<UserPermission>)
                PwmSetting.QUERY_MATCH_PWM_ADMIN.getDefaultValue(template).toNativeObject();
        final String groupDN =
            userPermissions != null && userPermissions.size() > 0
                ? userPermissions.get(0).getLdapBase()
                : "";
        defaultLdapForm.put(PARAM_LDAP_ADMIN_GROUP, groupDN);
      }

      defaultLdapForm.put(
          PARAM_CR_STORAGE_PREF,
          (String)
              PwmSetting.FORGOTTEN_PASSWORD_WRITE_PREFERENCE
                  .getDefaultValue(template)
                  .toNativeObject());

      defaultLdapForm.put(PARAM_CONFIG_PASSWORD, "");
      defaultLdapForm.put(PARAM_CONFIG_PASSWORD_VERIFY, "");
    } catch (Exception e) {
      LOGGER.error(
          "error building static form values using default configuration: " + e.getMessage());
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(defaultLdapForm);
  }
Beispiel #18
0
 /**
  * Gets the list of the vnmrj users(operators) for the current unix user logged in
  *
  * @return the list of vnmrj users
  */
 protected Object[] getOperators() {
   String strUser = System.getProperty("user.name");
   User user = LoginService.getDefault().getUser(strUser);
   ArrayList<String> aListOperators = user.getOperators();
   if (aListOperators == null || aListOperators.isEmpty())
     aListOperators = new ArrayList<String>();
   Collections.sort(aListOperators);
   if (aListOperators.contains(strUser)) aListOperators.remove(strUser);
   aListOperators.add(0, strUser);
   return (aListOperators.toArray());
 }
  ReplicaSetStatus(Mongo mongo, List<ServerAddress> initial) {
    _mongo = mongo;
    _all = Collections.synchronizedList(new ArrayList<Node>());
    for (ServerAddress addr : initial) {
      _all.add(new Node(addr));
    }
    _nextResolveTime = System.currentTimeMillis() + inetAddrCacheMS;

    _updater = new Updater();
    _updater.start();
  }
 public void closeServer() {
   isActive = false;
   // Remove all connections
   synchronized (connections) {
     for (Connection c : connections) {
       c.send(DISCONNECT);
       c.setState(DISCONNECTED);
     }
   }
   connections = Collections.synchronizedList(new ArrayList<Connection>());
 }
  public List<String> getElementList(String key) {
    Object element = definitionMap.getMapElement(key);
    List<String> lst;

    if (element instanceof String) {
      return Collections.singletonList((String) element);
    } else if (element instanceof List) {
      return (List) element;
    } else {
      return null;
    }
  }
 private static Set<SocketOption<?>> defaultOptions() {
   HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(8);
   set.add(StandardSocketOptions.SO_SNDBUF);
   set.add(StandardSocketOptions.SO_RCVBUF);
   set.add(StandardSocketOptions.SO_REUSEADDR);
   set.add(StandardSocketOptions.SO_BROADCAST);
   set.add(StandardSocketOptions.IP_TOS);
   set.add(StandardSocketOptions.IP_MULTICAST_IF);
   set.add(StandardSocketOptions.IP_MULTICAST_TTL);
   set.add(StandardSocketOptions.IP_MULTICAST_LOOP);
   return Collections.unmodifiableSet(set);
 }
  static class Holder {

    Holder(MongoOptions options) {
      _options = options;
    }

    DBPortPool get(InetSocketAddress addr) {

      DBPortPool p = _pools.get(addr);

      if (p != null) return p;

      synchronized (_pools) {
        p = _pools.get(addr);
        if (p != null) {
          return p;
        }

        p = new DBPortPool(addr, _options);
        _pools.put(addr, p);
        String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace(':', '_');

        try {
          ObjectName on = new ObjectName(name);
          if (_server.isRegistered(on)) {
            _server.unregisterMBean(on);
            Bytes.LOGGER.log(
                Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
          }
          _server.registerMBean(p, on);
        } catch (JMException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        } catch (java.security.AccessControlException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        }
      }

      return p;
    }

    void close() {
      synchronized (_pools) {
        for (DBPortPool p : _pools.values()) {
          p.close();
        }
      }
    }

    final MongoOptions _options;
    final Map<InetSocketAddress, DBPortPool> _pools =
        Collections.synchronizedMap(new HashMap<InetSocketAddress, DBPortPool>());
    final MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
  }
  /**
   * Parses HTTP parameters in an appropriate format and return back map of values to predefined
   * list of names.
   *
   * @param req Request.
   * @return Map of parsed parameters.
   */
  @SuppressWarnings({"unchecked"})
  private Map<String, Object> parameters(ServletRequest req) {
    Map<String, String[]> params = req.getParameterMap();

    if (F.isEmpty(params)) return Collections.emptyMap();

    Map<String, Object> map = U.newHashMap(params.size());

    for (Map.Entry<String, String[]> entry : params.entrySet())
      map.put(entry.getKey(), parameter(entry.getValue()));

    return map;
  }
 static {
   FILE_UTILS = FileUtils.getFileUtils();
   AntClassLoader.pathMap = Collections.synchronizedMap(new HashMap<String, String>());
   AntClassLoader.subClassToLoad = null;
   CONSTRUCTOR_ARGS = new Class[] {ClassLoader.class, Project.class, Path.class, Boolean.TYPE};
   if (JavaEnvUtils.isAtLeastJavaVersion("1.5")) {
     try {
       AntClassLoader.subClassToLoad =
           Class.forName("org.apache.tools.ant.loader.AntClassLoader5");
     } catch (ClassNotFoundException ex) {
     }
   }
 }
Beispiel #26
0
  // Examines servlet config and servlet context for configuration parameters.
  // Configuration from the servlet context overrides servlet parameters defined in web.xml
  Configuration initConfig(ServletConfig pConfig) {
    Configuration config =
        new Configuration(ConfigKey.AGENT_ID, NetworkUtil.getAgentId(hashCode(), "servlet"));
    // From ServletContext ....
    config.updateGlobalConfiguration(new ServletConfigFacade(pConfig));
    // ... and ServletConfig
    config.updateGlobalConfiguration(new ServletContextFacade(getServletContext()));

    // Set type last and overwrite anything written
    config.updateGlobalConfiguration(
        Collections.singletonMap(ConfigKey.AGENT_TYPE.getKeyValue(), "servlet"));
    return config;
  }
Beispiel #27
0
 public static void main(String[] args) {
   try {
     Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
     for (NetworkInterface netint : Collections.list(nets)) displayInfo(netint);
     pinging();
   } catch (java.net.SocketException s) {
     System.out.print('/'); //
     System.exit(0);
   } catch (IOException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
 }
 /**
  * Get IP address from first non-localhost interface
  *
  * @param ipv4 true=return ipv4, false=return ipv6
  * @return address or empty string
  */
 public static String getIPAddress(boolean useIPv4) {
   try {
     List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
     for (NetworkInterface intf : interfaces) {
       List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
       for (InetAddress addr : addrs) {
         if (!addr.isLoopbackAddress()) {
           String sAddr = addr.getHostAddress().toUpperCase();
           boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
           if (useIPv4) {
             if (isIPv4) return sAddr;
           } else {
             if (!isIPv4) {
               int delim = sAddr.indexOf('%'); // drop ip6 port suffix
               return delim < 0 ? sAddr : sAddr.substring(0, delim);
             }
           }
         }
       }
     }
   } catch (Exception ex) {
   } // for now eat exceptions
   return "";
 }
 private static Set<SocketOption<?>> defaultOptions() {
   HashSet<SocketOption<?>> set = new HashSet<SocketOption<?>>(8);
   set.add(StandardSocketOptions.SO_SNDBUF);
   set.add(StandardSocketOptions.SO_RCVBUF);
   set.add(StandardSocketOptions.SO_REUSEADDR);
   set.add(StandardSocketOptions.SO_BROADCAST);
   set.add(StandardSocketOptions.IP_TOS);
   set.add(StandardSocketOptions.IP_MULTICAST_IF);
   set.add(StandardSocketOptions.IP_MULTICAST_TTL);
   set.add(StandardSocketOptions.IP_MULTICAST_LOOP);
   if (ExtendedOptionsImpl.flowSupported()) {
     set.add(jdk.net.ExtendedSocketOptions.SO_FLOW_SLA);
   }
   return Collections.unmodifiableSet(set);
 }
Beispiel #30
0
  /** @return */
  public static String getIPv4Address() {
    String ipv4address = null;

    try {
      final List<NetworkInterface> networkinterfaces =
          Collections.list(NetworkInterface.getNetworkInterfaces());
      for (final NetworkInterface networkinterface : networkinterfaces) {
        final List<InetAddress> addresses = Collections.list(networkinterface.getInetAddresses());
        for (final InetAddress address : addresses) {
          if ((address == null) || address.isLoopbackAddress()) {
            continue;
          }
          if (address instanceof Inet4Address) {
            ipv4address = address.getHostAddress().toString();
            break;
          }
        }
      }
    } catch (Exception x) {
      DBG.m(x);
    }

    return ipv4address;
  }