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:com.beyondj.gateway.handlers.detecting.DetectingGateway.java

public void handle(final SocketWrapper socket) {
    shutdownTacker.retain();//from www. ja v a 2s  .c  o  m
    receivedConnectionAttempts.incrementAndGet();
    socketsConnecting.add(socket);

    if (connectionTimeout > 0) {
        vertx.setTimer(connectionTimeout, new Handler<Long>() {
            public void handle(Long timerID) {
                if (socketsConnecting.contains(socket)) {
                    handleConnectFailure(socket, String
                            .format("Gateway client '%s' protocol detection timeout.", socket.remoteAddress()));
                }
            }
        });
    }

    ReadStream<ReadStream> readStream = socket.readStream();
    readStream.exceptionHandler(new Handler<Throwable>() {
        @Override
        public void handle(Throwable e) {
            handleConnectFailure(socket,
                    String.format("Failed to route gateway client '%s' due to: %s", socket.remoteAddress(), e));
        }
    });
    readStream.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void event) {
            handleConnectFailure(socket,
                    String.format("Gateway client '%s' closed the connection before it could be routed.",
                            socket.remoteAddress()));
        }
    });
    readStream.dataHandler(new Handler<Buffer>() {
        Buffer received = new Buffer();

        @Override
        public void handle(Buffer event) {
            received.appendBuffer(event);
            for (final Protocol protocol : protocols) {
                if (protocol.matches(received)) {
                    if ("ssl".equals(protocol.getProtocolName())) {

                        LOG.info(String.format("SSL Connection from '%s'", socket.remoteAddress()));
                        String disabledCypherSuites = null;
                        String enabledCipherSuites = null;
                        if (sslConfig != null) {
                            disabledCypherSuites = sslConfig.getDisabledCypherSuites();
                            enabledCipherSuites = sslConfig.getEnabledCipherSuites();
                        }
                        if (sslContext == null) {
                            try {
                                if (sslConfig != null) {
                                    sslContext = SSLContext.getInstance(sslConfig.getProtocol());
                                    sslContext.init(sslConfig.getKeyManagers(), sslConfig.getTrustManagers(),
                                            null);
                                } else {
                                    sslContext = SSLContext.getDefault();
                                }
                            } catch (Exception e) {
                                handleConnectFailure(socket, "Could initialize SSL: " + e);
                                return;
                            }
                        }

                        // lets wrap it up in a SslSocketWrapper.
                        SslSocketWrapper sslSocketWrapper = new SslSocketWrapper(socket);
                        sslSocketWrapper.putBackHeader(received);
                        sslSocketWrapper.initServer(sslContext, clientAuth, disabledCypherSuites,
                                enabledCipherSuites);
                        DetectingGateway.this.handle(sslSocketWrapper);
                        return;

                    } else if ("http".equals(protocol.getProtocolName())) {
                        InetSocketAddress target = getHttpGateway();
                        if (target != null) {
                            try {
                                URI url = new URI("http://" + target.getHostString() + ":" + target.getPort());
                                LOG.info(String.format("Connecting '%s' to '%s:%d' using the http protocol",
                                        socket.remoteAddress(), url.getHost(), url.getPort()));
                                ConnectionParameters params = new ConnectionParameters();
                                params.protocol = "http";
                                createClient(params, socket, url, received);
                                return;
                            } catch (URISyntaxException e) {
                                handleConnectFailure(socket, "Could not build valid connect URI: " + e);
                                return;
                            }
                        } else {
                            handleConnectFailure(socket, "No http gateway available for the http protocol");
                            return;
                        }
                    } else {
                        protocol.snoopConnectionParameters(socket, received,
                                new Handler<ConnectionParameters>() {
                                    @Override
                                    public void handle(ConnectionParameters connectionParameters) {
                                        // this will install a new dataHandler on the socket.
                                        if (connectionParameters.protocol == null)
                                            connectionParameters.protocol = protocol.getProtocolName();
                                        if (connectionParameters.protocolSchemes == null)
                                            connectionParameters.protocolSchemes = protocol
                                                    .getProtocolSchemes();
                                        route(socket, connectionParameters, received);
                                    }
                                });
                        return;
                    }
                }
            }
            if (received.length() >= maxProtocolIdentificationLength) {
                handleConnectFailure(socket,
                        "Connection did not use one of the enabled protocols " + getProtocolNames());
            }
        }
    });
}

From source file:com.xebialabs.overthere.telnet.TelnetConnection.java

public TelnetConnection(ConnectionOptions options, AddressPortMapper mapper, OverthereFile workingDirectory) {
    String unmappedAddress = options.get(ADDRESS);
    int unmappedPort = options.get(PORT, connectionType.getDefaultPort(options));
    InetSocketAddress addressPort = mapper.map(createUnresolved(unmappedAddress, unmappedPort));

    this.os = options.getEnum(OPERATING_SYSTEM, OperatingSystemFamily.class);
    this.connectionTimeoutMillis = options.getInteger(CONNECTION_TIMEOUT_MILLIS,
            CONNECTION_TIMEOUT_MILLIS_DEFAULT);
    this.socketTimeoutMillis = options.getInteger(SOCKET_TIMEOUT_MILLIS, SOCKET_TIMEOUT_MILLIS_DEFAULT);

    this.address = addressPort.getHostName();
    this.port = addressPort.getPort();
    this.username = options.get(USERNAME);
    this.password = options.get(PASSWORD);
    this.mapper = mapper;
    this.workingDirectory = workingDirectory;
    this.protocol = options.get(PROTOCOL);

    checkIsWindowsHost(os, protocol, connectionType);
    checkNotNewStyleWindowsDomain(username, protocol, connectionType);

}

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java

public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uri = request.getRequestURI();

    String port = "";
    String host = "";

    int c = uri.indexOf(':');
    if (c >= 0) {
        port = uri.substring(c + 1);/* w  w  w.  j a  v  a2  s . co m*/
        host = uri.substring(0, c);
        if (host.indexOf('/') > 0)
            host = host.substring(host.indexOf('/') + 1);
    }

    InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port));

    // if
    // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false))
    // {
    // sendForbid(request,response,uri);
    // }
    // else
    {
        InputStream in = request.getInputStream();
        final OutputStream out = response.getOutputStream();

        final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort());

        response.setStatus(200);
        response.setHeader("Connection", "close");
        response.flushBuffer();

        //         try {
        //            Thread copy = new Thread(new Runnable() {
        //               public void run() {
        //                  try {
        IOUtils.copy(socket.getInputStream(), out);
        //                  } catch (IOException e) {
        //                     e.printStackTrace();
        //                  }
        //               }
        //            });
        //            copy.start();
        IOUtils.copy(in, socket.getOutputStream());
        //            copy.join();
        //            copy.join(10000);
        //         }
        //         catch (InterruptedException e) {
        //            e.printStackTrace();
        //         }
    }
}

From source file:edu.umass.cs.nio.JSONMessenger.java

@Override
public AddressMessenger<JSONObject> getClientMessenger(InetSocketAddress listenSockAddr) {
    AddressMessenger<JSONObject> msgr = this.getClientMessengerInternal();
    if (listenSockAddr == null)
        return msgr; // default
    if (msgr instanceof InterfaceNIOTransport && ((InterfaceNIOTransport<?, ?>) msgr)
            .getListeningSocketAddress().getPort() == (listenSockAddr.getPort()))
        return msgr;
    // else//from w ww .  j a  v a  2  s . c  om
    msgr = this.getSSLClientMessengerInternal();
    if (msgr instanceof InterfaceNIOTransport && ((InterfaceNIOTransport<?, ?>) msgr)
            .getListeningSocketAddress().getPort() == (listenSockAddr.getPort()))
        return msgr;

    assert (this.getListeningSocketAddress().getPort() == (listenSockAddr.getPort())) : this
            .getListeningSocketAddress() + " != " + listenSockAddr;

    return this;
}

From source file:org.jenkinsci.plugins.GithubSecurityRealm.java

/**
 * Returns the proxy to be used when connecting to the given URI.
 *///from w  w w .j  a v a  2  s  .co m
private HttpHost getProxy(HttpUriRequest method) throws URIException {
    ProxyConfiguration proxy = Jenkins.getInstance().proxy;
    if (proxy == null)
        return null; // defensive check

    Proxy p = proxy.createProxy(method.getURI().getHost());
    switch (p.type()) {
    case DIRECT:
        return null; // no proxy
    case HTTP:
        InetSocketAddress sa = (InetSocketAddress) p.address();
        return new HttpHost(sa.getHostName(), sa.getPort());
    case SOCKS:
    default:
        return null; // not supported yet
    }
}

From source file:com.hypersocket.netty.HttpRequestDispatcherHandler.java

private void processRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) throws IOException {

    HttpResponseServletWrapper nettyResponse = new HttpResponseServletWrapper(
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK), ctx.getChannel(),
            nettyRequest);/*from w w w .j  a  v  a  2s .  c o  m*/

    HypersocketSession session = server.setupHttpSession(nettyRequest.getHeaders("Cookie"),
            !server.isPlainPort((InetSocketAddress) ctx.getChannel().getLocalAddress()), nettyResponse);

    InetSocketAddress remoteAddress = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
    if (nettyRequest.containsHeader("X-Forwarded-For")) {
        String[] ips = nettyRequest.getHeader("X-Forwarded-For").split(",");
        remoteAddress = new InetSocketAddress(ips[0], remoteAddress.getPort());
    } else if (nettyRequest.containsHeader("Forwarded")) {
        StringTokenizer t = new StringTokenizer(nettyRequest.getHeader("Forwarded"), ";");
        while (t.hasMoreTokens()) {
            String[] pair = t.nextToken().split("=");
            if (pair.length == 2 && pair[0].equalsIgnoreCase("for")) {
                remoteAddress = new InetSocketAddress(pair[1], remoteAddress.getPort());
            }
        }
    }

    HttpRequestServletWrapper servletRequest = new HttpRequestServletWrapper(nettyRequest,
            (InetSocketAddress) ctx.getChannel().getLocalAddress(), remoteAddress,
            !server.isPlainPort((InetSocketAddress) ctx.getChannel().getLocalAddress()),
            server.getServletConfig().getServletContext(), session);

    Request.set(servletRequest);

    if (log.isDebugEnabled()) {
        synchronized (log) {
            log.debug("Begin Request <<<<<<<<<");
            log.debug(servletRequest.getMethod() + " " + servletRequest.getRequestURI() + " "
                    + servletRequest.getProtocol());
            Enumeration<String> headerNames = servletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String header = headerNames.nextElement();
                Enumeration<String> values = servletRequest.getHeaders(header);
                while (values.hasMoreElements()) {
                    log.debug(header + ": " + values.nextElement());
                }
            }
            log.debug("End Request <<<<<<<<<");
        }
    }

    if (ctx.getChannel().getLocalAddress() instanceof InetSocketAddress) {
        if (server.isPlainPort((InetSocketAddress) ctx.getChannel().getLocalAddress())
                && server.isHttpsRequired()) {
            // Redirect the plain port to SSL
            String host = nettyRequest.getHeader(HttpHeaders.HOST);
            if (host == null) {
                nettyResponse.sendError(400, "No Host Header");
            } else {
                int idx;
                if ((idx = host.indexOf(':')) > -1) {
                    host = host.substring(0, idx);
                }
                nettyResponse.sendRedirect("https://" + host
                        + (server.getHttpsPort() != 443 ? ":" + String.valueOf(server.getHttpsPort()) : "")
                        + nettyRequest.getUri());
            }
            sendResponse(servletRequest, nettyResponse, false);
            return;
        }
    }

    if (nettyRequest.containsHeader("Upgrade")) {
        for (WebsocketHandler handler : server.getWebsocketHandlers()) {
            if (handler.handlesRequest(servletRequest)) {
                try {
                    handler.acceptWebsocket(servletRequest, nettyResponse, new WebsocketConnectCallback(
                            ctx.getChannel(), servletRequest, nettyResponse, handler), this);
                } catch (AccessDeniedException ex) {
                    nettyResponse.setStatus(HttpStatus.SC_FORBIDDEN);
                    sendResponse(servletRequest, nettyResponse, false);
                } catch (UnauthorizedException ex) {
                    nettyResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    sendResponse(servletRequest, nettyResponse, false);
                }
                return;
            }
        }
    } else {
        for (HttpRequestHandler handler : server.getHttpHandlers()) {
            if (log.isDebugEnabled()) {
                log.debug("Checking HTTP handler: " + handler.getName());
            }
            if (handler.handlesRequest(servletRequest)) {
                if (log.isDebugEnabled()) {
                    log.debug(handler.getName() + " is processing HTTP request");
                }
                handler.handleHttpRequest(servletRequest, nettyResponse, this);
                return;
            }
        }
    }

    nettyResponse.sendError(HttpStatus.SC_NOT_FOUND);
    nettyResponse.setContentLength(0);
    sendResponse(servletRequest, nettyResponse, false);

    if (log.isDebugEnabled()) {
        log.debug("Leaving HttpRequestDispatcherHandler processRequest");
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) {
    rmId = (rmId == null) ? "" : ("." + rmId);
    InetSocketAddress address;
    if (sslEnabled) {
        address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId,
                YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS,
                YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT);
    } else {/* w ww .  jav  a 2  s .c  om*/
        address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId,
                YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT);
    }
    LOG.info("rm webapp address setting {}", address);
    LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS));
    InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address);
    InetAddress resolved = resolvedSocketAddress.getAddress();
    if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) {
        try {
            resolvedSocketAddress = InetSocketAddress
                    .createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort());
        } catch (UnknownHostException e) {
            //Ignore and fallback.
        }
    }
    return resolvedSocketAddress;
}

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

public ProxyJobTracker(CoronaConf conf) throws IOException {
    this.conf = conf;
    fs = FileSystem.get(conf);//  www . ja v  a 2 s .c om
    String infoAddr = conf.get("mapred.job.tracker.corona.proxyaddr", "0.0.0.0:0");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    String infoBindAddress = infoSocAddr.getHostName();
    int port = infoSocAddr.getPort();
    LOCALMACHINE = infoBindAddress;
    startTime = getClock().getTime();

    CoronaConf coronaConf = new CoronaConf(conf);
    InetSocketAddress rpcSockAddr = NetUtils.createSocketAddr(coronaConf.getProxyJobTrackerAddress());
    rpcServer = RPC.getServer(this, rpcSockAddr.getHostName(), rpcSockAddr.getPort(),
            conf.getInt("corona.proxy.job.tracker.handler.count", 10), false, conf);
    rpcServer.start();

    LOG.info("ProxyJobTracker RPC Server up at " + rpcServer.getListenerAddress());

    infoServer = new HttpServer("proxyjt", infoBindAddress, port, port == 0, conf);
    infoServer.setAttribute("proxy.job.tracker", this);
    infoServer.setAttribute("conf", conf);
    infoServer.addServlet("proxy", "/proxy", ProxyJobTrackerServlet.class);
    // initialize history parameters.
    JobConf jobConf = new JobConf(conf);
    boolean historyInitialized = JobHistory.init(this, jobConf, this.LOCALMACHINE, this.startTime);
    if (historyInitialized) {
        JobHistory.initDone(jobConf, fs);
        String historyLogDir = JobHistory.getCompletedJobHistoryLocation().toString();
        FileSystem historyFS = new Path(historyLogDir).getFileSystem(conf);
        infoServer.setAttribute("historyLogDir", historyLogDir);
        infoServer.setAttribute("fileSys", historyFS);
    }
    infoServer.start();
    LOCALPORT = infoServer.getPort();

    context = MetricsUtil.getContext("mapred");
    metricsRecord = MetricsUtil.createRecord(context, "proxyjobtracker");
    context.registerUpdater(this);

    expireUnusedFilesInCache = new ExpireUnusedFilesInCache(conf, getClock(), new Path(getSystemDir()));
    expireUnusedFilesInCache.setName("Cache File cleanup thread");
    expireUnusedFilesInCache.start();

    // 10 days
    long clearJobFileThreshold = conf.getLong("mapred.job.file.expirethreshold", 864000000L);

    long clearJobFileInterval = conf.getLong("mapred.job.file.checkinterval", 86400000L);

    expireUnusedJobFiles = new ExpireUnusedJobFiles(getClock(), conf, new Path(getSystemDir()),
            UNUSED_JOBFILE_PATTERN, clearJobFileThreshold, clearJobFileInterval);
    expireUnusedJobFiles.setName("Job File Cleanup Thread");
    expireUnusedJobFiles.start();

    long clearJobHistoryThreshold = conf.getLong("mapred.job.history.expirethreshold", 864000000L);

    long clearJobHistoryInterval = conf.getLong("mapred.job.history.checkinterval", 86400000L);

    expireUnusedJobHistory = new ExpireUnusedJobFiles(getClock(), conf, new Path(conf.getSessionsLogDir()),
            UNUSED_JOBHISTORY_PATTERN, clearJobHistoryThreshold, clearJobHistoryInterval);

    expireUnusedJobHistory.setName("Job History Cleanup Thread");
    expireUnusedJobHistory.start();
    sessionHistoryManager = new SessionHistoryManager();
    sessionHistoryManager.setConf(conf);

    String target = conf.getProxyJobTrackerThriftAddress();
    InetSocketAddress addr = NetUtils.createSocketAddr(target);
    LOG.info("Trying to start the Thrift Server at: " + target);
    ServerSocket serverSocket = new ServerSocket(addr.getPort());
    thriftServer = TFactoryBasedThreadPoolServer
            .createNewServer(new CoronaProxyJobTrackerService.Processor(this), serverSocket, 5000);
    thriftServerThread = new TServerThread(thriftServer);
    thriftServerThread.start();
    LOG.info("Thrift server started on: " + target);
}

From source file:org.reunionemu.jreunion.server.Network.java

public boolean register(InetSocketAddress address) {
    try {//from   w  w w  .jav a2 s  .c o  m
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(address);
        serverChannel.configureBlocking(false);
        synchronized (this) {
            selector.wakeup();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        }

    } catch (Exception e) {
        if (e instanceof BindException) {
            LoggerFactory.getLogger(Network.class)
                    .error("Port " + address.getPort() + " not available. Is the server already running?", e);
            return false;
        }
    }
    return true;
}

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

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

    ProtocolServer server = null;/*ww  w .  j  a  va  2  s  .  c o  m*/
    try {
        server = createServer(createProtocol(new TestPassCmdHandler()), address);
        server.bind();

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

        assertThat(client.login("invalid", "invalid")).isFalse();
        assertThat(client.logout()).isTrue();

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

}