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:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }//from   ww  w . j ava 2  s .  c o  m
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

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

public void answer(OutputStream output, StartStopListenerDelegate startStopListenerDelegate)
        throws IOException {
    this.output = output;

    long CLoverride = -2; // 0 and above are valid Content-Length values, -1 means omit
    if (lowRange != 0 || highRange != 0) {
        output(output, http10 ? HTTP_206_OK_10 : HTTP_206_OK);
    } else {//from  w  w w .  ja  va  2 s. co  m
        if (soapaction != null && soapaction.contains("X_GetFeatureList")) {
            //  If we don't return a 500 error, Samsung 2012 TVs time out.
            output(output, HTTP_500);
        } else {
            output(output, http10 ? HTTP_200_OK_10 : HTTP_200_OK);
        }
    }

    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/")) {
        output(output, "Content-Type: text/html");
        response.append(HTMLConsole.servePage(argument.substring(8)));
    } else if ((method.equals("GET") || method.equals("HEAD")) && argument.startsWith("get/")) {
        String id = argument.substring(argument.indexOf("get/") + 4, argument.lastIndexOf("/"));
        id = id.replace("%24", "$"); // popcorn hour ?
        List<DLNAResource> files = PMS.get().getRootFolder(mediaRenderer).getDLNAResources(id, false, 0, 0,
                mediaRenderer);
        if (transferMode != null) {
            output(output, "TransferMode.DLNA.ORG: " + transferMode);
        }
        if (files.size() == 1) {
            // DNLAresource 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(output, "Content-Type: " + dlna.getThumbnailContentType());
                output(output, "Accept-Ranges: bytes");
                output(output, "Expires: " + getFUTUREDATE() + " GMT");
                output(output, "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(output, "Content-Type: text/plain");
                output(output, "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.
                String name = dlna.getDisplayName(mediaRenderer);
                inputStream = dlna.getInputStream(Range.create(lowRange, highRange, timeseek, timeRangeEnd),
                        mediaRenderer);
                if (inputStream == null) {
                    // No inputStream indicates that transcoding / remuxing probably crashed.
                    logger.error("There is no inputstream to return for " + name);
                } else {
                    startStopListenerDelegate.start(dlna);
                    output(output, "Content-Type: " + getRendererMimeType(dlna.mimeType(), 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(output, subtitleHttpHeader + ": " + subtitleUrl);
                            }
                        }
                    }

                    final DLNAMediaInfo media = dlna.getMedia();

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

                        if (StringUtils.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(output,
                                "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;
                    }

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

                    if (dlna.getPlayer() == null || xbox) {
                        output(output, "Accept-Ranges: bytes");
                    }

                    output(output, "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(output, "Content-Type: image/png");
        } else {
            output(output, "Content-Type: image/jpeg");
        }
        output(output, "Accept-Ranges: bytes");
        output(output, "Connection: keep-alive");
        output(output, "Expires: " + getFUTUREDATE() + " GMT");
        inputStream = getResourceInputStream(argument);
    } else if ((method.equals("GET") || method.equals("HEAD"))
            && (argument.equals("description/fetch") || argument.endsWith("1.0.xml"))) {
        String profileName = configuration.getProfileName();
        output(output, CONTENT_TYPE);
        output(output, "Cache-Control: no-cache");
        output(output, "Expires: 0");
        output(output, "Accept-Ranges: bytes");
        output(output, "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));
            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 + "]");
            }
            inputStream = new ByteArrayInputStream(s.getBytes());
        }
    } else if (method.equals("POST")
            && (argument.contains("MS_MediaReceiverRegistrar_control") || argument.contains("mrr/control"))) {
        output(output, CONTENT_TYPE_UTF8);
        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.SOAP_ENCODING_FOOTER);
        response.append(CRLF);
    } else if (method.equals("POST") && argument.endsWith("upnp/control/connection_manager")) {
        output(output, CONTENT_TYPE_UTF8);
        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("SUBSCRIBE")) {
        if (soapaction == null) {
            // Ignore this
            return;
        }
        output(output, CONTENT_TYPE_UTF8);
        output(output, "Content-Length: 0");
        output(output, "Connection: close");
        output(output, "SID: " + PMS.get().usn());
        output(output, "Server: " + PMS.get().getServerName());
        output(output, "Timeout: Second-1800");
        output(output, "");
        output.flush();
        // output.close();

        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();

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

        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("POST") && argument.endsWith("upnp/control/content_directory")) {
        output(output, CONTENT_TYPE_UTF8);

        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#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#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#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 ... doh
            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 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());
        }
    }

    output(output, "Server: " + PMS.get().getServerName());

    if (response.length() > 0) {
        byte responseData[] = response.toString().getBytes("UTF-8");
        output(output, "Content-Length: " + responseData.length);
        output(output, "");

        if (!method.equals("HEAD")) {
            output.write(responseData);
            //logger.trace(response.toString());
        }
    } else if (inputStream != null) {
        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(output, "Content-Length: " + CLoverride);
            }
        } else {
            int cl = inputStream.available();
            logger.trace("Available Content-Length: " + cl);
            output(output, "Content-Length: " + cl);
        }

        if (timeseek > 0 && dlna != null) {
            String timeseekValue = DLNAMediaInfo.getDurationString(timeseek);
            String timetotalValue = dlna.getMedia().getDurationString();
            output(output, "TimeSeekRange.dlna.org: npt=" + timeseekValue + "-" + timetotalValue + "/"
                    + timetotalValue);
            output(output, "X-Seek-Range: npt=" + timeseekValue + "-" + timetotalValue + "/" + timetotalValue);
        }

        output(output, "");
        int sendB = 0;

        if (lowRange != DLNAMediaInfo.ENDFILE_POS && !method.equals("HEAD")) {
            sendB = sendBytes(inputStream); //, ((lowRange > 0 && highRange > 0)?(highRange-lowRange):-1)
        }

        logger.trace("Sending stream: " + sendB + " bytes of " + argument);
        PMS.get().getFrame().setStatusLine(null);
    } else { // inputStream is null
        if (lowRange > 0 && highRange > 0) {
            output(output, "Content-Length: " + (highRange - lowRange + 1));
        } else {
            output(output, "Content-Length: 0");
        }

        output(output, "");
    }
}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));//ww w .java2 s  .  c o m
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            if (log.isDebugEnabled()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

From source file:com.impetus.ankush.common.framework.ClusterPreValidator.java

/**
 * Check iptables.//ww  w . j a v  a  2  s.  c  om
 * 
 * @param hostname
 *            the hostname
 * @return true, if successful
 */
public Status checkIptables(String hostname) {
    Status value = null;
    String message = "Firewall is not disabled";
    Socket socket = null;
    // Random port to validate
    Integer port = 4511;
    try {
        // Creating a socket condition
        socket = new Socket(hostname, port);
        // if socket connection created, then firewall is disabled
        value = new Status("Firewall", OK);
    } catch (Exception e) {
        // if exception type is NoRouteToHostException , then firewall is
        // enabled , else if exception type is ConnectException, then
        // firewall is disabled but no process is running on the port , else
        // unable to validate firewall
        if (e instanceof java.net.NoRouteToHostException) {
            value = new Status("Firewall", message, CRITICAL);
        } else if (e instanceof java.net.ConnectException) {
            value = new Status("Firewall", OK);
        } else {
            value = new Status("Firewall", "Failed to validate firewall", CRITICAL);
        }
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    return value;
}

From source file:gobblin.tunnel.TalkPastServer.java

@Override
void handleClientSocket(Socket clientSocket) throws IOException {
    LOG.info("Writing to client");
    try {// ww w . ja  v  a  2  s .c o m
        final BufferedOutputStream serverOut = new BufferedOutputStream(clientSocket.getOutputStream());
        EasyThread clientWriterThread = new EasyThread() {
            @Override
            void runQuietly() throws Exception {
                long t = System.currentTimeMillis();
                try {
                    for (int i = 0; i < nMsgs; i++) {
                        serverOut.write(generateMsgFromServer(i).getBytes());
                        sleepQuietly(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info("Server done writing in " + (System.currentTimeMillis() - t) + " ms");
            }
        }.startThread();
        _threads.add(clientWriterThread);

        BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String line = serverIn.readLine();
        while (line != null && !line.equals("Goodbye")) {
            String[] tokens = line.split(":", 2);
            String client = tokens[0];
            digestMsgsRecvdAtServer.get(client).update(line.getBytes());
            digestMsgsRecvdAtServer.get(client).update("\n".getBytes());
            line = serverIn.readLine();
        }
        LOG.info("Server done reading");
        try {
            clientWriterThread.join();
        } catch (InterruptedException e) {
        }
        serverOut.write("Goodbye\n".getBytes());
        serverOut.flush();
        clientSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.code.android.vibevault.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*ww w .ja v  a2  s . co m*/
    }

    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

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

    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes = -1;

        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 (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

From source file:com.adito.server.Main.java

private void setupMode() throws Exception {

    // Ensure that https redirect is not turned on in jetty
    System.setProperty("jetty.force.HTTPSRedirect", "false");

    getBootProgressMonitor().updateMessage("Creating server");
    getBootProgressMonitor().updateProgress(8);

    actualPort = defaultPort == -1 ? 28080 : defaultPort;
    serverLock.start(actualPort);//from w ww .  j  a  v  a  2 s  . c  om

    server = createServer();

    SocketListener socketListener = new SocketListener();
    socketListener.setPort(actualPort);
    socketListener.setMinThreads(10);
    socketListener.setMaxThreads(200);
    socketListener.setMaxIdleTimeMs(0);
    socketListener.setLowResourcePersistTimeMs(2000);
    socketListener.setAcceptQueueSize(0);
    socketListener.setPoolName("P1");
    server.addListener(socketListener);

    // // Add the context
    // HttpContext context = new CustomHttpContext(server, "/",
    // useDevConfig);
    // server.addContext(context);

    // Create the webapp

    getBootProgressMonitor().updateMessage("Creating web application");
    getBootProgressMonitor().updateProgress(9);

    webappContext = new CustomWebApplicationContext(useDevConfig, bootLoader);
    webappContext.setRedirectNullPath(false);
    addLifecycleListener(webappContext);
    server.addContext(webappContext);

    // Configure the server
    server.setRequestsPerGC(2000);

    String realHostname = hostname == null ? InetAddress.getLocalHost().getHostName() : hostname;

    /*
     * If the 'Active DNS' feature is enabled, the DNS server may return the
     * wild-card name. This will probably fail. As a work-around, if the
     * hostname looks like a wildcard, then it is simply changed to
     * 'localhost'.
     */
    if (realHostname.startsWith("*.")) {
        realHostname = "localhost";
    }

    //
    final String fRealHostname = realHostname;
    final int realPort = defaultPort == -1 ? 28080 : defaultPort;

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    mainThread = new Thread(threadGroup, "WebServer") {
        public void run() {
            // Start the server
            try {
                server.start();

                if (!useWrapper && !"true".equals(SystemProperties.get("adito.noBrowserLaunch"))) {
                    try {
                        BrowserLauncher.openURL("http://" + fRealHostname + ":" + realPort);
                        System.out.println("A browser has been opened and pointed to http://" + fRealHostname
                                + ":" + realPort + ". ");
                    } catch (Exception ex) {
                        System.out.println(
                                "Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                    }
                } else {
                    System.out.println("Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                }
                System.out.println(
                        "\nPress CTRL+C or use the 'Shutdown' option from the web interface to leave the installation wizard.");
                getBootProgressMonitor().updateMessage("Server is now running");
                getBootProgressMonitor().updateProgress(100);
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error("Failed to start Jetty. " + e.getMessage(), e);
                if (useWrapper) {
                    WrapperManager.stop(1);
                } else {
                    System.exit(1);
                }
            } finally {
                getBootProgressMonitor().dispose();
            }
        }
    };

    System.out.print("Starting installation wizard");
    mainThread.start();

    /*
     * Wait for up to 5 minutes for the server to become available we need
     * to wait this long because precompilation can take a while!
     */

    int waitFor = 60 * 5;

    boolean running = false;

    if (!"true".equals(SystemProperties.get("adito.disableStartupCheck", "false"))) {
        int i = 0;
        for (; i < waitFor && !running; i++) {
            try {
                System.out.print(".");
                Socket s = new Socket(realHostname, realPort);
                s.close();
                running = true;
            } catch (Exception ex) {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex2) {
                }
            }
        }
        System.out.println();
    } else {
        running = true;
    }
    if (!running) {
        System.out.println("Failed to start installation wizard. Check the logs for more detail.");
        if (useWrapper) {
            WrapperManager.stop(1);
        } else {
            System.exit(1);
        }
    }
}

From source file:com.sslexplorer.server.Main.java

private void setupMode() throws Exception {

    // Ensure that https redirect is not turned on in jetty
    System.setProperty("jetty.force.HTTPSRedirect", "false");

    getBootProgressMonitor().updateMessage("Creating server");
    getBootProgressMonitor().updateProgress(8);

    actualPort = defaultPort == -1 ? 28080 : defaultPort;
    serverLock.start(actualPort);/*  w w  w . j a va  2s. com*/

    server = createServer();

    SocketListener socketListener = new SocketListener();
    socketListener.setPort(actualPort);
    socketListener.setMinThreads(10);
    socketListener.setMaxThreads(200);
    socketListener.setMaxIdleTimeMs(0);
    socketListener.setLowResourcePersistTimeMs(2000);
    socketListener.setAcceptQueueSize(0);
    socketListener.setPoolName("P1");
    server.addListener(socketListener);

    // // Add the context
    // HttpContext context = new CustomHttpContext(server, "/",
    // useDevConfig);
    // server.addContext(context);

    // Create the webapp

    getBootProgressMonitor().updateMessage("Creating web application");
    getBootProgressMonitor().updateProgress(9);

    webappContext = new CustomWebApplicationContext(useDevConfig, bootLoader);
    webappContext.setRedirectNullPath(false);
    addLifecycleListener(webappContext);
    server.addContext(webappContext);

    // Configure the server
    server.setRequestsPerGC(2000);

    String realHostname = hostname == null ? InetAddress.getLocalHost().getHostName() : hostname;

    /*
     * If the 'Active DNS' feature is enabled, the DNS server may return the
     * wild-card name. This will probably fail. As a work-around, if the
     * hostname looks like a wildcard, then it is simply changed to
     * 'localhost'.
     */
    if (realHostname.startsWith("*.")) {
        realHostname = "localhost";
    }

    //
    final String fRealHostname = realHostname;
    final int realPort = defaultPort == -1 ? 28080 : defaultPort;

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    mainThread = new Thread(threadGroup, "WebServer") {
        public void run() {
            // Start the server
            try {
                server.start();

                if (!useWrapper && !"true".equals(SystemProperties.get("sslexplorer.noBrowserLaunch"))) {
                    try {
                        BrowserLauncher.openURL("http://" + fRealHostname + ":" + realPort);
                        System.out.println("A browser has been opened and pointed to http://" + fRealHostname
                                + ":" + realPort + ". ");
                    } catch (Exception ex) {
                        System.out.println(
                                "Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                    }
                } else {
                    System.out.println("Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                }
                System.out.println(
                        "\nPress CTRL+C or use the 'Shutdown' option from the web interface to leave the installation wizard.");
                getBootProgressMonitor().updateMessage("Server is now running");
                getBootProgressMonitor().updateProgress(100);
                Thread.sleep(2000);
            } catch (Exception e) {
                log.error("Failed to start Jetty. " + e.getMessage(), e);
                if (useWrapper) {
                    WrapperManager.stop(1);
                } else {
                    System.exit(1);
                }
            } finally {
                getBootProgressMonitor().dispose();
            }
        }
    };

    System.out.print("Starting installation wizard");
    mainThread.start();

    /*
     * Wait for up to 5 minutes for the server to become available we need
     * to wait this long because precompilation can take a while!
     */

    int waitFor = 60 * 5;

    boolean running = false;

    if (!"true".equals(SystemProperties.get("sslexplorer.disableStartupCheck", "false"))) {
        int i = 0;
        for (; i < waitFor && !running; i++) {
            try {
                System.out.print(".");
                Socket s = new Socket(realHostname, realPort);
                s.close();
                running = true;
            } catch (Exception ex) {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex2) {
                }
            }
        }
        System.out.println();
    } else {
        running = true;
    }
    if (!running) {
        System.out.println("Failed to start installation wizard. Check the logs for more detail.");
        if (useWrapper) {
            WrapperManager.stop(1);
        } else {
            System.exit(1);
        }
    }
}

From source file:com.clustercontrol.agent.Agent.java

/**
 * ??sendManagerDiscoveryInfo?/* w  w  w.j ava2s .co m*/
 * TCP 24005?????????IP?
 * 
 * @throws Exception
 */
private String receiveManagerDiscoveryInfo() throws Exception {
    int default_port = 24005;
    String portStr = AgentProperties.getProperty("discovery.pingport", Integer.toString(default_port));
    int port = Integer.parseInt(portStr);
    if (port < 1 || port > 65535) {
        port = default_port;
    }
    ServerSocket servSock = null;
    Socket clntSock = null;

    final int BUFSIZE = 256;
    int tmpRecvMsgSize = 0;
    int recvMsgSize = 0;
    byte[] receiveBuf = new byte[BUFSIZE];
    String recvMsg = "";

    try {
        servSock = new ServerSocket(port);

        // ????
        clntSock = servSock.accept();
        m_log.info("connecting to " + clntSock.getRemoteSocketAddress().toString());

        InputStream in = clntSock.getInputStream();
        OutputStream out = clntSock.getOutputStream();

        while ((tmpRecvMsgSize = in.read(receiveBuf)) != -1) {
            out.write(receiveBuf, 0, tmpRecvMsgSize);
            recvMsgSize = tmpRecvMsgSize;
        }

        recvMsg = new String(receiveBuf, 0, recvMsgSize);
        m_log.info("receive message : " + recvMsg);
    } catch (Exception e) {
        m_log.warn("receiveManagerIp " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    } finally {
        try {
            if (clntSock != null) {
                clntSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
        try {
            if (servSock != null) {
                servSock.close();
            }
        } catch (Exception e) {
            m_log.warn("receiveManagerIp: " + e);
        }
    }
    return recvMsg;
}

From source file:com.google.vrtoolkit.cardboard.samples.treasurehunt.MainActivity.java

private void sendArmoRequest(boolean _lock) {
    final boolean lock = _lock;

    if (lock == false) {
        if (armo_locked == false) {
            return;
        }//  www . j  ava2  s  . com
    }
    if (lock) {
        if (armo_locked == true) {
            return;
        }
    }
    new Thread(new Runnable() {
        public void run() {
            try {
                String host = ARMO_HOST;
                Socket socket = new Socket(host, 5000);
                String request = "GET /position/180 HTTP/1.0\r\n\r\n";
                if (lock == false) {
                    if (armo_locked == false) {
                        return;
                    }
                    armo_locked = false;
                }
                if (lock) {
                    if (armo_locked == true) {
                        return;
                    }
                    request = "GET /position/85 HTTP/1.0\r\n\r\n";
                    armo_locked = true;
                }
                OutputStream os = socket.getOutputStream();
                os.write(request.getBytes());
                os.flush();

                InputStream is = socket.getInputStream();
                int ch;
                while ((ch = is.read()) != -1)
                    System.out.print((char) ch);
                socket.close();
            } catch (IOException e) {
                Log.e("Lock_request", "Something went wrong: " + e.getMessage());
            }
        }
    }).start();
}