Example usage for java.net Socket close

List of usage examples for java.net Socket close

Introduction

In this page you can find the example usage for java.net Socket close.

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null)
        return;/*from w ww.j  av  a 2 s . com*/

    Log.d(TAG, "Proxy processing");

    HttpResponse realResponse = download();
    if (realResponse == null)
        return;

    Log.d(TAG, "Proxy downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(TAG, "Proxy reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());
    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        // TODO: this is disabled until it is made optional
        //            if (h.getName().equals("Content-Type") && proxyInfo.isMpeg())
        //                httpString.append(h.getName()).append(": ").append("video/mpeg").append("\n");
        //            else
        Log.d(TAG, "  header->" + h.getName() + ": " + h.getValue());
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // start streaming content
        byte[] buff = new byte[1024 * 50];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (SocketException ex) {
        Log.e(TAG, "SocketException writing to client", ex);
        // avoid trying to close (because close() hangs in this situation, and for some reason
        // libvlc breaks the first connection when attempting to write, but second succeeds)
        data = null;
    } finally {
        if (data != null)
            data.close();
        client.close();
    }
}

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

/**
 * Construct a proper HTTP response to a received request. After the response has been
 * created, it is sent and the resulting {@link ChannelFuture} object is returned.
 * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC-2616</a>
 * for HTTP header field definitions.// w ww. j  a  va2  s.  co  m
 * @param output The {@link HttpResponse} object that will be used to construct the response.
 * @param e The {@link MessageEvent} object used to communicate with the client that sent
 *          the request.
 * @param close Set to true to close the channel after sending the response. By default the
 *          channel is not closed after sending.
 * @param startStopListenerDelegate The {@link StartStopListenerDelegate} object that is used
 *          to notify plugins that the {@link DLNAResource} is about to start playing.
 * @return The {@link ChannelFuture} object via which the response was sent.
 * @throws IOException
 */
public ChannelFuture answer(HttpResponse output, MessageEvent e, final boolean close,
        final StartStopListenerDelegate startStopListenerDelegate) throws IOException {
    ChannelFuture future = null;
    long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
    StringBuilder response = new StringBuilder();
    DLNAResource dlna = null;
    boolean xbox = mediaRenderer.isXBOX();

    // Samsung 2012 TVs have a problematic preceding slash that needs to be removed.
    if (argument.startsWith("/")) {
        logger.trace("Stripping preceding slash from: " + argument);
        argument = argument.substring(1);
    }

    if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("console/")) {
        // Request to output a page to the HTML console.
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html");
        response.append(HTMLConsole.servePage(argument.substring(8)));
    } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
        // Request to retrieve a file

        /*
         * skip the leading "get/" and extract the
         * resource ID from the first path element
         * e.g. "get/0$1$5$3$4/Foo.mp4" -> "0$1$5$3$4"
         *
         * ExSport: I spotted on Android it is asking for "/get/0$2$4$2$1$3"
         */
        String id = StringUtils.substringBetween(argument, "get/", "/");

        // Some clients escape the separators in their request: unescape them.
        id = id.replace("%24", "$");

        // Retrieve the DLNA resource itself.
        List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0,
                mediaRenderer);

        if (transferMode != null) {
            output.setHeader("TransferMode.DLNA.ORG", transferMode);
        }

        if (files.size() == 1) {
            // DLNAresource was found.
            dlna = files.get(0);
            String fileName = argument.substring(argument.lastIndexOf("/") + 1);

            if (fileName.startsWith("thumbnail0000")) {
                // This is a request for a thumbnail file.
                output.setHeader(HttpHeaders.Names.CONTENT_TYPE, dlna.getThumbnailContentType());
                output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
                output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
                output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");

                if (mediaRenderer.isMediaParserV2()) {
                    dlna.checkThumbnail();
                }

                inputStream = dlna.getThumbnailInputStream();
            } else if (fileName.indexOf("subtitle0000") > -1) {
                // This is a request for a subtitle file
                output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
                output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
                List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();

                if (subs != null && !subs.isEmpty()) {
                    // TODO: maybe loop subs to get the requested subtitle type instead of using the first one
                    DLNAMediaSubtitle sub = subs.get(0);
                    if (sub.isExternal()) {
                        inputStream = new java.io.FileInputStream(sub.getExternalFile());
                    }
                }
            } else {
                // This is a request for a regular file.

                // If range has not been initialized yet and the DLNAResource has its
                // own start and end defined, initialize range with those values before
                // requesting the input stream.
                Range.Time splitRange = dlna.getSplitRange();

                if (range.getStart() == null && splitRange.getStart() != null) {
                    range.setStart(splitRange.getStart());
                }

                if (range.getEnd() == null && splitRange.getEnd() != null) {
                    range.setEnd(splitRange.getEnd());
                }

                inputStream = dlna.getInputStream(
                        Range.create(lowRange, highRange, range.getStart(), range.getEnd()), mediaRenderer);

                if (!configuration.isDisableSubtitles()) {
                    // Some renderers (like Samsung devices) allow a custom header for a subtitle URL
                    String subtitleHttpHeader = mediaRenderer.getSubtitleHttpHeader();

                    if (subtitleHttpHeader != null && !"".equals(subtitleHttpHeader)) {
                        // Device allows a custom subtitle HTTP header; construct it
                        List<DLNAMediaSubtitle> subs = dlna.getMedia().getSubtitleTracksList();

                        if (subs != null && !subs.isEmpty()) {
                            DLNAMediaSubtitle sub = subs.get(0);
                            String subtitleUrl;
                            String subExtension = sub.getType().getExtension();
                            if (isNotBlank(subExtension)) {
                                subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':'
                                        + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000."
                                        + subExtension;
                            } else {
                                subtitleUrl = "http://" + PMS.get().getServer().getHost() + ':'
                                        + PMS.get().getServer().getPort() + "/get/" + id + "/subtitle0000";
                            }
                            output.setHeader(subtitleHttpHeader, subtitleUrl);
                        }
                    }
                }

                String name = dlna.getDisplayName(mediaRenderer);

                if (inputStream == null) {
                    // No inputStream indicates that transcoding / remuxing probably crashed.
                    logger.error("There is no inputstream to return for " + name);
                } else {
                    // Notify plugins that the DLNAresource is about to start playing
                    startStopListenerDelegate.start(dlna);

                    // Try to determine the content type of the file
                    String rendererMimeType = getRendererMimeType(dlna.mimeType(), mediaRenderer);

                    if (rendererMimeType != null && !"".equals(rendererMimeType)) {
                        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, rendererMimeType);
                    }

                    final DLNAMediaInfo media = dlna.getMedia();
                    if (media != null) {
                        if (isNotBlank(media.getContainer())) {
                            name += " [container: " + media.getContainer() + "]";
                        }

                        if (isNotBlank(media.getCodecV())) {
                            name += " [video: " + media.getCodecV() + "]";
                        }
                    }

                    PMS.get().getFrame().setStatusLine("Serving " + name);

                    // Response generation:
                    // We use -1 for arithmetic convenience but don't send it as a value.
                    // If Content-Length < 0 we omit it, for Content-Range we use '*' to signify unspecified.

                    boolean chunked = mediaRenderer.isChunkedTransfer();

                    // Determine the total size. Note: when transcoding the length is
                    // not known in advance, so DLNAMediaInfo.TRANS_SIZE will be returned instead.

                    long totalsize = dlna.length(mediaRenderer);

                    if (chunked && totalsize == DLNAMediaInfo.TRANS_SIZE) {
                        // In chunked mode we try to avoid arbitrary values.
                        totalsize = -1;
                    }

                    long remaining = totalsize - lowRange;
                    long requested = highRange - lowRange;

                    if (requested != 0) {
                        // Determine the range (i.e. smaller of known or requested bytes)
                        long bytes = remaining > -1 ? remaining : inputStream.available();

                        if (requested > 0 && bytes > requested) {
                            bytes = requested + 1;
                        }

                        // Calculate the corresponding highRange (this is usually redundant).
                        highRange = lowRange + bytes - (bytes > 0 ? 1 : 0);

                        logger.trace(
                                (chunked ? "Using chunked response. " : "") + "Sending " + bytes + " bytes.");

                        output.setHeader(HttpHeaders.Names.CONTENT_RANGE,
                                "bytes " + lowRange + "-" + (highRange > -1 ? highRange : "*") + "/"
                                        + (totalsize > -1 ? totalsize : "*"));

                        // Content-Length refers to the current chunk size here, though in chunked
                        // mode if the request is open-ended and totalsize is unknown we omit it.
                        if (chunked && requested < 0 && totalsize < 0) {
                            CLoverride = -1;
                        } else {
                            CLoverride = bytes;
                        }
                    } else {
                        // Content-Length refers to the total remaining size of the stream here.
                        CLoverride = remaining;
                    }

                    // Calculate the corresponding highRange (this is usually redundant).
                    highRange = lowRange + CLoverride - (CLoverride > 0 ? 1 : 0);

                    if (contentFeatures != null) {
                        output.setHeader("ContentFeatures.DLNA.ORG", dlna.getDlnaContentFeatures());
                    }

                    output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
                    output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
                }
            }
        }
    } else if ((method.equals("GET") || method.equals("HEAD")) && (argument.toLowerCase().endsWith(".png")
            || argument.toLowerCase().endsWith(".jpg") || argument.toLowerCase().endsWith(".jpeg"))) {
        if (argument.toLowerCase().endsWith(".png")) {
            output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
        } else {
            output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/jpeg");
        }

        output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
        output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
        output.setHeader(HttpHeaders.Names.EXPIRES, getFUTUREDATE() + " GMT");
        inputStream = getResourceInputStream(argument);
    } else if ((method.equals("GET") || method.equals("HEAD"))
            && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
        output.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-cache");
        output.setHeader(HttpHeaders.Names.EXPIRES, "0");
        output.setHeader(HttpHeaders.Names.ACCEPT_RANGES, "bytes");
        output.setHeader(HttpHeaders.Names.CONNECTION, "keep-alive");
        inputStream = getResourceInputStream((argument.equals("description/fetch") ? "PMS.xml" : argument));

        if (argument.equals("description/fetch")) {
            byte b[] = new byte[inputStream.available()];
            inputStream.read(b);
            String s = new String(b);
            s = s.replace("[uuid]", PMS.get().usn()); //.substring(0, PMS.get().usn().length()-2));
            String profileName = configuration.getProfileName();

            if (PMS.get().getServer().getHost() != null) {
                s = s.replace("[host]", PMS.get().getServer().getHost());
                s = s.replace("[port]", "" + PMS.get().getServer().getPort());
            }

            if (xbox) {
                logger.debug("DLNA changes for Xbox 360");
                s = s.replace("PS3 Media Server",
                        "PS3 Media Server [" + profileName + "] : Windows Media Connect");
                s = s.replace("<modelName>PMS</modelName>", "<modelName>Windows Media Connect</modelName>");
                s = s.replace("<serviceList>", "<serviceList>" + CRLF + "<service>" + CRLF
                        + "<serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>"
                        + CRLF
                        + "<serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>"
                        + CRLF + "<SCPDURL>/upnp/mrr/scpd</SCPDURL>" + CRLF
                        + "<controlURL>/upnp/mrr/control</controlURL>" + CRLF + "</service>" + CRLF);
            } else {
                s = s.replace("PS3 Media Server", "PS3 Media Server [" + profileName + "]");
            }

            if (!mediaRenderer.isPS3()) {
                // hacky stuff. replace the png icon by a jpeg one. Like mpeg2 remux,
                // really need a proper format compatibility list by renderer
                s = s.replace("<mimetype>image/png</mimetype>", "<mimetype>image/jpeg</mimetype>");
                s = s.replace("/images/thumbnail-video-256.png", "/images/thumbnail-video-120.jpg");
                s = s.replace(">256<", ">120<");
            }

            response.append(s);
            inputStream = null;
        }
    } else if (method.equals("POST")
            && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");
        response.append(HTTPXMLHelper.XML_HEADER);
        response.append(CRLF);
        response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
        response.append(CRLF);

        if (soapaction != null && soapaction.contains("IsAuthorized")) {
            response.append(HTTPXMLHelper.XBOX_2);
            response.append(CRLF);
        } else if (soapaction != null && soapaction.contains("IsValidated")) {
            response.append(HTTPXMLHelper.XBOX_1);
            response.append(CRLF);
        }

        response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
        response.append(CRLF);
        response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
        response.append(CRLF);
    } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");

        if (soapaction != null && soapaction.indexOf("ConnectionManager:1#GetProtocolInfo") > -1) {
            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.PROTOCOLINFO_RESPONSE);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
        }
    } else if (method.equals("POST") && argument.endsWith("upnp/control/content_directory")) {
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml; charset=\"utf-8\"");

        if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSystemUpdateID") > -1) {
            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_HEADER);
            response.append(CRLF);
            response.append("<Id>").append(DLNAResource.getSystemUpdateId()).append("</Id>");
            response.append(CRLF);
            response.append(HTTPXMLHelper.GETSYSTEMUPDATEID_FOOTER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
        } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#X_GetFeatureList") > -1) { // Added for Samsung 2012 TVs
            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.UPNP_INVALID_ACTION);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
        } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSortCapabilities") > -1) {
            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SORTCAPS_RESPONSE);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
        } else if (soapaction != null && soapaction.indexOf("ContentDirectory:1#GetSearchCapabilities") > -1) {
            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SEARCHCAPS_RESPONSE);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
        } else if (soapaction != null && (soapaction.contains("ContentDirectory:1#Browse")
                || soapaction.contains("ContentDirectory:1#Search"))) {
            objectID = getEnclosingValue(content, "<ObjectID>", "</ObjectID>");
            String containerID = null;
            if (isEmpty(objectID) && xbox) {
                containerID = getEnclosingValue(content, "<ContainerID>", "</ContainerID>");
                if (containerID == null || !containerID.contains("$")) {
                    objectID = "0";
                } else {
                    objectID = containerID;
                    containerID = null;
                }
            }
            Object sI = getEnclosingValue(content, "<StartingIndex>", "</StartingIndex>");
            Object rC = getEnclosingValue(content, "<RequestedCount>", "</RequestedCount>");
            browseFlag = getEnclosingValue(content, "<BrowseFlag>", "</BrowseFlag>");

            if (sI != null) {
                startingIndex = Integer.parseInt(sI.toString());
            }

            if (rC != null) {
                requestCount = Integer.parseInt(rC.toString());
            }

            response.append(HTTPXMLHelper.XML_HEADER);
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_HEADER);
            response.append(CRLF);

            if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
                response.append(HTTPXMLHelper.SEARCHRESPONSE_HEADER);
            } else {
                response.append(HTTPXMLHelper.BROWSERESPONSE_HEADER);
            }

            response.append(CRLF);
            response.append(HTTPXMLHelper.RESULT_HEADER);
            response.append(HTTPXMLHelper.DIDL_HEADER);

            if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
                browseFlag = "BrowseDirectChildren";
            }

            // XBOX virtual containers ... d'oh!
            String searchCriteria = null;
            if (xbox && configuration.getUseCache() && PMS.get().getLibrary() != null && containerID != null) {
                if (containerID.equals("7") && PMS.get().getLibrary().getAlbumFolder() != null) {
                    objectID = PMS.get().getLibrary().getAlbumFolder().getResourceId();
                } else if (containerID.equals("6") && PMS.get().getLibrary().getArtistFolder() != null) {
                    objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
                } else if (containerID.equals("5") && PMS.get().getLibrary().getGenreFolder() != null) {
                    objectID = PMS.get().getLibrary().getGenreFolder().getResourceId();
                } else if (containerID.equals("F") && PMS.get().getLibrary().getPlaylistFolder() != null) {
                    objectID = PMS.get().getLibrary().getPlaylistFolder().getResourceId();
                } else if (containerID.equals("4") && PMS.get().getLibrary().getAllFolder() != null) {
                    objectID = PMS.get().getLibrary().getAllFolder().getResourceId();
                } else if (containerID.equals("1")) {
                    String artist = getEnclosingValue(content, "upnp:artist = &quot;", "&quot;)");
                    if (artist != null) {
                        objectID = PMS.get().getLibrary().getArtistFolder().getResourceId();
                        searchCriteria = artist;
                    }
                }
            }

            List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(objectID,
                    browseFlag != null && browseFlag.equals("BrowseDirectChildren"), startingIndex,
                    requestCount, mediaRenderer);

            if (searchCriteria != null && files != null) {
                for (int i = files.size() - 1; i >= 0; i--) {
                    if (!files.get(i).getName().equals(searchCriteria)) {
                        files.remove(i);
                    }
                }

                if (files.size() > 0) {
                    files = files.get(0).getChildren();
                }
            }

            int minus = 0;
            if (files != null) {
                for (DLNAResource uf : files) {
                    if (xbox && containerID != null) {
                        uf.setFakeParentId(containerID);
                    }
                    if (uf.isCompatible(mediaRenderer)
                            && (uf.getPlayer() == null || uf.getPlayer().isPlayerCompatible(mediaRenderer))) {
                        response.append(uf.toString(mediaRenderer));
                    } else {
                        minus++;
                    }
                }
            }

            response.append(HTTPXMLHelper.DIDL_FOOTER);
            response.append(HTTPXMLHelper.RESULT_FOOTER);
            response.append(CRLF);
            int filessize = 0;
            if (files != null) {
                filessize = files.size();
            }
            response.append("<NumberReturned>").append(filessize - minus).append("</NumberReturned>");
            response.append(CRLF);
            DLNAResource parentFolder = null;
            if (files != null && filessize > 0) {
                parentFolder = files.get(0).getParent();
            }
            if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")
                    && mediaRenderer.isMediaParserV2() && mediaRenderer.isDLNATreeHack()) {
                // with the new parser, files are parsed and analyzed *before* creating the DLNA tree,
                // every 10 items (the ps3 asks 10 by 10),
                // so we do not know exactly the total number of items in the DLNA folder to send
                // (regular files, plus the #transcode folder, maybe the #imdb one, also files can be
                // invalidated and hidden if format is broken or encrypted, etc.).
                // let's send a fake total size to force the renderer to ask following items
                int totalCount = startingIndex + requestCount + 1; // returns 11 when 10 asked
                if (filessize - minus <= 0) { // if no more elements, send the startingIndex
                    totalCount = startingIndex;
                }
                response.append("<TotalMatches>").append(totalCount).append("</TotalMatches>");
            } else if (browseFlag != null && browseFlag.equals("BrowseDirectChildren")) {
                response.append("<TotalMatches>")
                        .append(((parentFolder != null) ? parentFolder.childrenNumber() : filessize) - minus)
                        .append("</TotalMatches>");
            } else { //from upnp spec: If BrowseMetadata is specified in the BrowseFlags then TotalMatches = 1
                response.append("<TotalMatches>1</TotalMatches>");
            }
            response.append(CRLF);
            response.append("<UpdateID>");
            if (parentFolder != null) {
                response.append(parentFolder.getUpdateId());
            } else {
                response.append("1");
            }
            response.append("</UpdateID>");
            response.append(CRLF);
            if (soapaction != null && soapaction.contains("ContentDirectory:1#Search")) {
                response.append(HTTPXMLHelper.SEARCHRESPONSE_FOOTER);
            } else {
                response.append(HTTPXMLHelper.BROWSERESPONSE_FOOTER);
            }
            response.append(CRLF);
            response.append(HTTPXMLHelper.SOAP_ENCODING_FOOTER);
            response.append(CRLF);
            // logger.trace(response.toString());
        }
    } else if (method.equals("SUBSCRIBE")) {
        output.setHeader("SID", PMS.get().usn());
        output.setHeader("TIMEOUT", "Second-1800");

        if (soapaction != null) {
            String cb = soapaction.replace("<", "").replace(">", "");

            try {
                URL soapActionUrl = new URL(cb);
                String addr = soapActionUrl.getHost();
                int port = soapActionUrl.getPort();
                Socket sock = new Socket(addr, port);
                OutputStream out = sock.getOutputStream();

                out.write(("NOTIFY /" + argument + " HTTP/1.1").getBytes());
                out.write(CRLF.getBytes());
                out.write(("SID: " + PMS.get().usn()).getBytes());
                out.write(CRLF.getBytes());
                out.write(("SEQ: " + 0).getBytes());
                out.write(CRLF.getBytes());
                out.write(("NT: upnp:event").getBytes());
                out.write(CRLF.getBytes());
                out.write(("NTS: upnp:propchange").getBytes());
                out.write(CRLF.getBytes());
                out.write(("HOST: " + addr + ":" + port).getBytes());
                out.write(CRLF.getBytes());
                out.flush();
                out.close();
                sock.close();
            } catch (MalformedURLException ex) {
                logger.debug("Cannot parse address and port from soap action \"" + soapaction + "\"", ex);
            }
        } else {
            logger.debug("Expected soap action in request");
        }

        if (argument.contains("connection_manager")) {
            response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ConnectionManager:1"));
            response.append(HTTPXMLHelper.eventProp("SinkProtocolInfo"));
            response.append(HTTPXMLHelper.eventProp("SourceProtocolInfo"));
            response.append(HTTPXMLHelper.eventProp("CurrentConnectionIDs"));
            response.append(HTTPXMLHelper.EVENT_FOOTER);
        } else if (argument.contains("content_directory")) {
            response.append(HTTPXMLHelper.eventHeader("urn:schemas-upnp-org:service:ContentDirectory:1"));
            response.append(HTTPXMLHelper.eventProp("TransferIDs"));
            response.append(HTTPXMLHelper.eventProp("ContainerUpdateIDs"));
            response.append(HTTPXMLHelper.eventProp("SystemUpdateID", "" + DLNAResource.getSystemUpdateId()));
            response.append(HTTPXMLHelper.EVENT_FOOTER);
        }
    } else if (method.equals("NOTIFY")) {
        output.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
        output.setHeader("NT", "upnp:event");
        output.setHeader("NTS", "upnp:propchange");
        output.setHeader("SID", PMS.get().usn());
        output.setHeader("SEQ", "0");
        response.append("<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">");
        response.append("<e:property>");
        response.append("<TransferIDs></TransferIDs>");
        response.append("</e:property>");
        response.append("<e:property>");
        response.append("<ContainerUpdateIDs></ContainerUpdateIDs>");
        response.append("</e:property>");
        response.append("<e:property>");
        response.append("<SystemUpdateID>").append(DLNAResource.getSystemUpdateId())
                .append("</SystemUpdateID>");
        response.append("</e:property>");
        response.append("</e:propertyset>");
    }

    output.setHeader("Server", PMS.get().getServerName());

    if (response.length() > 0) {
        // A response message was constructed; convert it to data ready to be sent.
        byte responseData[] = response.toString().getBytes("UTF-8");
        output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + responseData.length);

        // HEAD requests only require headers to be set, no need to set contents.
        if (!method.equals("HEAD")) {
            // Not a HEAD request, so set the contents of the response.
            ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseData);
            output.setContent(buf);
        }

        // Send the response to the client.
        future = e.getChannel().write(output);

        if (close) {
            // Close the channel after the response is sent.
            future.addListener(ChannelFutureListener.CLOSE);
        }
    } else if (inputStream != null) {
        // There is an input stream to send as a response.

        if (CLoverride > -2) {
            // Content-Length override has been set, send or omit as appropriate
            if (CLoverride > -1 && CLoverride != DLNAMediaInfo.TRANS_SIZE) {
                // Since PS3 firmware 2.50, it is wiser not to send an arbitrary Content-Length,
                // as the PS3 will display a network error and request the last seconds of the
                // transcoded video. Better to send no Content-Length at all.
                output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + CLoverride);
            }
        } else {
            int cl = inputStream.available();
            logger.trace("Available Content-Length: " + cl);
            output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + cl);
        }

        if (range.isStartOffsetAvailable() && dlna != null) {
            // Add timeseek information headers.
            String timeseekValue = DLNAMediaInfo.getDurationString(range.getStartOrZero());
            String timetotalValue = dlna.getMedia().getDurationString();
            String timeEndValue = range.isEndLimitAvailable() ? DLNAMediaInfo.getDurationString(range.getEnd())
                    : timetotalValue;
            output.setHeader("TimeSeekRange.dlna.org",
                    "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
            output.setHeader("X-Seek-Range",
                    "npt=" + timeseekValue + "-" + timeEndValue + "/" + timetotalValue);
        }

        // Send the response headers to the client.
        future = e.getChannel().write(output);

        if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
            // Send the response body to the client in chunks.
            ChannelFuture chunkWriteFuture = e.getChannel().write(new ChunkedStream(inputStream, BUFFER_SIZE));

            // Add a listener to clean up after sending the entire response body.
            chunkWriteFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    try {
                        PMS.get().getRegistry().reenableGoToSleep();
                        inputStream.close();
                    } catch (IOException e) {
                        logger.debug("Caught exception", e);
                    }

                    // Always close the channel after the response is sent because of
                    // a freeze at the end of video when the channel is not closed.
                    future.getChannel().close();
                    startStopListenerDelegate.stop();
                }
            });
        } else {
            // HEAD method is being used, so simply clean up after the response was sent.
            try {
                PMS.get().getRegistry().reenableGoToSleep();
                inputStream.close();
            } catch (IOException ioe) {
                logger.debug("Caught exception", ioe);
            }

            if (close) {
                // Close the channel after the response is sent
                future.addListener(ChannelFutureListener.CLOSE);
            }

            startStopListenerDelegate.stop();
        }
    } else {
        // No response data and no input stream. Seems we are merely serving up headers.
        if (lowRange > 0 && highRange > 0) {
            // FIXME: There is no content, so why set a length?
            output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "" + (highRange - lowRange + 1));
        } else {
            output.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0");
        }

        // Send the response headers to the client.
        future = e.getChannel().write(output);

        if (close) {
            // Close the channel after the response is sent.
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    // Log trace information
    Iterator<String> it = output.getHeaderNames().iterator();

    while (it.hasNext()) {
        String headerName = it.next();
        logger.trace("Sent to socket: " + headerName + ": " + output.getHeader(headerName));
    }

    return future;
}

From source file:com.clustercontrol.port.protocol.ReachAddressTCP.java

/**
 * ????????????//from   w  ww  . ja  v  a 2 s.  c  o m
 * 
 * @param addressText
 * @return PORT
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        // Reachability ?? ICMP ??
        boolean retry = true;

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the port of " + address.getHostName() + "[" + address.getHostAddress()
                + "]:" + m_portNo + ".\n\n");

        // 
        Socket socket = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                // ?
                socket = new Socket();
                InetSocketAddress isa = new InetSocketAddress(address, m_portNo);

                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                start = HinemosTime.currentTimeMillis();
                socket.connect(isa, m_timeout);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;
                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = ("Response Time < 1ms");
                }
                retry = false;
                isReachable = true;
            } catch (BindException e) {
                result = (e.getMessage() + "[BindException]");
                retry = true;
                isReachable = false;
            } catch (ConnectException e) {
                result = (e.getMessage() + "[ConnectException]");
                retry = false;
                isReachable = false;
            } catch (NoRouteToHostException e) {
                result = (e.getMessage() + "[NoRouteToHostException]");
                retry = true;
                isReachable = false;
            } catch (PortUnreachableException e) {
                result = (e.getMessage() + "[PortUnreachableException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket close failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(TCP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {//from  www .  ja  v  a2s .  c o  m
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * @param message/*from   w w w . j  a v a 2s .c  om*/
 *            the message as a string, that should send.
 * @return the result of the call
 * @throws UnknownHostException
 * @throws IOException
 */
private boolean sendMessage(String message) {

    StringBuilder result = new StringBuilder();

    try {
        Socket client = getSocket();

        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println(message);
        LOGGER.info("Send message to AUT:" + message);
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));

        int c;
        while ((c = in.read()) != -1) {
            result.append((char) c);
        }
        String myMessage = result.toString();
        if (myMessage.indexOf("ERROR ") > -1) {
            LOGGER.error("Fails: " + myMessage);
            throw new RuntimeException("Message: " + message + " fails with: " + myMessage);
        }

        client.close();

    } catch (UnknownHostException e) {
        LOGGER.error("SendMessage Host not Found", e);
    } catch (IOException e) {
        LOGGER.error("Send Message IOException ", e);
    }
    if (result.toString().startsWith("true")) {
        return true;
    }
    return false;
}

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///  ww  w. j  a  va 2 s . c  o m
@Deprecated
private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
    LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint);

    if (authorization != null) {
        LOGGER.warning("-auth ignored when using JNLP agent port");
    }

    final Socket s = new Socket();
    // this prevents a connection from silently terminated by the router in between or the other peer
    // and that goes without unnoticed. However, the time out is often very long (for example 2 hours
    // by default in Linux) that this alone is enough to prevent that.
    s.setKeepAlive(true);
    // we take care of buffering on our own
    s.setTcpNoDelay(true);
    OutputStream out;

    if (httpsProxyTunnel != null) {
        String[] tokens = httpsProxyTunnel.split(":");
        LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port",
                new Object[] { tokens[0], tokens[1] });
        s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1])));
        PrintStream o = new PrintStream(s.getOutputStream());
        o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort()
                + " HTTP/1.0\r\n\r\n");

        // read the response from the proxy
        ByteArrayOutputStream rsp = new ByteArrayOutputStream();
        while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) {
            int ch = s.getInputStream().read();
            if (ch < 0)
                throw new IOException("Failed to read the HTTP proxy response: " + rsp);
            rsp.write(ch);
        }
        String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine();

        if (head == null) {
            throw new IOException("Unexpected empty response");
        }
        if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) {
            s.close();
            LOGGER.log(Level.SEVERE,
                    "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP.");
            throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp);
        }

        // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well.
        // So instead of relying on it, we'll just send the close command and then let the server
        // cut their side, then close the socket after the join.
        out = new SocketOutputStream(s) {
            @Override
            public void close() throws IOException {
                // ignore
            }
        };
    } else {
        s.connect(clip.endpoint, 3000);
        out = SocketChannelStream.out(s);
    }

    closables.add(new Closeable() {
        public void close() throws IOException {
            s.close();
        }
    });

    Connection c = new Connection(SocketChannelStream.in(s), out);

    switch (clip.version) {
    case 1:
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI-connect");
        // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor.
        break;
    case 2:
        DataInputStream dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI2-connect");
        String greeting = dis.readUTF();
        if (!greeting.equals("Welcome"))
            throw new IOException("Handshaking failed: " + greeting);
        try {
            byte[] secret = c.diffieHellman(false).generateSecret();
            SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES");
            c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding");

            // validate the instance identity, so that we can be sure that we are talking to the same server
            // and there's no one in the middle.
            byte[] signature = c.readByteArray();

            if (clip.identity != null) {
                Signature verifier = Signature.getInstance("SHA1withRSA");
                verifier.initVerify(clip.getIdentity());
                verifier.update(secret);
                if (!verifier.verify(signature))
                    throw new IOException("Server identity signature validation failed.");
            }

        } catch (GeneralSecurityException e) {
            throw (IOException) new IOException("Failed to negotiate transport security").initCause(e);
        }
    }

    return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in),
            new BufferedOutputStream(c.out));
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public void init(String[] args) throws SshToolsApplicationException {
    instance = this;

    boolean listen = isReuseCapable();

    // Do parse 1 of the command line arguments - see if we need to start
    // the daemon
    Options options1 = new Options();
    SshToolsApplication.this.buildCLIOptions(options1);

    pluginManager = new PluginManager();
    try {// w  w  w.ja v  a2 s .  co m
        initPluginManager(options1);
    } catch (PluginException e1) {
        log(PluginHostContext.LOG_ERROR, "Failed to initialise plugin manager.", e1);
    }

    CommandLineParser parser1 = new PosixParser();
    CommandLine commandLine1;

    try {
        // parse the command line arguments
        commandLine1 = parser1.parse(options1, args);
        if (commandLine1.hasOption("d")) {
            listen = false;
        }

        if (commandLine1.hasOption('r')) {
            reusePort = Integer.parseInt(commandLine1.getOptionValue('r'));
        }
    } catch (Exception e) {
        // Don't care at the moment
    }

    // Try and message the reuse daemon if possible - saves starting another
    // instance
    if (listen) {
        Socket s = null;
        try {
            String hostname = "localhost";
            if (reusePort == -1) {
                reusePort = getDefaultReusePort();
            }
            log.debug("Attempting connection to reuse server on " + hostname + ":" + reusePort);
            s = new Socket(hostname, reusePort);
            log.debug("Found reuse server on " + hostname + ":" + reusePort + ", sending arguments");
            s.setSoTimeout(5000);
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            for (int i = 0; args != null && i < args.length; i++) {
                pw.println(args[i]);
            }
            pw.println();
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            log.debug("Waiting for reuse server reply");
            String error = r.readLine();
            log.debug("Reuse server replied with '" + error + "'");
            if (error != null && !error.equals("")) {
                throw new SshToolsApplicationException(error);
            }
            System.exit(0);
        } catch (SshToolsApplicationException t) {
            throw t;
        } catch (SocketException se) {
            log.debug("No reuse server found.");
        } catch (SocketTimeoutException se) {
            log.debug("Reuse server not responding.", se);
        } catch (Exception e) {
            throw new SshToolsApplicationException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException ioe) {
                }
            }
        }
    }

    additionalOptionsTabs = new ArrayList<OptionsTab>();
    log.info("Initialising application");
    File f = getApplicationPreferencesDirectory();
    if (f != null) {
        //
        FilePreferencesFactory.setPreferencesFile(new File(f, "javaprefs.properties"));
        PreferencesStore.init(new File(f, getApplicationName() + ".properties"));
    }
    setLookAndFeel(getDefaultLAF());

    log.debug("Plugin manager initialised, adding global preferences tabs");

    postInitialization();
    addAdditionalOptionsTab(new GlobalOptionsTab(this));

    Options options = new Options();
    buildCLIOptions(options);
    log.debug("Parsing command line");
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        cli = parser.parse(options, args);
        if (cli.hasOption("?")) {
            printHelp(options);
            System.exit(0);
        }
    } catch (Exception e) {
        System.err.println("Invalid option: " + e.getMessage());
        printHelp(options);
        System.exit(1);
    }
    log.debug("Parsed command line");

    if (listen) {
        Thread t = new Thread("RemoteCommandLine") {
            @Override
            public void run() {
                Socket s = null;
                try {
                    reuseServerSocket = new ServerSocket(reusePort, 1);
                    while (true) {
                        s = reuseServerSocket.accept();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        String line = null;
                        List<String> args = new ArrayList<String>();
                        while ((line = reader.readLine()) != null && !line.equals("")) {
                            args.add(line);
                        }
                        final PrintWriter pw = new PrintWriter(s.getOutputStream());
                        String[] a = new String[args.size()];
                        args.toArray(a);
                        CommandLineParser parser = new PosixParser();
                        Options options = new Options();
                        buildCLIOptions(options);
                        // parse the command line arguments
                        final CommandLine remoteCLI = parser.parse(options, a);
                        pw.println("");
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                try {
                                    reuseRequest(remoteCLI);
                                } catch (Throwable t) {
                                    pw.println(t.getMessage());
                                }
                            }
                        });
                        s.close();
                        s = null;
                    }
                } catch (Exception e) {
                    /* DEBUG */e.printStackTrace();
                } finally {
                    if (s != null) {
                        try {
                            s.close();
                        } catch (IOException ioe) {

                        }
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}

From source file:net.emotivecloud.scheduler.drp4one.DRP4OVF.java

private boolean port22Reached(String ipAddress) {
    boolean gotPort22Connection = false;

    try {/* w w w . j a  v  a  2  s .  c o m*/

        InetAddress toPoll = InetAddress.getByName(ipAddress);
        boolean reachable = false;
        try {
            // We have to answer within a WS timeout
            reachable = toPoll.isReachable(5000);
        } catch (IOException e) {
            // same as unreachable, log the problem
            if (log.isDebugEnabled()) {
                log.error(e);
            } else {
                log.error(e.getMessage());
            }
        }

        if (reachable) {
            // see if we can ssh connect to port 22
            try {
                Socket socket = new Socket(toPoll, 22);
                gotPort22Connection |= socket.isConnected();
                socket.close();
            } catch (IOException e) {
                // Happens when there's no one listening
                // on port 22, for example. Anyway, it
                // means we can't connect
            }

        }

    } catch (UnknownHostException e) {
        // Ignore, it's not a valid ip!
    } catch (SecurityException e) {

        if (log.isDebugEnabled()) {
            log.fatal(e);
        } else {
            log.fatal(e.getMessage());
        }

        throw e;

    }
    return gotPort22Connection;

}

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

@Override
public Socket wrapAcceptedSocket(Socket socket) throws IOException {
    InputStream ins = socket.getInputStream();

    byte[] buffer = new byte[0xFF];
    int position = 0;
    SSLCapabilities capabilities = null;

    // Read the header of TLS record
    while (position < SSLExplorer.RECORD_HEADER_SIZE) {
        int count = SSLExplorer.RECORD_HEADER_SIZE - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }//from  www .  j ava 2 s  .c om
        position += n;
    }

    // Get the required size to explore the SSL capabilities
    int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position);
    if (buffer.length < recordLength) {
        buffer = Arrays.copyOf(buffer, recordLength);
    }

    while (position < recordLength) {
        int count = recordLength - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }
        position += n;
    }

    capabilities = SSLExplorer.explore(buffer, 0, recordLength);

    SSLContext sslContext = null;

    if (capabilities != null) {
        List<SNIServerName> serverNames = capabilities.getServerNames();
        if (serverNames != null && serverNames.size() > 0) {
            OUTER: for (SNIServerName snisn : serverNames) {
                String hostname = new String(snisn.getEncoded(), "UTF-8");
                for (int i = 0; i < dnsNames.size(); i++)
                    if (dnsNames.get(i).matcher(hostname).matches()) {
                        sslContext = sslContexts.get(i);
                        break OUTER;
                    }
            }
            if (sslContext == null) {
                // no hostname matched: send 'unrecognized_name' alert and close socket

                byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0,
                        2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ };

                try {
                    socket.getOutputStream().write(alert_unrecognized_name);
                } finally {
                    socket.close();
                }

                StringBuilder hostname = null;
                for (SNIServerName snisn : serverNames) {
                    if (hostname == null)
                        hostname = new StringBuilder();
                    else
                        hostname.append(", ");
                    hostname.append(new String(snisn.getEncoded(), "UTF-8"));
                }

                throw new RuntimeException(
                        "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname
                                + "\"");
            }
        }
    }

    // no Server Name Indication used by the client: fall back to first sslContext
    if (sslContext == null)
        sslContext = sslContexts.get(0);

    SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory();

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position);

    SSLSocket serviceSocket;
    // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8
    try {
        serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac,
                new Object[] { socket, bais, true });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    sslContext.applyCiphers(serviceSocket);
    if (sslContext.getProtocols() != null) {
        serviceSocket.setEnabledProtocols(sslContext.getProtocols());
    } else {
        String[] protocols = serviceSocket.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        serviceSocket.setEnabledProtocols(set.toArray(new String[0]));
    }
    serviceSocket.setWantClientAuth(sslContext.isWantClientAuth());
    serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth());

    return serviceSocket;
}

From source file:com.delphix.session.test.ServiceTest.java

/**
 * Scan for an unused port.//from w w w. j a v  a 2 s  .  c o m
 */
private int portScan() {
    int localPort = (int) (Math.random() * 1000) + 62626;

    do {
        Socket socket = new Socket();

        try {
            socket.setReuseAddress(true);
            socket.bind(new InetSocketAddress(localPort));
            assertTrue(socket.isBound());
            break;
        } catch (IOException e) {
            logger.infof(e, "failed to bind to port %d - try next", localPort);
            localPort++;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                fail("failed to close socket", e);
            }
        }
    } while (localPort < 65536);

    if (localPort >= 65536) {
        fail("failed to find unused port");
    }

    logger.infof("unused local port %d found", localPort);

    return localPort;
}