Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

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

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:eu.stratosphere.client.program.Client.java

/**
 * Creates a new instance of the class that submits the jobs to a job-manager.
 * at the given address using the default port.
 * //from   w ww  . jav a  2s  . com
 * @param jobManagerAddress Address and port of the job-manager.
 */
public Client(InetSocketAddress jobManagerAddress, Configuration config) {
    Preconditions.checkNotNull(config, "Configuration is null");
    this.configuration = config;
    configuration.setString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY,
            jobManagerAddress.getAddress().getHostAddress());
    configuration.setInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, jobManagerAddress.getPort());

    this.compiler = new PactCompiler(new DataStatistics(), new DefaultCostEstimator(), jobManagerAddress);

    //  Disable Local Execution when using a Client
    ContextEnvironment.disableLocalExecution();
}

From source file:org.apache.axis2.transport.p2p.pastry.PastryNodeUtils.java

/**
 * @param bootaddress/*w ww  .j  a  v a 2 s  .c  o  m*/
 * @param bindPort
 * @param environment -creates a new environment if null provided
 * @return
 * @throws IOException
 */
public PastryNode createNewNode(InetSocketAddress bootaddress, int bindPort, Environment environment)
        throws IOException {

    if (environment == null) {
        // Loads pastry settings
        this.setEnv(new Environment());

        // disable the UPnP setting (in case you are testing this on a NATted LAN)
        getEnv().getParameters().setString("nat_search_policy", "never");
    }
    // Generate the NodeIds
    NodeIdFactory nidFactory = new IPNodeIdFactory(bootaddress.getAddress(), bindPort, getEnv());

    PastryNodeFactory factory;

    // construct the PastryNodeFactory, this is how we use rice.pastry.socket
    //check if this is a test for localhost or real deployment with realIP
    if (bootaddress.getAddress().isLoopbackAddress()) {
        factory = new SocketPastryNodeFactory(nidFactory, bootaddress.getAddress(), bindPort, getEnv());
    } else {
        factory = new SocketPastryNodeFactory(nidFactory, bindPort, getEnv());
    }

    //  SocketPastryNodeFactory
    // construct a node
    PastryNode node = factory.newNode();

    return node;
}

From source file:at.bitfire.davdroid.mirakel.webdav.TlsSniSocketFactory.java

@Override
public Socket connectSocket(int timeout, Socket plain, HttpHost host, InetSocketAddress remoteAddr,
        InetSocketAddress localAddr, HttpContext context) throws IOException {
    Log.d(TAG, "Preparing direct SSL connection (without proxy) to " + host);

    // we'll rather use an SSLSocket directly
    plain.close();//from  ww w  .j a v a2  s . c o m

    // create a plain SSL socket, but don't do hostname/certificate verification yet
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(remoteAddr.getAddress(), host.getPort());
    setReasonableEncryption(ssl);

    // connect, set SNI, shake hands, verify, print connection info
    connectWithSNI(ssl, host.getHostName());

    return ssl;
}

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

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

    ProtocolServer server = null;/*from  ww  w  .j ava2  s  . c  o  m*/
    try {
        server = createServer(createProtocol(new ProtocolHandler[0]), address,
                Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
        server.bind();

        SMTPSClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.sendCommand("EHLO localhost");
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        boolean startTLSAnnounced = false;
        for (String reply : client.getReplyStrings()) {
            if (reply.toUpperCase(Locale.UK).endsWith("STARTTLS")) {
                startTLSAnnounced = true;
                break;
            }
        }
        assertTrue(startTLSAnnounced);

        assertTrue(client.execTLS());

        // TODO: Add back once commons-net 3.1.0 was released.
        // See: NET-421
        //
        //client.quit();
        //assertTrue("Reply="+ client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.disconnect();

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

}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestClientRMTokens.java

@Test
public void testShortCircuitRenewCancelSameHostDifferentPort() throws IOException, InterruptedException {
    InetSocketAddress rmAddr = NetUtils.createSocketAddr(InetAddress.getLocalHost().getHostName(), 123, null);
    checkShortCircuitRenewCancel(rmAddr, new InetSocketAddress(rmAddr.getAddress(), rmAddr.getPort() + 1),
            false);// w  w w . ja  v a 2  s  .c o  m
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientPlainConnectionFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException, ConnectTimeoutException {

    Socket sock;/*from   w  w w. j ava2 s  .  c  o m*/
    if (socket != null) {
        sock = socket;
    } else {
        sock = createSocket(context);
    }
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
    }
    return sock;
}

From source file:org.apache.axis2.transport.p2p.registry.RegistryApp.java

private void initialize(String bootIp, String bootPort, String bindPort)
        throws IOException, InterruptedException {

    PastryNodeUtils nodeUtils = new PastryNodeUtils();

    int bindport;

    if (bindPort == null) {

        bindport = nodeUtils.createRandomPort();

    } else {//from w  ww .ja va  2  s  .  com
        bindport = Integer.parseInt(bindPort);
    }

    log.debug("generated random port no for the Registry application :" + bindport);

    InetSocketAddress bootaddress = nodeUtils.getBootAddress(bootIp, Integer.parseInt(bootPort));

    this.env = new Environment();

    // Generate the NodeIds Randomly
    NodeIdFactory nidFactory = new RandomNodeIdFactory(env);

    PastryNodeFactory factory = null;

    if (bootaddress.getAddress().isLoopbackAddress()) {
        factory = new SocketPastryNodeFactory(nidFactory, bootaddress.getAddress(), bindport, env);
    } else {
        // construct the PastryNodeFactory, this is how we use rice.pastry.socket
        factory = new SocketPastryNodeFactory(nidFactory, bindport, env);
    }
    // construct a node, passing the null boothandle on the first loop will
    // cause the node to start its own ring
    PastryNode node = factory.newNode();

    // used for generating PastContent object Ids.
    // this implements the "hash function" for our DHT
    this.idf = new rice.pastry.commonapi.PastryIdFactory(env);

    // create a different storage root for each node
    String storageDirectory = "./" + baseDir + "/storage" + node.getId().hashCode();

    this.storageFile = new File(storageDirectory);

    // create the persistent part
    Storage store = new PersistentStorage(idf, storageDirectory, 4 * 1024 * 1024, node.getEnvironment());
    //Storage store = new MemoryStorage(idf);
    PastImpl app = new PastImpl(node, new StorageManagerImpl(idf, store,
            new LRUCache(new MemoryStorage(idf), 512 * 1024, node.getEnvironment())), 3, "");

    this.pastApp = app;

    node.boot(bootaddress);

    // the node may require sending several messages to fully boot into the ring
    synchronized (node) {
        while (!node.isReady() && !node.joinFailed()) {
            // delay so we don't busy-wait
            node.wait(500);

            // abort if can't join
            if (node.joinFailed()) {
                throw new IOException("Could not join the FreePastry ring.  Reason:" + node.joinFailedReason());
            }
        }
    }

    this.setInitialized(true);

    log.info("Finished creating new node for Registry " + node);

}

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

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    RequestV2 request = null;//ww  w . j a va  2s . c om
    RendererConfiguration renderer = null;
    String userAgentString = null;
    ArrayList<String> identifiers = new ArrayList<>();

    HttpRequest nettyRequest = this.nettyRequest = (HttpRequest) e.getMessage();

    InetSocketAddress remoteAddress = (InetSocketAddress) e.getChannel().getRemoteAddress();
    InetAddress ia = remoteAddress.getAddress();

    // Is the request from our own Cling service, i.e. self-originating?
    boolean isSelf = ia.getHostAddress().equals(PMS.get().getServer().getHost())
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT) != null
            && nettyRequest.headers().get(HttpHeaders.Names.USER_AGENT).contains("UMS/");

    // Filter if required
    if (isSelf || filterIp(ia)) {
        e.getChannel().close();
        LOGGER.trace(isSelf ? ("Ignoring self-originating request from " + ia + ":" + remoteAddress.getPort())
                : ("Access denied for address " + ia + " based on IP filter"));
        return;
    }

    LOGGER.trace("Opened request handler on socket " + remoteAddress);
    PMS.get().getRegistry().disableGoToSleep();
    request = new RequestV2(nettyRequest.getMethod().getName(), nettyRequest.getUri().substring(1));
    LOGGER.trace("Request: " + nettyRequest.getProtocolVersion().getText() + " : " + request.getMethod() + " : "
            + request.getArgument());

    if (nettyRequest.getProtocolVersion().getMinorVersion() == 0) {
        request.setHttp10(true);
    }

    HttpHeaders headers = nettyRequest.headers();

    // 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.
    if (renderer == null || !renderer.loaded) {
        // Attempt 2: try to recognize the renderer by matching headers
        renderer = RendererConfiguration.getRendererConfigurationByHeaders(headers.entries(), ia);
    }

    if (renderer != null) {
        request.setMediaRenderer(renderer);
    }

    Set<String> headerNames = headers.names();
    Iterator<String> iterator = headerNames.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        String headerLine = name + ": " + headers.get(name);
        LOGGER.trace("Received on socket: " + headerLine);

        if (headerLine.toUpperCase().startsWith("USER-AGENT")) {
            userAgentString = headerLine.substring(headerLine.indexOf(':') + 1).trim();
        }

        try {
            StringTokenizer s = new StringTokenizer(headerLine);
            String temp = s.nextToken();
            if (temp.toUpperCase().equals("SOAPACTION:")) {
                request.setSoapaction(s.nextToken());
            } else if (temp.toUpperCase().equals("CALLBACK:")) {
                request.setSoapaction(s.nextToken());
            } 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 {
                Matcher matcher = TIMERANGE_PATTERN.matcher(headerLine);
                if (matcher.find()) {
                    String first = matcher.group(1);
                    if (first != null) {
                        request.setTimeRangeStartString(first);
                    }
                    String end = matcher.group(2);
                    if (end != null) {
                        request.setTimeRangeEndString(end);
                    }
                } 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 known headers.
                    String lowerCaseHeaderLine = headerLine.toLowerCase();
                    for (String knownHeaderString : KNOWN_HEADERS) {
                        if (lowerCaseHeaderLine.startsWith(knownHeaderString)) {
                            isKnown = true;
                            break;
                        }
                    }

                    // It may be unusual but already known
                    if (!isKnown && 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 (Exception ee) {
            LOGGER.error("Error parsing HTTP headers", ee);
        }
    }

    // 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, ", "));
                PMS.get().setRendererFound(renderer);
            }
        } 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 (nettyRequest.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) {
        byte data[] = new byte[(int) HttpHeaders.getContentLength(nettyRequest)];
        ChannelBuffer content = nettyRequest.getContent();
        content.readBytes(data);
        request.setTextContent(new String(data, "UTF-8"));
    }

    LOGGER.trace(
            "HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());

    writeResponse(ctx, e, request, ia);
}

From source file:org.shelloid.netverif.NetVerifSocketImpl.java

@Override
public void connect(SocketAddress saddr, int timeout) throws IOException {
    InetSocketAddress iaddr = (InetSocketAddress) saddr;
    System.out.println("connect: " + iaddr);
    if (localAddr == null) {
        localAddr = InetAddress.getByName(NetVerifEngine.getInstance().getCurrentHost());
    }//from w  w  w.  j a v  a 2 s. c  o m
    this.localport = NetVerifEngine.getInstance().getAvailablePort(localAddr.getHostAddress());
    Continuation.suspend(new EventMeta(EventMeta.REASON.SOCKET_CONNECT, this, iaddr));
    this.address = iaddr.getAddress();
    this.port = iaddr.getPort();
}

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

@Override
public void run() {
    Request request = null;/*  w ww. j a v  a  2  s .c  o m*/
    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");
    }
}