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:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

/**
 * @param config// w  w w.java 2  s. c  om
 *          initial configuration
 */
@SuppressWarnings("deprecation")
public MiniAccumuloClusterImpl(MiniAccumuloConfigImpl config) throws IOException {

    this.config = config.initialize();

    mkdirs(config.getConfDir());
    mkdirs(config.getLogDir());
    mkdirs(config.getLibDir());
    mkdirs(config.getLibExtDir());

    if (!config.useExistingInstance()) {
        if (!config.useExistingZooKeepers())
            mkdirs(config.getZooKeeperDir());
        mkdirs(config.getWalogDir());
        mkdirs(config.getAccumuloDir());
    }

    if (config.useMiniDFS()) {
        File nn = new File(config.getAccumuloDir(), "nn");
        mkdirs(nn);
        File dn = new File(config.getAccumuloDir(), "dn");
        mkdirs(dn);
        File dfs = new File(config.getAccumuloDir(), "dfs");
        mkdirs(dfs);
        Configuration conf = new Configuration();
        conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY, nn.getAbsolutePath());
        conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY, dn.getAbsolutePath());
        conf.set(DFSConfigKeys.DFS_REPLICATION_KEY, "1");
        conf.set(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, "1");
        conf.set("dfs.support.append", "true");
        conf.set("dfs.datanode.synconclose", "true");
        conf.set("dfs.datanode.data.dir.perm", MiniDFSUtil.computeDatanodeDirectoryPermission());
        String oldTestBuildData = System.setProperty("test.build.data", dfs.getAbsolutePath());
        miniDFS = new MiniDFSCluster.Builder(conf).build();
        if (oldTestBuildData == null)
            System.clearProperty("test.build.data");
        else
            System.setProperty("test.build.data", oldTestBuildData);
        miniDFS.waitClusterUp();
        InetSocketAddress dfsAddress = miniDFS.getNameNode().getNameNodeAddress();
        dfsUri = "hdfs://" + dfsAddress.getHostName() + ":" + dfsAddress.getPort();
        File coreFile = new File(config.getConfDir(), "core-site.xml");
        writeConfig(coreFile, Collections.singletonMap("fs.default.name", dfsUri).entrySet());
        File hdfsFile = new File(config.getConfDir(), "hdfs-site.xml");
        writeConfig(hdfsFile, conf);

        Map<String, String> siteConfig = config.getSiteConfig();
        siteConfig.put(Property.INSTANCE_DFS_URI.getKey(), dfsUri);
        siteConfig.put(Property.INSTANCE_DFS_DIR.getKey(), "/accumulo");
        config.setSiteConfig(siteConfig);
    } else if (config.useExistingInstance()) {
        dfsUri = CachedConfiguration.getInstance().get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY);
    } else {
        dfsUri = "file:///";
    }

    File clientConfFile = config.getClientConfFile();
    // Write only the properties that correspond to ClientConfiguration properties
    writeConfigProperties(clientConfFile, Maps.filterEntries(config.getSiteConfig(),
            v -> ClientConfiguration.ClientProperty.getPropertyByKey(v.getKey()) != null));

    File siteFile = new File(config.getConfDir(), "accumulo-site.xml");
    writeConfig(siteFile, config.getSiteConfig().entrySet());

    if (!config.useExistingInstance() && !config.useExistingZooKeepers()) {
        zooCfgFile = new File(config.getConfDir(), "zoo.cfg");
        FileWriter fileWriter = new FileWriter(zooCfgFile);

        // zookeeper uses Properties to read its config, so use that to write in order to properly escape things like Windows paths
        Properties zooCfg = new Properties();
        zooCfg.setProperty("tickTime", "2000");
        zooCfg.setProperty("initLimit", "10");
        zooCfg.setProperty("syncLimit", "5");
        zooCfg.setProperty("clientPortAddress", "127.0.0.1");
        zooCfg.setProperty("clientPort", config.getZooKeeperPort() + "");
        zooCfg.setProperty("maxClientCnxns", "1000");
        zooCfg.setProperty("dataDir", config.getZooKeeperDir().getAbsolutePath());
        zooCfg.store(fileWriter, null);

        fileWriter.close();
    }

    // disable audit logging for mini....
    InputStream auditStream = this.getClass().getResourceAsStream("/auditLog.xml");

    if (auditStream != null) {
        FileUtils.copyInputStreamToFile(auditStream, new File(config.getConfDir(), "auditLog.xml"));
    }

    clusterControl = new MiniAccumuloClusterControl(this);
}

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

/**
 * @param taskid/*from  ww w  .j  a  v a  2  s .c  om*/
 * @param workDir
 * @param classPaths
 * @param logSize
 * @return
 * @throws IOException
 */
private Vector<String> getVMArgs(TaskAttemptID taskid, File workDir, List<String> classPaths, long logSize)
        throws IOException {
    Vector<String> vargs = new Vector<String>(8);
    File jvm = // use same jvm as parent
            new File(new File(System.getProperty("java.home"), "bin"), "java");

    vargs.add(jvm.toString());

    // Add child (task) java-vm options.
    //
    // The following symbols if present in mapred.{map|reduce}.child.java.opts 
    // value are replaced:
    // + @taskid@ is interpolated with value of TaskID.
    // Other occurrences of @ will not be altered.
    //
    // Example with multiple arguments and substitutions, showing
    // jvm GC logging, and start of a passwordless JVM JMX agent so can
    // connect with jconsole and the likes to watch child memory, threads
    // and get thread dumps.
    //
    //  <property>
    //    <name>mapred.map.child.java.opts</name>
    //    <value>-Xmx 512M -verbose:gc -Xloggc:/tmp/@taskid@.gc \
    //           -Dcom.sun.management.jmxremote.authenticate=false \
    //           -Dcom.sun.management.jmxremote.ssl=false \
    //    </value>
    //  </property>
    //
    //  <property>
    //    <name>mapred.reduce.child.java.opts</name>
    //    <value>-Xmx 1024M -verbose:gc -Xloggc:/tmp/@taskid@.gc \
    //           -Dcom.sun.management.jmxremote.authenticate=false \
    //           -Dcom.sun.management.jmxremote.ssl=false \
    //    </value>
    //  </property>
    //
    String javaOpts = getChildJavaOpts(conf, JobConf.DEFAULT_MAPRED_TASK_JAVA_OPTS);
    javaOpts = javaOpts.replace("@taskid@", taskid.toString());
    String[] javaOptsSplit = javaOpts.split(" ");

    // Add java.library.path; necessary for loading native libraries.
    //
    // 1. To support native-hadoop library i.e. libhadoop.so, we add the 
    //    parent processes' java.library.path to the child. 
    // 2. We also add the 'cwd' of the task to it's java.library.path to help 
    //    users distribute native libraries via the DistributedCache.
    // 3. The user can also specify extra paths to be added to the 
    //    java.library.path via mapred.{map|reduce}.child.java.opts.
    //
    String libraryPath = System.getProperty("java.library.path");
    if (libraryPath == null) {
        libraryPath = workDir.getAbsolutePath();
    } else {
        libraryPath += SYSTEM_PATH_SEPARATOR + workDir;
    }
    boolean hasUserLDPath = false;
    for (int i = 0; i < javaOptsSplit.length; i++) {
        if (javaOptsSplit[i].startsWith("-Djava.library.path=")) {
            javaOptsSplit[i] += SYSTEM_PATH_SEPARATOR + libraryPath;
            hasUserLDPath = true;
            break;
        }
    }
    if (!hasUserLDPath) {
        vargs.add("-Djava.library.path=" + libraryPath);
    }
    for (int i = 0; i < javaOptsSplit.length; i++) {
        vargs.add(javaOptsSplit[i]);
    }

    Path childTmpDir = createChildTmpDir(workDir, conf, false);
    vargs.add("-Djava.io.tmpdir=" + childTmpDir);

    // Add classpath.
    vargs.add("-classpath");
    String classPath = StringUtils.join(SYSTEM_PATH_SEPARATOR, classPaths);
    vargs.add(classPath);

    // Setup the log4j prop
    setupLog4jProperties(vargs, taskid, logSize);

    if (conf.getProfileEnabled()) {
        if (conf.getProfileTaskRange(t.isMapTask()).isIncluded(t.getPartition())) {
            File prof = TaskLog.getTaskLogFile(taskid, t.isTaskCleanupTask(), TaskLog.LogName.PROFILE);
            vargs.add(String.format(conf.getProfileParams(), prof.toString()));
        }
    }

    // Add main class and its arguments 
    vargs.add(Child.class.getName()); // main of Child
    // pass umbilical address
    InetSocketAddress address = tracker.getTaskTrackerReportAddress();
    vargs.add(address.getAddress().getHostAddress());
    vargs.add(Integer.toString(address.getPort()));
    vargs.add(taskid.toString()); // pass task identifier
    // pass task log location
    vargs.add(TaskLog.getAttemptDir(taskid, t.isTaskCleanupTask()).toString());
    return vargs;
}

From source file:com.cloud.bridge.io.S3CAStorBucketAdapter.java

private String castorURL(String mountedRoot, String bucket, String fileName) {
    // TODO: Replace this method with access to ScspClient's Locator,
    // or add read method that returns the body as an unread
    // InputStream for use by loadObject() and loadObjectRange().

    myClient(mountedRoot); // make sure castorNodes and castorPort initialized
    InetSocketAddress nodeAddr = _locator.locate();
    if (nodeAddr == null) {
        throw new ConfigurationException("Unable to locate CAStor node with locator " + _locator);
    }/*from  w  w w.  ja  va  2 s  .  c o  m*/
    InetAddress nodeInetAddr = nodeAddr.getAddress();
    if (nodeInetAddr == null) {
        _locator.foundDead(nodeAddr);
        throw new ConfigurationException(
                "Unable to resolve CAStor node name '" + nodeAddr.getHostName() + "' to IP address");
    }
    return "http://" + nodeInetAddr.getHostAddress() + ":" + nodeAddr.getPort() + "/" + bucket + "/" + fileName
            + (_domain == null ? "" : "?domain=" + _domain);
}

From source file:org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager.java

/**
 * Start PTT Endpoint which is given by axis2.xml
 *
 * @param inetSocketAddress         Socket Address of starting endpoint
 * @param defaultListeningIOReactor IO Reactor which  starts Endpoint
 * @param namePrefix                name specified for endpoint
 * @return Is started//from w  w  w  .  ja v  a2s  .com
 */
public boolean startPTTEndpoint(InetSocketAddress inetSocketAddress,
        DefaultListeningIOReactor defaultListeningIOReactor, String namePrefix) {
    try {
        return startEndpoint(inetSocketAddress, defaultListeningIOReactor, namePrefix) != null;
    } catch (Exception e) {
        log.error("Cannot Start PassThroughListeningEndpoint for port " + inetSocketAddress.getPort(), e);
        return false;
    }
}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testNoop() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//  w w w . j  a va  2s .c  o m
    try {
        String identifier = "id";
        TestPassCmdHandler factory = new TestPassCmdHandler();

        factory.add("valid", new MockMailbox(identifier));
        server = createServer(createProtocol(factory), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());

        assertThat(client.login("valid", "valid")).isTrue();
        assertThat(client.noop()).isTrue();
        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java

public VenusBIOConnection makeObject() throws Exception {
    Socket socket = new Socket();
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {/*from   w w  w .j  a  v a  2  s .c  o  m*/
        address = new InetSocketAddress(host, port);
    }

    socket.setSendBufferSize(sendBufferSize * 1024);
    socket.setReceiveBufferSize(receiveBufferSize * 1024);
    socket.setTcpNoDelay(tcpNoDelay);
    socket.setKeepAlive(keepAlive);
    try {
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }
        if (coTimeout > 0) {
            socket.connect(address, coTimeout);
        } else {
            socket.connect(address);
        }
    } catch (ConnectException e) {
        throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort());
    }

    VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis());
    byte[] bts = conn.read();
    HandshakePacket handshakePacket = new HandshakePacket();
    handshakePacket.init(bts);

    AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket);
    conn.write(authen.toByteArray());
    bts = conn.read();
    int type = AbstractServicePacket.getType(bts);
    if (type == PacketConstant.PACKET_TYPE_OK) {
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success");
        }
    } else if (type == PacketConstant.PACKET_TYPE_ERROR) {
        ErrorPacket error = new ErrorPacket();
        error.init(bts);
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code="
                    + error.errorCode + ",message=" + error.message + "}");
        }
        throw new AuthenticationException(error.message, error.errorCode);
    }

    return conn;
}

From source file:org.apache.hadoop.corona.ClusterManager.java

/**
 * Construct ClusterManager given {@link CoronaConf}
 *
 * @param conf the configuration for the ClusterManager
 * @param recoverFromDisk true if we are restarting after going down while
 *                        in Safe Mode//from   w w  w .j a va  2s . com
 * @throws IOException
 */
public ClusterManager(CoronaConf conf, boolean recoverFromDisk) throws IOException {
    this.conf = conf;
    HostsFileReader hostsReader = new HostsFileReader(conf.getHostsFile(), conf.getExcludesFile());
    initLegalTypes();
    metrics = new ClusterManagerMetrics(getTypes());

    if (recoverFromDisk) {
        recoverClusterManagerFromDisk(hostsReader);
    } else {
        File stateFile = new File(conf.getCMStateFile());
        if (stateFile.exists()) {
            throw new IOException("State file " + stateFile.getAbsolutePath()
                    + " exists, but recoverFromDisk is not set, delete the state file first");
        }
        LOG.info("Starting Cluster Manager with clean state");
        startTime = clock.getTime();
        lastRestartTime = startTime;
        nodeManager = new NodeManager(this, hostsReader);
        nodeManager.setConf(conf);
        sessionManager = new SessionManager(this);
        sessionNotifier = new SessionNotifier(sessionManager, this, metrics);
    }
    sessionManager.setConf(conf);
    sessionNotifier.setConf(conf);

    sessionHistoryManager = new SessionHistoryManager();
    sessionHistoryManager.setConf(conf);

    scheduler = new Scheduler(nodeManager, sessionManager, sessionNotifier, getTypes(), metrics, conf);
    scheduler.start();
    metrics.registerUpdater(scheduler, sessionNotifier);

    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(conf.getClusterManagerHttpAddress());
    infoServer = new HttpServer("cm", infoSocAddr.getHostName(), infoSocAddr.getPort(),
            infoSocAddr.getPort() == 0, conf);
    infoServer.setAttribute("cm", this);
    infoServer.start();

    hostName = infoSocAddr.getHostName();

    // We have not completely restored the nodeManager, sessionManager and the
    // sessionNotifier
    if (recoverFromDisk) {
        nodeManager.restoreAfterSafeModeRestart();
        sessionManager.restoreAfterSafeModeRestart();
        sessionNotifier.restoreAfterSafeModeRestart();
    }

    nodeRestarter = new CoronaNodeRestarter(conf, nodeManager);
    nodeRestarter.start();

    setSafeMode(false);
}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testEmptyInbox() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*from w  w w  . jav  a  2  s . c om*/
    try {
        String identifier = "id";
        TestPassCmdHandler handler = new TestPassCmdHandler();

        handler.add("valid", new MockMailbox(identifier));
        server = createServer(createProtocol(handler), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());

        assertThat(client.login("valid", "valid")).isTrue();
        POP3MessageInfo[] info = client.listMessages();
        assertThat(info.length).isEqualTo(0);

        info = client.listUniqueIdentifiers();
        assertThat(info.length).isEqualTo(0);
        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testRset() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/* w ww  .j  a  v  a 2 s .co m*/
    try {
        String identifier = "id";
        TestPassCmdHandler factory = new TestPassCmdHandler();

        factory.add("valid", new MockMailbox(identifier, MESSAGE1));
        server = createServer(createProtocol(factory), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());

        assertThat(client.login("valid", "valid")).isTrue();
        assertThat(client.listMessages().length).isEqualTo(1);
        assertThat(client.deleteMessage(1)).isTrue();
        assertThat(client.listMessages().length).isEqualTo(0);

        // call RSET. After this the deleted mark should be removed again
        assertThat(client.reset()).isTrue();
        assertThat(client.listMessages().length).isEqualTo(1);

        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.pop3.AbstractPOP3ServerTest.java

@Test
public void testStat() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*from   w w w .j a  v a2  s . c  om*/
    try {
        String identifier = "id";
        TestPassCmdHandler factory = new TestPassCmdHandler();

        factory.add("valid", new MockMailbox(identifier, MESSAGE1, MESSAGE2));
        server = createServer(createProtocol(factory), address);
        server.bind();

        POP3Client client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());

        assertThat(client.login("valid", "valid")).isTrue();
        POP3MessageInfo info = client.status();
        assertThat(info.size).isEqualTo((int) (MESSAGE1.meta.getSize() + MESSAGE2.meta.getSize()));
        assertThat(info.number).isEqualTo(2);
        assertThat(client.logout()).isTrue();

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}