Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

In this page you can find the example usage for java.net InetSocketAddress getPort.

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean addToNodeConfig(NodeIDType node, InetSocketAddress sockAddr, int version,
        boolean isReconfigurator) {
    String cmd = "insert into " + getNodeConfigTable() + " (" + Columns.RC_NODE_ID.toString() + ", "
            + Columns.INET_ADDRESS.toString() + ", " + Columns.PORT.toString() + ", "
            + Columns.NODE_CONFIG_VERSION.toString() + ", " + Columns.IS_RECONFIGURATOR.toString()
            + " ) values (?,?,?,?,?)";

    PreparedStatement insertCP = null;
    Connection conn = null;//from  w w w .  j  a va 2 s . c  o  m
    boolean added = false;
    try {
        conn = this.getDefaultConn();
        insertCP = conn.prepareStatement(cmd);
        insertCP.setString(1, node.toString());
        insertCP.setString(2, sockAddr.toString());
        insertCP.setInt(3, sockAddr.getPort());
        insertCP.setInt(4, version);
        insertCP.setInt(5, isReconfigurator ? 1 : 0); // 1 means true
        insertCP.executeUpdate();
        // conn.commit();
        added = true;
    } catch (SQLException sqle) {
        if (!SQL.DUPLICATE_KEY.contains(sqle.getSQLState())) {
            log.severe("SQLException while inserting RC record using " + cmd);
            sqle.printStackTrace();
        }
    } finally {
        cleanup(insertCP);
        cleanup(conn);
    }
    return added;
}

From source file:org.apache.hadoop.dfs.DataNode.java

/**
 * This method starts the data node with the specified conf.
 * /* www . j  a v a2 s.c o  m*/
 * @param conf - the configuration
 *  if conf's CONFIG_PROPERTY_SIMULATED property is set
 *  then a simulated storage based data node is created.
 * 
 * @param dataDirs - only for a non-simulated storage data node
 * @throws IOException
 */
void startDataNode(Configuration conf, AbstractList<File> dataDirs) throws IOException {
    // use configured nameserver & interface to get local hostname
    if (conf.get("slave.host.name") != null) {
        machineName = conf.get("slave.host.name");
    }
    if (machineName == null) {
        machineName = DNS.getDefaultHost(conf.get("dfs.datanode.dns.interface", "default"),
                conf.get("dfs.datanode.dns.nameserver", "default"));
    }
    InetSocketAddress nameNodeAddr = NameNode.getAddress(conf);

    this.estimateBlockSize = conf.getLong("dfs.block.size", DEFAULT_BLOCK_SIZE);
    this.socketTimeout = conf.getInt("dfs.socket.timeout", FSConstants.READ_TIMEOUT);
    this.socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", FSConstants.WRITE_TIMEOUT);
    /* Based on results on different platforms, we might need set the default 
     * to false on some of them. */
    this.transferToAllowed = conf.getBoolean("dfs.datanode.transferTo.allowed", true);
    this.writePacketSize = conf.getInt("dfs.write.packet.size", 64 * 1024);
    String address = NetUtils.getServerAddress(conf, "dfs.datanode.bindAddress", "dfs.datanode.port",
            "dfs.datanode.address");
    InetSocketAddress socAddr = NetUtils.createSocketAddr(address);
    int tmpPort = socAddr.getPort();
    storage = new DataStorage();
    // construct registration
    this.dnRegistration = new DatanodeRegistration(machineName + ":" + tmpPort);

    // connect to name node
    this.namenode = (DatanodeProtocol) RPC.waitForProxy(DatanodeProtocol.class, DatanodeProtocol.versionID,
            nameNodeAddr, conf);
    // get version and id info from the name-node
    NamespaceInfo nsInfo = handshake();
    StartupOption startOpt = getStartupOption(conf);
    assert startOpt != null : "Startup option must be set.";

    boolean simulatedFSDataset = conf.getBoolean("dfs.datanode.simulateddatastorage", false);
    if (simulatedFSDataset) {
        setNewStorageID(dnRegistration);
        dnRegistration.storageInfo.layoutVersion = FSConstants.LAYOUT_VERSION;
        dnRegistration.storageInfo.namespaceID = nsInfo.namespaceID;
        // it would have been better to pass storage as a parameter to
        // constructor below - need to augment ReflectionUtils used below.
        conf.set("StorageId", dnRegistration.getStorageID());
        try {
            //Equivalent of following (can't do because Simulated is in test dir)
            //  this.data = new SimulatedFSDataset(conf);
            this.data = (FSDatasetInterface) ReflectionUtils
                    .newInstance(Class.forName("org.apache.hadoop.dfs.SimulatedFSDataset"), conf);
        } catch (ClassNotFoundException e) {
            throw new IOException(StringUtils.stringifyException(e));
        }
    } else { // real storage
        // read storage info, lock data dirs and transition fs state if necessary
        storage.recoverTransitionRead(nsInfo, dataDirs, startOpt);
        // adjust
        this.dnRegistration.setStorageInfo(storage);
        // initialize data node internal structure
        this.data = new FSDataset(storage, conf);
    }

    // find free port
    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    Server.bind(ss, socAddr, 0);
    ss.setReceiveBufferSize(DEFAULT_DATA_SOCKET_SIZE);
    ss.setSoTimeout(conf.getInt("dfs.dataXceiver.timeoutInMS", 30000)); //30s
    // adjust machine name with the actual port
    tmpPort = ss.getLocalPort();
    selfAddr = new InetSocketAddress(ss.getInetAddress().getHostAddress(), tmpPort);
    this.dnRegistration.setName(machineName + ":" + tmpPort);
    LOG.info("Opened info server at " + tmpPort);

    this.maxXceiverCount = conf.getInt("dfs.datanode.max.xcievers", MAX_XCEIVER_COUNT);
    this.threadGroup = new ThreadGroup("dataXceiveServer");
    this.dataXceiveServer = new Daemon(threadGroup, new DataXceiveServer(ss));
    this.threadGroup.setDaemon(true); // auto destroy when empty

    this.blockReportInterval = conf.getLong("dfs.blockreport.intervalMsec", BLOCKREPORT_INTERVAL);
    this.initialBlockReportDelay = conf.getLong("dfs.blockreport.initialDelay", BLOCKREPORT_INITIAL_DELAY)
            * 1000L;
    if (this.initialBlockReportDelay >= blockReportInterval) {
        this.initialBlockReportDelay = 0;
        LOG.info("dfs.blockreport.initialDelay is greater than " + "dfs.blockreport.intervalMsec."
                + " Setting initial delay to 0 msec:");
    }
    this.heartBeatInterval = conf.getLong("dfs.heartbeat.interval", HEARTBEAT_INTERVAL) * 1000L;
    DataNode.nameNodeAddr = nameNodeAddr;

    this.balancingThrottler = new BlockBalanceThrottler(
            conf.getLong("dfs.balance.bandwidthPerSec", 1024L * 1024));

    //initialize periodic block scanner
    String reason = null;
    if (conf.getInt("dfs.datanode.scan.period.hours", 0) < 0) {
        reason = "verification is turned off by configuration";
    } else if (!(data instanceof FSDataset)) {
        reason = "verifcation is supported only with FSDataset";
    }
    if (reason == null) {
        blockScanner = new DataBlockScanner(this, (FSDataset) data, conf);
    } else {
        LOG.info("Periodic Block Verification is disabled because " + reason + ".");
    }

    //create a servlet to serve full-file content
    String infoAddr = NetUtils.getServerAddress(conf, "dfs.datanode.info.bindAddress", "dfs.datanode.info.port",
            "dfs.datanode.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    String infoHost = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    this.infoServer = new StatusHttpServer("datanode", infoHost, tmpInfoPort, tmpInfoPort == 0);
    InetSocketAddress secInfoSocAddr = NetUtils
            .createSocketAddr(conf.get("dfs.datanode.https.address", infoHost + ":" + 0));
    Configuration sslConf = new Configuration(conf);
    sslConf.addResource(conf.get("https.keystore.info.rsrc", "sslinfo.xml"));
    String keyloc = sslConf.get("https.keystore.location");
    if (null != keyloc) {
        this.infoServer.addSslListener(secInfoSocAddr, keyloc, sslConf.get("https.keystore.password", ""),
                sslConf.get("https.keystore.keypassword", ""));
    }
    this.infoServer.addServlet(null, "/streamFile/*", StreamFile.class);
    this.infoServer.setAttribute("datanode.blockScanner", blockScanner);
    this.infoServer.addServlet(null, "/blockScannerReport", DataBlockScanner.Servlet.class);
    this.infoServer.start();
    // adjust info port
    this.dnRegistration.setInfoPort(this.infoServer.getPort());
    myMetrics = new DataNodeMetrics(conf, dnRegistration.getStorageID());

    //init ipc server
    InetSocketAddress ipcAddr = NetUtils.createSocketAddr(conf.get("dfs.datanode.ipc.address"));
    ipcServer = RPC.getServer(this, ipcAddr.getHostName(), ipcAddr.getPort(),
            conf.getInt("dfs.datanode.handler.count", 3), false, conf);
    ipcServer.start();
    dnRegistration.setIpcPort(ipcServer.getListenerAddress().getPort());

    LOG.info("dnRegistration = " + dnRegistration);
}

From source file:net.pms.network.RequestHandler.java

@Override
public void run() {
    Request request = null;/* w  w w. jav a  2  s. com*/
    StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(
            socket.getInetAddress().getHostAddress());

    try {
        int receivedContentLength = -1;
        String userAgentString = null;
        ArrayList<String> identifiers = new ArrayList<>();
        RendererConfiguration renderer = null;

        InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
        InetAddress ia = remoteAddress.getAddress();

        boolean isSelf = ia.getHostAddress().equals(PMS.get().getServer().getHost());

        // Apply the IP filter
        if (filterIp(ia)) {
            throw new IOException("Access denied for address " + ia + " based on IP filter");
        }

        LOGGER.trace("Opened request handler on socket " + socket);
        PMS.get().getRegistry().disableGoToSleep();

        // The handler makes a couple of attempts to recognize a renderer from its requests.
        // IP address matches from previous requests are preferred, when that fails request
        // header matches are attempted and if those fail as well we're stuck with the
        // default renderer.

        // Attempt 1: try to recognize the renderer by its socket address from previous requests
        renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);

        // If the renderer exists but isn't marked as loaded it means it's unrecognized
        // by upnp and we still need to attempt http recognition here.
        boolean unrecognized = renderer == null || !renderer.loaded;
        RendererConfiguration.SortedHeaderMap sortedHeaders = unrecognized
                ? new RendererConfiguration.SortedHeaderMap()
                : null;

        // Gather all the headers
        ArrayList<String> headerLines = new ArrayList<>();
        String line = br.readLine();
        while (line != null && line.length() > 0) {
            headerLines.add(line);
            if (unrecognized) {
                sortedHeaders.put(line);
            }
            line = br.readLine();
        }

        if (unrecognized) {
            // Attempt 2: try to recognize the renderer by matching headers
            renderer = RendererConfiguration.getRendererConfigurationByHeaders(sortedHeaders, ia);
        }

        for (String headerLine : headerLines) {
            LOGGER.trace("Received on socket: " + headerLine);

            // The request object is created inside the while loop.
            if (request != null && request.getMediaRenderer() == null && renderer != null) {
                request.setMediaRenderer(renderer);
            }
            if (headerLine.toUpperCase().startsWith("USER-AGENT")) {
                // Is the request from our own Cling service, i.e. self-originating?
                if (isSelf && headerLine.contains("UMS/")) {
                    LOGGER.trace(
                            "Ignoring self-originating request from " + ia + ":" + remoteAddress.getPort());
                    return;
                }
                userAgentString = headerLine.substring(headerLine.indexOf(':') + 1).trim();
            }

            try {
                StringTokenizer s = new StringTokenizer(headerLine);
                String temp = s.nextToken();
                if (temp.equals("SUBSCRIBE") || temp.equals("GET") || temp.equals("POST")
                        || temp.equals("HEAD")) {
                    request = new Request(temp, s.nextToken().substring(1));
                    if (s.hasMoreTokens() && s.nextToken().equals("HTTP/1.0")) {
                        request.setHttp10(true);
                    }
                } else if (request != null && temp.toUpperCase().equals("CALLBACK:")) {
                    request.setSoapaction(s.nextToken());
                } else if (request != null && temp.toUpperCase().equals("SOAPACTION:")) {
                    request.setSoapaction(s.nextToken());
                } else if (headerLine.toUpperCase().contains("CONTENT-LENGTH:")) {
                    receivedContentLength = Integer.parseInt(
                            headerLine.substring(headerLine.toUpperCase().indexOf("CONTENT-LENGTH: ") + 16));
                } else if (headerLine.toUpperCase().contains("RANGE: BYTES=")) {
                    String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13)
                            .trim();
                    StringTokenizer st = new StringTokenizer(nums, "-");
                    if (!nums.startsWith("-")) {
                        request.setLowRange(Long.parseLong(st.nextToken()));
                    }
                    if (!nums.startsWith("-") && !nums.endsWith("-")) {
                        request.setHighRange(Long.parseLong(st.nextToken()));
                    } else {
                        request.setHighRange(-1);
                    }
                } else if (headerLine.toLowerCase().contains("transfermode.dlna.org:")) {
                    request.setTransferMode(headerLine
                            .substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
                } else if (headerLine.toLowerCase().contains("getcontentfeatures.dlna.org:")) {
                    request.setContentFeatures(headerLine
                            .substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28)
                            .trim());
                } else if (headerLine.toUpperCase().contains("TIMESEEKRANGE.DLNA.ORG: NPT=")) { // firmware 2.50+
                    String timeseek = headerLine
                            .substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") + 28);
                    if (timeseek.endsWith("-")) {
                        timeseek = timeseek.substring(0, timeseek.length() - 1);
                    } else if (timeseek.indexOf('-') > -1) {
                        timeseek = timeseek.substring(0, timeseek.indexOf('-'));
                    }
                    request.setTimeseek(convertStringToTime(timeseek));
                } else if (headerLine.toUpperCase().contains("TIMESEEKRANGE.DLNA.ORG : NPT=")) { // firmware 2.40
                    String timeseek = headerLine
                            .substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") + 29);
                    if (timeseek.endsWith("-")) {
                        timeseek = timeseek.substring(0, timeseek.length() - 1);
                    } else if (timeseek.indexOf('-') > -1) {
                        timeseek = timeseek.substring(0, timeseek.indexOf('-'));
                    }
                    request.setTimeseek(convertStringToTime(timeseek));
                } else {
                    /*
                     * If we made it to here, none of the previous header checks matched.
                     * Unknown headers make interesting logging info when we cannot recognize
                     * the media renderer, so keep track of the truly unknown ones.
                     */
                    boolean isKnown = false;

                    // Try to match possible known headers.
                    String lowerCaseHeaderLine = headerLine.toLowerCase();
                    for (String knownHeaderString : KNOWN_HEADERS) {
                        if (lowerCaseHeaderLine.startsWith(knownHeaderString.toLowerCase())) {
                            isKnown = true;
                            break;
                        }
                    }

                    // It may be unusual but already known
                    if (renderer != null) {
                        String additionalHeader = renderer.getUserAgentAdditionalHttpHeader();
                        if (StringUtils.isNotBlank(additionalHeader)
                                && lowerCaseHeaderLine.startsWith(additionalHeader)) {
                            isKnown = true;
                        }
                    }

                    if (!isKnown) {
                        // Truly unknown header, therefore interesting. Save for later use.
                        identifiers.add(headerLine);
                    }
                }
            } catch (IllegalArgumentException e) {
                LOGGER.error("Error in parsing HTTP headers", e);
            }
        }

        if (request != null) {
            // Still no media renderer recognized?
            if (renderer == null) {
                // Attempt 3: Not really an attempt; all other attempts to recognize
                // the renderer have failed. The only option left is to assume the
                // default renderer.
                renderer = RendererConfiguration.resolve(ia, null);
                request.setMediaRenderer(renderer);
                if (renderer != null) {
                    LOGGER.trace("Using default media renderer: " + renderer.getConfName());

                    if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
                        // We have found an unknown renderer
                        identifiers.add(0, "User-Agent: " + userAgentString);
                        renderer.setIdentifiers(identifiers);
                        LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers:"
                                + StringUtils.join(identifiers, ", "));
                    }
                } else {
                    // If RendererConfiguration.resolve() didn't return the default renderer
                    // it means we know via upnp that it's not really a renderer.
                    return;
                }
            } else {
                if (userAgentString != null) {
                    LOGGER.trace("HTTP User-Agent: " + userAgentString);
                }
                LOGGER.trace("Recognized media renderer: " + renderer.getRendererName());
            }
        }

        if (receivedContentLength > 0) {
            char buf[] = new char[receivedContentLength];
            br.read(buf);
            if (request != null) {
                request.setTextContent(new String(buf));
            }
        }

        if (request != null) {
            LOGGER.trace("HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-"
                    + request.getHighRange());
        }

        if (request != null) {
            request.answer(output, startStopListenerDelegate);
        }

        if (request != null && request.getInputStream() != null) {
            request.getInputStream().close();
        }
    } catch (IOException e) {
        LOGGER.trace("Unexpected IO error: " + e.getClass().getName() + ": " + e.getMessage());
        if (request != null && request.getInputStream() != null) {
            try {
                LOGGER.trace("Closing input stream: " + request.getInputStream());
                request.getInputStream().close();
            } catch (IOException e1) {
                LOGGER.error("Error closing input stream", e1);
            }
        }
    } finally {
        try {
            PMS.get().getRegistry().reenableGoToSleep();
            output.close();
            br.close();
            socket.close();
        } catch (IOException e) {
            LOGGER.error("Error closing connection: ", e);
        }

        startStopListenerDelegate.stop();
        LOGGER.trace("Close connection");
    }
}

From source file:com.datatorrent.stram.StreamingContainerManager.java

private BufferServerController getBufferServerClient(PTOperator operator) {
    BufferServerController bsc = new BufferServerController(operator.getLogicalId());
    bsc.setToken(operator.getContainer().getBufferServerToken());
    InetSocketAddress address = operator.getContainer().bufferServerAddress;
    StreamingContainer.eventloop.connect(
            address.isUnresolved() ? new InetSocketAddress(address.getHostName(), address.getPort()) : address,
            bsc);/* w w  w.  java  2s  .  c o  m*/
    return bsc;
}

From source file:com.buaa.cfs.conf.Configuration.java

/**
 * Set the socket address a client can use to connect for the <code>name</code> property as a
 * <code>host:port</code>.  The wildcard address is replaced with the local host's address. If the host and address
 * properties are configured the host component of the address will be combined with the port component of the addr
 * to generate the address.  This is to allow optional control over which host name is used in multi-home bind-host
 * cases where a host can have multiple names
 *
 * @param hostProperty        the bind-host configuration name
 * @param addressProperty     the service address configuration name
 * @param defaultAddressValue the service default address configuration value
 * @param addr                InetSocketAddress of the service listener
 *
 * @return InetSocketAddress for clients to connect
 *//*from w  w w .j av  a 2  s  .  co m*/
public InetSocketAddress updateConnectAddr(String hostProperty, String addressProperty,
        String defaultAddressValue, InetSocketAddress addr) {

    final String host = get(hostProperty);
    final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue);

    if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) {
        //not our case, fall back to original logic
        return updateConnectAddr(addressProperty, addr);
    }

    final String connectHost = connectHostPort.split(":")[0];
    // Create connect address using client address hostname and server port.
    return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost(connectHost, addr.getPort()));
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts controller with a special config file, and creates and starts all
 * components of PowerFolder.//from ww w  .ja v a  2  s .c  o  m
 *
 * @param filename
 *            The filename to uses as config file (located in the
 *            "getConfigLocationBase()")
 */
public void startConfig(String filename) {
    if (started) {
        throw new IllegalStateException("Configuration already started, shutdown controller first");
    }

    additionalConnectionListeners = Collections.synchronizedList(new ArrayList<ConnectionListener>());
    started = false;
    shuttingDown = false;
    threadPool = new WrappedScheduledThreadPoolExecutor(Constants.CONTROLLER_THREADS_IN_THREADPOOL,
            new NamedThreadFactory("Controller-Thread-"));

    // Initialize resource bundle eager
    // check forced language file from commandline
    if (commandLine != null && commandLine.hasOption("f")) {
        String langfilename = commandLine.getOptionValue("f");
        try {
            ResourceBundle resourceBundle = new ForcedLanguageFileResourceBundle(langfilename);
            Translation.setResourceBundle(resourceBundle);
            logInfo("Loading language bundle from file " + langfilename);
        } catch (FileNotFoundException fnfe) {
            logSevere("forced language file (" + langfilename + ") not found: " + fnfe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        } catch (IOException ioe) {
            logSevere("forced language file io error: " + ioe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        }
    } else {
        Translation.resetResourceBundle();
    }
    Translation.getResourceBundle();

    // loadConfigFile
    if (!loadConfigFile(filename)) {
        return;
    }

    boolean isDefaultConfig = Constants.DEFAULT_CONFIG_FILE.startsWith(getConfigName());
    if (isDefaultConfig) {
        // To keep compatible with previous versions
        preferences = Preferences.userNodeForPackage(PowerFolder.class);
    } else {
        preferences = Preferences.userNodeForPackage(PowerFolder.class).node(getConfigName());

    }

    // initialize logger
    // Enabled verbose mode if in config.
    // This logs to file for analysis.
    verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
    initLogger();

    if (verbose) {
        ByteSerializer.BENCHMARK = true;
        scheduleAndRepeat(new Runnable() {
            @Override
            public void run() {
                ByteSerializer.printStats();
            }
        }, 600000L, 600000L);
        Profiling.setEnabled(false);
        Profiling.reset();
    }

    String arch = OSUtil.is64BitPlatform() ? "64bit" : "32bit";
    logFine("OS: " + System.getProperty("os.name") + " (" + arch + ')');
    logFine("Java: " + JavaVersion.systemVersion().toString() + " (" + System.getProperty("java.vendor") + ')');
    logFine("Current time: " + new Date());
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long totalMemory = runtime.totalMemory();
    logFine("Max Memory: " + Format.formatBytesShort(maxMemory) + ", Total Memory: "
            + Format.formatBytesShort(totalMemory));
    if (!Desktop.isDesktopSupported() && isUIEnabled()) {
        logWarning("Desktop utility not supported");
    }

    // If we have a new config. clear the preferences.
    clearPreferencesOnConfigSwitch();

    // Load and set http proxy settings
    HTTPProxySettings.loadFromConfig(this);

    // #2179: Load from server. How to handle timeouts?
    // Command line option -c http://are.de
    ConfigurationLoader.loadAndMergeCLI(this);
    // Config entry in file
    ConfigurationLoader.loadAndMergeConfigURL(this);
    // Read from installer temp file
    ConfigurationLoader.loadAndMergeFromInstaller(this);

    if (verbose != ConfigurationEntry.VERBOSE.getValueBoolean(this)) {
        verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
        initLogger();
    }

    // Init paused only if user expects pause to be permanent or
    // "while I work"
    int pauseSecs = ConfigurationEntry.PAUSE_RESUME_SECONDS.getValueInt(getController());
    paused = PreferencesEntry.PAUSED.getValueBoolean(this)
            && (pauseSecs == Integer.MAX_VALUE || pauseSecs == 0);

    // Now set it, just in case it was paused in permanent mode.
    PreferencesEntry.PAUSED.setValue(this, paused);

    // Load and set http proxy settings again.
    HTTPProxySettings.loadFromConfig(this);

    // Initialize branding/preconfiguration of the client
    initDistribution();
    logFine("Build time: " + getBuildTime());
    logInfo("Program version " + PROGRAM_VERSION);

    if (getDistribution().getBinaryName().toLowerCase().contains("powerfolder")) {
        Debug.writeSystemProperties();
    }

    if (ConfigurationEntry.KILL_RUNNING_INSTANCE.getValueBoolean(this)) {
        killRunningInstance();
    }
    FolderList.removeMemberFiles(this);

    // Initialize plugins
    setupProPlugins();
    pluginManager = new PluginManager(this);
    pluginManager.init();

    // create node manager
    nodeManager = new NodeManager(this);

    // Only one task brother left...
    taskManager = new PersistentTaskManager(this);

    // Folder repository
    folderRepository = new FolderRepository(this);
    setLoadingCompletion(0, 10);

    // Create transfer manager
    // If this is a unit test it might have been set before.
    try {
        transferManager = transferManagerFactory.call();
    } catch (Exception e) {
        logSevere("Exception", e);
    }

    reconnectManager = new ReconnectManager(this);
    // Create os client
    osClient = new ServerClient(this);

    if (isUIEnabled()) {
        uiController = new UIController(this);
        if (ConfigurationEntry.USER_INTERFACE_LOCKED.getValueBoolean(this)) {
            // Don't let the user pass this step.
            new UIUnLockDialog(this).openAndWait();
        }
    }

    setLoadingCompletion(10, 20);

    // The io provider.
    ioProvider = new IOProvider(this);
    ioProvider.start();

    // Set hostname by CLI
    if (commandLine != null && commandLine.hasOption('d')) {
        String host = commandLine.getOptionValue("d");
        if (StringUtils.isNotBlank(host)) {
            InetSocketAddress addr = Util.parseConnectionString(host);
            if (addr != null) {
                ConfigurationEntry.HOSTNAME.setValue(this, addr.getHostName());
                ConfigurationEntry.NET_BIND_PORT.setValue(this, addr.getPort());
            }
        }
    }

    // initialize dyndns manager
    dyndnsManager = new DynDnsManager(this);

    setLoadingCompletion(20, 30);

    // initialize listener on local port
    if (!initializeListenerOnLocalPort()) {
        return;
    }
    if (!isUIEnabled()) {
        // Disable paused function
        paused = false;
    }

    setLoadingCompletion(30, 35);

    // Start the nodemanager
    nodeManager.init();
    if (!ProUtil.isRunningProVersion()) {
        // Nodemanager gets later (re) started by ProLoader.
        nodeManager.start();
    }

    setLoadingCompletion(35, 60);
    securityManager = new SecurityManagerClient(this, osClient);

    // init repo (read folders)
    folderRepository.init();
    logInfo("Dataitems: " + Debug.countDataitems(Controller.this));
    // init of folders takes rather long so a big difference with
    // last number to get smooth bar... ;-)
    setLoadingCompletion(60, 65);

    // start repo maintainance Thread
    folderRepository.start();
    setLoadingCompletion(65, 70);

    // Start the transfer manager thread
    transferManager.start();
    setLoadingCompletion(70, 75);

    // Initalize rcon manager
    startRConManager();

    setLoadingCompletion(75, 80);

    // Start all configured listener if not in paused mode
    startConfiguredListener();
    setLoadingCompletion(80, 85);

    // open broadcast listener
    openBroadcastManager();
    setLoadingCompletion(85, 90);

    // Controller now started
    started = true;
    startTime = new Date();

    // Now taskmanager
    taskManager.start();

    logInfo("Controller started");

    // dyndns updater
    /*
     * boolean onStartUpdate = ConfigurationEntry.DYNDNS_AUTO_UPDATE
     * .getValueBoolean(this).booleanValue(); if (onStartUpdate) {
     * getDynDnsManager().onStartUpdate(); }
     */
    dyndnsManager.updateIfNessesary();

    setLoadingCompletion(90, 100);

    // Login to OS
    if (Feature.OS_CLIENT.isEnabled()) {
        try {
            osClient.loginWithLastKnown();
        } catch (Exception e) {
            logWarning("Unable to login with last known username. " + e);
            logFiner(e);
        }
    }

    // Start Plugins
    pluginManager.start();

    // open UI
    if (isConsoleMode()) {
        logFine("Running in console");
    } else {
        logFine("Opening UI");
        openUI();
    }

    // Load anything that was not handled last time.
    loadPersistentObjects();

    setLoadingCompletion(100, 100);
    if (!isConsoleMode()) {
        uiController.hideSplash();
    }

    if (ConfigurationEntry.AUTO_CONNECT.getValueBoolean(this)) {
        // Now start the connecting process
        reconnectManager.start();
    } else {
        logFine("Not starting reconnection process. " + "Config auto.connect set to false");
    }
    // Start connecting to OS client.
    if (Feature.OS_CLIENT.isEnabled() && ConfigurationEntry.SERVER_CONNECT.getValueBoolean(this)) {
        osClient.start();
    } else {
        logInfo("Not connecting to server (" + osClient.getServerString() + "): Disabled");
    }

    // Setup our background working tasks
    setupPeriodicalTasks();

    if (MacUtils.isSupported()) {
        if (isFirstStart()) {
            MacUtils.getInstance().setPFStartup(true, this);
        }
        MacUtils.getInstance().setAppReOpenedListener(this);
    }

    if (pauseSecs == 0) {
        // Activate adaptive logic
        setPaused(paused);
    }
}

From source file:org.apache.hadoop.mapred.CoronaJobTracker.java

private void initializePJTClient() throws IOException {
    InetSocketAddress address = NetUtils
            .createSocketAddr(new CoronaConf(conf).getProxyJobTrackerThriftAddress());
    pjtTransport = new TFramedTransport(new TSocket(address.getHostName(), address.getPort()));
    pjtClient = new CoronaProxyJobTrackerService.Client(new TBinaryProtocol(pjtTransport));
    try {//from www. j a v a 2s .c o  m
        pjtTransport.open();
    } catch (TException e) {
        LOG.info("Transport Exception: ", e);
    }
}

From source file:org.apache.hadoop.mapred.CoronaJobTracker.java

private void startInfoServer() throws IOException {
    InetSocketAddress infoSocAddr = NetUtils
            .createSocketAddr(java.net.InetAddress.getLocalHost().getCanonicalHostName(), 0);
    String infoBindAddress = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("jt", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("job.tracker", this);
    infoServer.start();//from w  w  w . j  a  v  a 2  s .  c  om
    this.infoPort = this.infoServer.getPort();

    String hostname = java.net.InetAddress.getLocalHost().getCanonicalHostName();
    this.conf.set("mapred.job.tracker.http.address", hostname + ":" + this.infoPort);
    this.conf.setInt("mapred.job.tracker.info.port", this.infoPort);
    this.conf.set("mapred.job.tracker.info.bindAddress", hostname);

    LOG.info("JobTracker webserver: " + this.infoPort);
}

From source file:org.apache.hadoop.mapred.CoronaJobTracker.java

@Override
public void restoreTaskLaunch(TaskLaunch launch) {
    TaskAttemptID attemptId = launch.getTaskId();
    TaskInProgress tip = job.getTaskInProgress(attemptId.getTaskID());
    String trackerName = launch.getTrackerName();
    InetSocketAddress trackerAddr = launch.getAddress();
    // Update trackerName -> trackerAddress mapping in ResourceTracker
    resourceTracker.updateTrackerAddr(trackerName,
            new InetAddress(trackerAddr.getHostName(), trackerAddr.getPort()));
    Task task = null;//from w w w .j a v a  2 s . c  o m
    if (tip.isMapTask()) {
        task = job.forceNewMapTaskForTip(trackerName, trackerAddr.getHostName(), tip);
    } else {
        task = job.forceNewReduceTaskForTip(trackerName, trackerAddr.getHostName(), tip);
    }
    if (task != null && task.getTaskID().equals(attemptId)) {
        TaskAttemptID taskId = task.getTaskID();
        Integer grantId = launch.getGrantId();
        taskLookupTable.createTaskEntry(taskId, trackerName, tip, grantId);
        // Skip launching task, but add to expire logic
        expireTasks.addNewTask(task.getTaskID());
        trackerStats.recordTask(trackerName);
    } else {
        LOG.error("Failed to register restored task " + attemptId);
    }
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS./*from  w w  w. j a va  2 s .co  m*/
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}