List of usage examples for java.net Socket getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java
License:asdf
@Test public void testGoogleConnect() { System.out.println("BANKAI"); Socket tmp_socket = null;/*w ww .j a v a 2 s . com*/ try { tmp_socket = new Socket("www.google.com", 80); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } final Socket socket = tmp_socket; new Thread() { @Override public void run() { while (true) { try { int read; System.out.print(read = socket.getInputStream().read()); System.out.print("[" + (char) read + "]"); System.out.print(","); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } } } }.start(); try { //socket.getOutputStream().write("GET http://www.google.com/ HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\n".getBytes()); //URI uri = new URI("/?gfe_rd=cr&ei=F07YVIjKBe_98wfq74LICw"); URI uri = new URI("/asdfwef?"); System.out.println(uri.getRawFragment()); System.out.println(uri.getRawPath()); System.out.println(uri.getRawQuery()); System.out.println(uri.getRawSchemeSpecificPart()); socket.getOutputStream() .write(("GET / HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\r\n").getBytes()); System.out.println("REQUEST SENT"); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.sleep(50000); } catch (InterruptedException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } }
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 v a 2s.c o 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 = "", "")"); 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.att.android.arodatacollector.main.AROCollectorService.java
/** * Stops the ARO Data Collector trace by stopping the tcpdump process. * // w ww. j a v a 2 s. c o m * @throws java.io.IOException * @throws java.net.UnknownHostException */ public void requestDataCollectorStop() { dataCollectorStopWatchTimer(); try { if (DEBUG) { Log.i(TAG, "enter requestDataCollectorStop at " + System.currentTimeMillis()); } logTcpdumpPid(); final Socket tcpdumpsocket = new Socket(InetAddress.getByName("localhost"), 50999); final OutputStream out = tcpdumpsocket.getOutputStream(); out.write("STOP".getBytes("ASCII")); out.flush(); out.close(); tcpdumpsocket.close(); getBatteryInfo(); getAlarmInfo(outAlarmInfoEndFileName); restoreDebugMaskDefault(); if (DEBUG) { Log.i(TAG, "exit requestDataCollectorStop at " + System.currentTimeMillis()); } } catch (Exception e) { Log.e(TAG, "exception in stopTcpDump", e); //for debugging, check if tcpdump is still running logTcpdumpPid(); } }
From source file:com.raddle.tools.ClipboardTransferMain.java
private void initGUI() { try {/*w w w . j a v a2 s. co m*/ { this.setTitle("\u8fdc\u7a0b\u526a\u5207\u677f"); getContentPane().setLayout(null); { remoteClipGetBtn = new JButton(); getContentPane().add(remoteClipGetBtn); remoteClipGetBtn.setText("\u83b7\u5f97\u8fdc\u7a0b\u526a\u5207\u677f"); remoteClipGetBtn.setBounds(12, 22, 151, 29); remoteClipGetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { doInSocket(new SocketCallback() { @Override public Object connected(Socket socket) throws Exception { if (!isProcessing) { isProcessing = true; try { ClipCommand cmd = new ClipCommand(); cmd.setCmdCode(ClipCommand.CMD_GET_CLIP); updateMessage("??"); // ?? ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); out.writeObject(cmd); // ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); ClipResult result = (ClipResult) in.readObject(); if (result.isSuccess()) { setLocalClipboard(result); StringBuilder sb = new StringBuilder(); for (DataFlavor dataFlavor : result.getClipdata().keySet()) { sb.append("\n"); sb.append(dataFlavor.getPrimaryType()).append("/") .append(dataFlavor.getSubType()); } updateMessage("??? " + sb); } else { updateMessage("?:" + result.getMessage()); } in.close(); out.close(); } catch (Exception e) { updateMessage("?:" + e.getMessage()); } finally { isProcessing = false; } } return null; } }); } }); } { remoteClipSetBtn = new JButton(); getContentPane().add(remoteClipSetBtn); remoteClipSetBtn.setText("\u8bbe\u7f6e\u8fdc\u7a0b\u526a\u5207\u677f"); remoteClipSetBtn.setBounds(181, 22, 159, 29); remoteClipSetBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setRemoteClipboard(true); } }); } { serverLeb = new JLabel(); getContentPane().add(serverLeb); serverLeb.setText("\u8fdc\u7a0b\u670d\u52a1\u5668\u5730\u5740(IP:PORT)"); serverLeb.setBounds(12, 63, 162, 17); } { serverAddrTxt = new JTextField(); getContentPane().add(serverAddrTxt); serverAddrTxt.setBounds(169, 58, 186, 27); } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); jLabel1.setText("\u6d88\u606f\uff1a"); jLabel1.setBounds(12, 97, 48, 24); } { jLabel2 = new JLabel(); getContentPane().add(jLabel2); jLabel2.setText("\u672c\u5730\u526a\u5207\u677f\u670d\u52a1"); jLabel2.setBounds(12, 297, 91, 20); } { clipServerStartBtn = new JButton(); getContentPane().add(clipServerStartBtn); clipServerStartBtn.setText("\u542f\u52a8"); clipServerStartBtn.setBounds(12, 329, 79, 29); clipServerStartBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { startServer(); } }); } { clipServerStopBtn = new JButton(); getContentPane().add(clipServerStopBtn); clipServerStopBtn.setText("\u505c\u6b62"); clipServerStopBtn.setBounds(103, 329, 81, 29); clipServerStopBtn.setEnabled(false); clipServerStopBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { shutdown(); } }); } { jLabel3 = new JLabel(); getContentPane().add(jLabel3); jLabel3.setText("\u7aef\u53e3\uff1a"); jLabel3.setBounds(196, 335, 44, 17); } { portTxt = new JTextField(); getContentPane().add(portTxt); portTxt.setText("11221"); portTxt.setBounds(252, 330, 88, 27); } { modifyClipChk = new JCheckBox(); getContentPane().add(modifyClipChk); modifyClipChk.setText("\u5141\u8bb8\u8fdc\u7a0b\u4fee\u6539\u526a\u5207\u677f"); modifyClipChk.setBounds(12, 377, 172, 22); } { clearBtn = new JButton(); getContentPane().add(clearBtn); clearBtn.setText("\u6e05\u7a7a\u672c\u5730\u7cfb\u7edf\u526a\u5207\u677f"); clearBtn.setBounds(196, 374, 159, 29); clearBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable tText = new StringSelection(null); sysc.setContents(tText, null); } }); } { autoChk = new JCheckBox(); autoChk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { m.setEnabled(autoChk.isSelected()); } }); getContentPane().add(autoChk); autoChk.setText("\u81ea\u52a8\u8bbe\u7f6e\u8fdc\u7a0b\u526a\u5207\u677f"); autoChk.setBounds(12, 405, 172, 22); } } JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(55, 97, 542, 199); getContentPane().add(scrollPane); { messageArea = new JTextArea(); scrollPane.setViewportView(messageArea); } this.setSize(611, 465); { } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.npr.android.test.HttpServer.java
private void processRequest(DataSource dataSource, Socket client) throws IllegalStateException, IOException { if (dataSource == null) { Log.e(TAG, "Invalid (null) resource."); client.close();//from www.j av a 2 s.co m return; } Log.d(TAG, "setting response headers"); StringBuilder httpString = new StringBuilder(); httpString.append(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK")); httpString.append("\n"); httpString.append("Content-Type: ").append(dataSource.getContentType()); httpString.append("\n"); // Some content (e.g. streams) does not define a length long length = dataSource.getContentLength(); if (length >= 0) { httpString.append("Content-Length: ").append(length); httpString.append("\n"); } httpString.append("\n"); Log.d(TAG, "headers done"); InputStream data = null; try { data = dataSource.createInputStream(); byte[] buffer = httpString.toString().getBytes(); int readBytes; Log.d(TAG, "writing to client"); client.getOutputStream().write(buffer, 0, buffer.length); // Start sending content. byte[] buff = new byte[1024 * 50]; while (isRunning) { readBytes = data.read(buff, 0, buff.length); if (readBytes == -1) { if (simulateStream) { data.close(); data = dataSource.createInputStream(); readBytes = data.read(buff, 0, buff.length); if (readBytes == -1) { throw new IOException("Error re-opening data source for looping."); } } else { break; } } client.getOutputStream().write(buff, 0, readBytes); } } catch (SocketException e) { // Ignore when the client breaks connection Log.w(TAG, "Ignoring " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "Error getting content stream.", e); } catch (Exception e) { Log.e(TAG, "Error streaming file content.", e); } finally { if (data != null) { data.close(); } client.close(); } }
From source file:game.Clue.ClueGameUI.java
private void sendMsgToServer(Socket clientSocket, String msg) { try {/* ww w.j a va 2 s.c om*/ PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); out.println(msg); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } }
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 . j av a 2 s.c om 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:com.vkassin.mtrade.Common.java
public static void login(final Context ctx) { // ctx = Common.app_ctx; Common.connected = false;// w w w.j a v a 2 s. c om if (inLogin) return; inLogin = true; if (Common.mainActivity != null) Common.mainActivity.handler.sendMessage( Message.obtain(Common.mainActivity.handler, Common.mainActivity.DISMISS_PROGRESS_DIALOG)); // while(true) { final Dialog dialog = new Dialog(ctx); dialog.setContentView(R.layout.login_dialog); dialog.setTitle(R.string.LoginDialogTitle); dialog.setCancelable(false); final EditText nametxt = (EditText) dialog.findViewById(R.id.loginnameedit); final EditText passtxt = (EditText) dialog.findViewById(R.id.passwordedit); final EditText passtxt1 = (EditText) dialog.findViewById(R.id.passwordedit1); final EditText passtxt2 = (EditText) dialog.findViewById(R.id.passwordedit2); final EditText mailtxt = (EditText) dialog.findViewById(R.id.emailedit2); String nam = myaccount.get("name"); Common.oldName = nam; if (nam != null) { nametxt.setText(nam); passtxt.requestFocus(); } Button customDialog_Register = (Button) dialog.findViewById(R.id.goregister); customDialog_Register.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { dialog.setTitle(R.string.LoginDialogTitle1); final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354); layreg.setVisibility(View.VISIBLE); final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543); laylog.setVisibility(View.GONE); } }); Button customDialog_Register1 = (Button) dialog.findViewById(R.id.goregister1); customDialog_Register1.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { if (mailtxt.getText().length() < 1) { Toast toast = Toast.makeText(mainActivity, R.string.CorrectEmail, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); return; } if (passtxt1.getText().length() < 1) { Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); return; } if (!passtxt2.getText().toString().equals(passtxt1.getText().toString())) { Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword1, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); return; } try { Socket sock = new Socket(ip_addr, port_register); JSONObject msg = new JSONObject(); msg.put("objType", Common.MSG_REGISTER); msg.put("time", Calendar.getInstance().getTimeInMillis()); msg.put("user", mailtxt.getText().toString()); msg.put("passwd", passtxt1.getText().toString()); msg.put("version", Common.PROTOCOL_VERSION); msg.put("sign", sign(mailtxt.getText().toString(), passtxt1.getText().toString())); byte[] array = msg.toString().getBytes(); ByteBuffer buff = ByteBuffer.allocate(array.length + 4); buff.putInt(array.length); buff.put(array); sock.getOutputStream().write(buff.array()); ByteBuffer buff1 = ByteBuffer.allocate(4); buff1.put(readMsg(sock.getInputStream(), 4)); buff1.position(0); int pkgSize = buff1.getInt(); // Log.i(TAG, "size = "+pkgSize); String s = new String(readMsg(sock.getInputStream(), pkgSize)); sock.close(); JSONObject jo = new JSONObject(s); Log.i(TAG, "register answer = " + jo); int t = jo.getInt("status"); switch (t) { case 1: Toast toast = Toast.makeText(mainActivity, R.string.RegisterStatus1, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); dialog.setTitle(R.string.LoginDialogTitle); final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354); layreg.setVisibility(View.GONE); final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543); laylog.setVisibility(View.VISIBLE); nametxt.setText(mailtxt.getText()); break; case -2: Toast toast1 = Toast.makeText(mainActivity, R.string.RegisterStatus3, Toast.LENGTH_LONG); toast1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast1.show(); break; default: Toast toast2 = Toast.makeText(mainActivity, R.string.RegisterStatus2, Toast.LENGTH_LONG); toast2.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast2.show(); break; } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Error in registration process!!", e); Toast toast = Toast.makeText(mainActivity, R.string.ConnectError, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } }); Button customDialog_CancelReg = (Button) dialog.findViewById(R.id.cancelreg); customDialog_CancelReg.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { dialog.setTitle(R.string.LoginDialogTitle); final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354); layreg.setVisibility(View.GONE); final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543); laylog.setVisibility(View.VISIBLE); } }); Button customDialog_Dismiss = (Button) dialog.findViewById(R.id.gologin); customDialog_Dismiss.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.lradio0); Common.isSSL = bu0.isChecked(); inLogin = false; JSONObject msg = new JSONObject(); try { msg.put("objType", Common.LOGOUT); msg.put("time", Calendar.getInstance().getTimeInMillis()); msg.put("version", Common.PROTOCOL_VERSION); msg.put("status", 1); mainActivity.writeJSONMsg(msg); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Error! Cannot create JSON logout object", e); } myaccount.put("name", nametxt.getText().toString()); myaccount.put("password", passtxt.getText().toString()); Log.i(TAG, "myaccount username: " + myaccount.get("name") + " password: " + myaccount.get("password")); dialog.dismiss(); mainActivity.stop(); // saveAccountDetails(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } loginFromDialog = true; // mainActivity.refresh(); Common.keypassword(ctx); } }); dialog.show(); // Common.confChanged = false; // }//while(true); }
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; }/*from w ww .j ava 2 s . c o m*/ } 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(); }
From source file:com.sun.grizzly.http.jk.common.ChannelSocket.java
public void accept(MsgContext ep) throws IOException { if (sSocket == null) { return;/*from www .j ava 2s . co m*/ } synchronized (this) { while (paused) { try { wait(); } catch (InterruptedException ie) { //Ignore, since can't happen } } } Socket s = sSocket.accept(); ep.setNote(socketNote, s); if (LoggerUtils.getLogger().isLoggable(Level.FINEST)) { LoggerUtils.getLogger().log(Level.FINEST, "Accepted socket " + s); } try { setSocketOptions(s); } catch (SocketException sex) { LoggerUtils.getLogger().log(Level.FINEST, "Error initializing Socket Options", sex); } requestCount++; InputStream is = new BufferedInputStream(s.getInputStream()); OutputStream os; if (bufferSize > 0) { os = new BufferedOutputStream(s.getOutputStream(), bufferSize); } else { os = s.getOutputStream(); } ep.setNote(isNote, is); ep.setNote(osNote, os); ep.setControl(tp); }