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.hadoop.hdfs.server.namenode.Standby.java

Standby(AvatarNode avatarNode, Configuration startupConf, Configuration conf, InetSocketAddress nameNodeAddr,
        NamenodeProtocol primaryNamenode) throws IOException {
    this.running = true;
    this.avatarNode = avatarNode;
    this.metrics = avatarNode.getAvatarNodeMetrics();
    this.confg = conf;
    this.startupConf = startupConf;
    this.fsImage = avatarNode.getFSImage();
    this.fsnamesys = avatarNode.getNamesystem();
    this.sleepBetweenErrors = startupConf.getInt("hdfs.avatarnode.sleep", 5000);
    this.nameNodeAddr = nameNodeAddr;
    this.primaryNamenode = primaryNamenode;

    initSecondary(startupConf); // start webserver for secondary namenode

    this.machineName = DNS.getDefaultIP(conf.get(FSConstants.DFS_NAMENODE_DNS_INTERFACE, "default"));
    LOG.info("machineName=" + machineName);

    InetSocketAddress addr = NameNode.getClientProtocolAddress(conf);
    this.tmpImageFileForValidation = new File("/tmp",
            "hadoop_image." + addr.getAddress().getHostAddress() + ":" + addr.getPort());

    URI remoteJournalURI = avatarNode.getRemoteSharedEditsURI(conf);
    if (remoteJournalURI.getScheme().equals(NNStorage.LOCAL_URI_SCHEME)) {
        StorageDirectory remoteJournalStorage = fsImage.storage.new StorageDirectory(
                new File(remoteJournalURI.getPath()));
        remoteJournal = new FileJournalManager(remoteJournalStorage, null, null);
    } else if (remoteJournalURI.getScheme().equals(QuorumJournalManager.QJM_URI_SCHEME)) {
        // TODO for now we pass null for NameNodeMetrics
        // once we have shared log we will pass the actual metrics
        remoteJournal = new QuorumJournalManager(conf, remoteJournalURI, new NamespaceInfo(fsImage.storage),
                null, false);/*from w ww.j  a  va2  s.  c o  m*/
    } else {
        remoteJournal = FSEditLog.createJournal(conf, remoteJournalURI, new NamespaceInfo(fsImage.storage),
                null);
    }
    // we will start ingestion from the txid of the image
    this.currentSegmentTxId = avatarNode.getFSImage().storage.getMostRecentCheckpointTxId() + 1;
    this.inputStreamRetries = confg.getInt("dfs.ingest.retries", 30);
    checkpointStatus("No checkpoint initiated");
}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testRcptHookPermanentError() throws Exception {
    RcptHook hook = new RcptHook() {

        @Override/*from  w  ww.j a  v a  2  s  .c o  m*/
        public void init(Configuration config) throws ConfigurationException {

        }

        @Override
        public void destroy() {

        }

        public HookResult doRcpt(SMTPSession session, MailAddress sender, MailAddress rcpt) {
            if (RCPT1.equals(rcpt.toString())) {
                return new HookResult(HookReturnCode.DENY);
            } else {
                return new HookResult(HookReturnCode.DECLINED);
            }
        }

    };

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("localhost");
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.setSender(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.addRecipient(RCPT1);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.addRecipient(RCPT2);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

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

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testRcptHookTemporaryError() throws Exception {
    RcptHook hook = new RcptHook() {

        @Override//from  ww  w.  ja va2 s. co m
        public void init(Configuration config) throws ConfigurationException {

        }

        @Override
        public void destroy() {

        }

        public HookResult doRcpt(SMTPSession session, MailAddress sender, MailAddress rcpt) {
            if (RCPT1.equals(rcpt.toString())) {
                return new HookResult(HookReturnCode.DENYSOFT);
            } else {
                return new HookResult(HookReturnCode.DECLINED);
            }
        }

    };

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("localhost");
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.setSender(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.addRecipient(RCPT1);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativeTransient(client.getReplyCode()));

        client.addRecipient(RCPT2);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

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

}

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

@Override
public void initializeJob(String user, String jobid, Path credentials, Path jobConf,
        TaskUmbilicalProtocol taskTracker, InetSocketAddress ttAddr) throws IOException {
    List<String> command = new ArrayList<String>(Arrays.asList(taskControllerExe, user,
            localStorage.getDirsString(), Integer.toString(Commands.INITIALIZE_JOB.getValue()), jobid,
            credentials.toUri().getPath().toString(), jobConf.toUri().getPath().toString()));
    File jvm = // use same jvm as parent
            new File(new File(System.getProperty("java.home"), "bin"), "java");
    command.add(jvm.toString());//from  w w w .  j  av  a2s  .c o  m
    command.add("-classpath");
    command.add(System.getProperty("java.class.path"));
    command.add("-Dhadoop.log.dir=" + TaskLog.getBaseLogDir());
    command.add("-Dhadoop.root.logger=INFO,console");
    command.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    command.add(JobLocalizer.class.getName()); // main of JobLocalizer
    command.add(user);
    command.add(jobid);
    // add the task tracker's reporting address
    command.add(ttAddr.getHostName());
    command.add(Integer.toString(ttAddr.getPort()));
    String[] commandArray = command.toArray(new String[0]);
    ShellCommandExecutor shExec = new ShellCommandExecutor(commandArray);
    if (LOG.isDebugEnabled()) {
        LOG.debug("initializeJob: " + Arrays.toString(commandArray));
    }
    try {
        shExec.execute();
        if (LOG.isDebugEnabled()) {
            logOutput(shExec.getOutput());
        }
    } catch (ExitCodeException e) {
        int exitCode = shExec.getExitCode();
        logOutput(shExec.getOutput());
        throw new IOException("Job initialization failed (" + exitCode + ") with output: " + shExec.getOutput(),
                e);
    }
}

From source file:name.persistent.behaviours.RemoteDomainSupport.java

private HttpResponse resolveRemotePURL(InetSocketAddress addr, String source, String qs, String accept,
        String language, Set<String> via) throws IOException, InterruptedException {
    HTTPObjectClient client = HTTPObjectClient.getInstance();
    String url = qs == null ? source : source + "?" + qs;
    BasicHttpRequest req = new BasicHttpRequest("GET", url);
    if (accept != null) {
        req.setHeader("Accept", accept);
    }//w  w w .j  a v a  2  s  .c  o  m
    if (language != null) {
        req.setHeader("Accept-Language", language);
    }
    StringBuilder sb = new StringBuilder();
    for (String v : via) {
        if (v.contains(VIA) && (v.endsWith(VIA) || v.contains(VIA + ",")))
            throw new InternalServerError("Request Loop Detected\n" + via + "\n" + VIA);
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(v);
    }
    sb.append(VIA);
    req.setHeader("Via", sb.toString());
    try {
        HttpResponse resp = client.service(addr, req);
        if (!resp.containsHeader("Via")) {
            String original = "1.1 " + addr.getHostName();
            if (addr.getPort() != 80 && addr.getPort() != 443) {
                original += ":" + addr.getPort();
            }
            resp.addHeader("Via", original);
        }
        StatusLine status = resp.getStatusLine();
        if (status.getStatusCode() >= 500) {
            ProtocolVersion ver = status.getProtocolVersion();
            String phrase = status.getReasonPhrase();
            resp.setStatusLine(new BasicStatusLine(ver, 502, phrase));
            blackList.put(addr, Boolean.TRUE);
            return resp;
        } else {
            return resp;
        }
    } catch (GatewayTimeout e) {
        blackList.put(addr, Boolean.TRUE);
        return null;
    }
}

From source file:com.github.hrpc.rpc.Client.java

/**
 * Make a call, passing <code>rpcRequest</code>, to the IPC server defined by
 * <code>remoteId</code>, returning the rpc respond.
 *
 * @param rpcKind/* ww  w.  jav  a  2 s .c  o m*/
 * @param rpcRequest -  contains serialized method and method parameters
 * @param remoteId - the target rpc server
 * @param serviceClass - service class for RPC
 * @returns the rpc response
 * Throws exceptions if there are network problems or if the remote code
 * threw an exception.
 */
public Writable call(RPC.RpcKind rpcKind, Writable rpcRequest, ConnectionId remoteId, int serviceClass)
        throws IOException {
    final Call call = createCall(rpcKind, rpcRequest);
    Connection connection = getConnection(remoteId, call, serviceClass);
    try {
        connection.sendRpcRequest(call); // send the rpc request
    } catch (RejectedExecutionException e) {
        throw new IOException("connection has been closed", e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.warn("interrupted waiting to send rpc request to server", e);
        throw new IOException(e);
    }

    boolean interrupted = false;
    synchronized (call) {
        while (!call.done) {
            try {
                call.wait(); // wait for the result
            } catch (InterruptedException ie) {
                // save the fact that we were interrupted
                interrupted = true;
            }
        }

        if (interrupted) {
            // set the interrupt flag now that we are done waiting
            Thread.currentThread().interrupt();
        }

        if (call.error != null) {
            if (call.error instanceof RemoteException) {
                call.error.fillInStackTrace();
                throw call.error;
            } else { // local exception
                InetSocketAddress address = connection.getRemoteAddress();
                throw NetUtils.wrapException(address.getHostName(), address.getPort(), NetUtils.getHostname(),
                        0, call.error);
            }
        } else {
            return call.getRpcResponse();
        }
    }
}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testMessageHookPermanentError() throws Exception {
    TestMessageHook testHook = new TestMessageHook();

    MessageHook hook = new MessageHook() {

        @Override/*from www .j av  a 2  s.c  o  m*/
        public void init(Configuration config) throws ConfigurationException {

        }

        @Override
        public void destroy() {

        }

        public HookResult onMessage(SMTPSession session, MailEnvelope mail) {
            return new HookResult(HookReturnCode.DENY);
        }

    };

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;
    try {
        server = createServer(createProtocol(hook, testHook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("localhost");
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.setSender(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.addRecipient(RCPT2);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        assertFalse(client.sendShortMessageData(MSG1));
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

        Iterator<MailEnvelope> queued = testHook.getQueued().iterator();
        assertFalse(queued.hasNext());

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

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testMessageHookTemporaryError() throws Exception {
    TestMessageHook testHook = new TestMessageHook();

    MessageHook hook = new MessageHook() {

        @Override/*from  w w  w .  j  a  va 2 s .c om*/
        public void init(Configuration config) throws ConfigurationException {

        }

        @Override
        public void destroy() {

        }

        public HookResult onMessage(SMTPSession session, MailEnvelope mail) {
            return new HookResult(HookReturnCode.DENYSOFT);
        }

    };

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;
    try {
        server = createServer(createProtocol(hook, testHook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("localhost");
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.setSender(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.addRecipient(RCPT2);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        assertFalse(client.sendShortMessageData(MSG1));
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativeTransient(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

        Iterator<MailEnvelope> queued = testHook.getQueued().iterator();
        assertFalse(queued.hasNext());

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

}

From source file:org.apache.hadoop.hdfs.server.namenode.NameNode.java

/**
 * Initialize name-node.//  w  w w  .  ja va 2s  .  co  m
 * 
 * @param conf the configuration
 */
private void initialize(Configuration conf) throws IOException {
    InetSocketAddress socAddr = NameNode.getAddress(conf);
    UserGroupInformation.setConfiguration(conf);
    SecurityUtil.login(conf, DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY,
            DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY, socAddr.getHostName());
    int handlerCount = conf.getInt("dfs.namenode.handler.count", 10);

    // set service-level authorization security policy
    if (serviceAuthEnabled = conf.getBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
        ServiceAuthorizationManager.refresh(conf, new HDFSPolicyProvider());
    }

    myMetrics = NameNodeInstrumentation.create(conf);
    this.namesystem = new FSNamesystem(this, conf);

    if (UserGroupInformation.isSecurityEnabled()) {
        namesystem.activateSecretManager();
    }

    // create rpc server
    InetSocketAddress dnSocketAddr = getServiceRpcServerAddress(conf);
    if (dnSocketAddr != null) {
        int serviceHandlerCount = conf.getInt(DFSConfigKeys.DFS_NAMENODE_SERVICE_HANDLER_COUNT_KEY,
                DFSConfigKeys.DFS_NAMENODE_SERVICE_HANDLER_COUNT_DEFAULT);
        this.serviceRpcServer = RPC.getServer(this, dnSocketAddr.getHostName(), dnSocketAddr.getPort(),
                serviceHandlerCount, false, conf, namesystem.getDelegationTokenSecretManager());
        this.serviceRPCAddress = this.serviceRpcServer.getListenerAddress();
        setRpcServiceServerAddress(conf);
    }
    this.server = RPC.getServer(this, socAddr.getHostName(), socAddr.getPort(), handlerCount, false, conf,
            namesystem.getDelegationTokenSecretManager());

    // The rpc-server port can be ephemeral... ensure we have the correct info
    this.serverAddress = this.server.getListenerAddress();
    FileSystem.setDefaultUri(conf, getUri(serverAddress));
    LOG.info("Namenode up at: " + this.serverAddress);

    startHttpServer(conf);
    this.server.start(); //start RPC server   
    if (serviceRpcServer != null) {
        serviceRpcServer.start();
    }
    startTrashEmptier(conf);
}

From source file:org.apache.hadoop.hdfs.server.namenode.AvatarNodeNew.java

/**
 * Initialize AvatarNode//from  ww w.j a  v a  2 s. c om
 * @param conf the configuration
 */
private void initialize(Configuration conf) throws IOException {
    InetSocketAddress socAddr = AvatarNodeNew.getAddress(conf);

    int handlerCount = conf.getInt("hdfs.avatarnode.handler.count", 3);
    try {
        UserGroupInformation.setCurrentUser(UnixUserGroupInformation.login(conf));
    } catch (LoginException e) {

    }
    // create rpc server 
    this.server = RPC.getServer(this, socAddr.getHostName(), socAddr.getPort(), handlerCount, false, conf);

    // The rpc-server port can be ephemeral... ensure we have the 
    // correct info
    this.serverAddress = this.server.getListenerAddress();
    LOG.info("AvatarNode up at: " + this.serverAddress);
    this.server.start();
}