List of usage examples for java.net Socket getInetAddress
public InetAddress getInetAddress()
From source file:runtime.starter.MPJRun.java
private void pack(int nProcesses, int start_rank, Socket sockClient) { if (wdir == null) { wdir = System.getProperty("user.dir"); }//from w w w. j av a 2 s .com MPJProcessTicket ticket = new MPJProcessTicket(); ticket.setMpjHomeDir(mpjHomeDir); ticket.setClassPath(new String(urlArray)); ticket.setProcessCount(nProcesses); ticket.setStartingRank(start_rank); ticket.setWorkingDirectory(wdir); ticket.setUserID(System.getProperty("user.name")); if (this.zippedSource) { String zipFileName = UUID.randomUUID() + ".zip"; this.sourceFolder = wdir; IOHelper.zipFolder(this.sourceFolder, zipFileName); byte[] zipContents = IOHelper.ReadBinaryFile(zipFileName); String encodedString = Base64.encodeBase64String(zipContents); ticket.setSourceCode(encodedString); IOHelper.deleteFile(zipFileName); ticket.setZippedSource(true); } ticket.setMainClass(className); ticket.setConfFileContents(CONF_FILE_CONTENTS); ticket.setDeviceName(deviceName); IOMessagesThread ioMessages = new IOMessagesThread(sockClient); ioMessages.start(); ArrayList<String> jvmArgs = new ArrayList<String>(); for (int j = 0; j < jArgs.length; j++) { jvmArgs.add(jArgs[j]); } ticket.setJvmArgs(jvmArgs); ArrayList<String> appArgs = new ArrayList<String>(); for (int j = 0; j < aArgs.length; j++) { appArgs.add(aArgs[j]); } ticket.setAppArgs(appArgs); if (deviceName.equals("hybdev")) { ticket.setNetworkProcessCount(networkProcesscount); ticket.setTotalProcessCount(nprocs); ticket.setNetworkDevice(networkDevice); } if (ADEBUG) { ticket.setDebug(true); ticket.setDebugPort(DEBUG_PORT); } if (APROFILE) { ticket.setProfiler(true); } String ticketString = ticket.ToXML().toXmlString(); OutputStream outToServer = null; try { outToServer = sockClient.getOutputStream(); } catch (IOException e) { logger.info(" Unable to get deamon stream-"); e.printStackTrace(); } DataOutputStream out = new DataOutputStream(outToServer); try { int length = ticketString.getBytes().length; out.writeInt(length); if (DEBUG && logger.isDebugEnabled()) { logger.info("Machine Name: " + sockClient.getInetAddress().getHostName() + " Startting Rank: " + ticket.getStartingRank() + " Process Count: " + ticket.getProcessCount()); } out.write(ticketString.getBytes(), 0, length); out.flush(); } catch (IOException e) { logger.info(" Unable to write on deamon stream-"); e.printStackTrace(); } }
From source file:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java
@Override public void writeBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken, final String clientname, final DatanodeInfo[] targets, final DatanodeInfo srcDataNode, final BlockConstructionStage stage, final int pipelineSize, final long minBytesRcvd, final long maxBytesRcvd, final long latestGenerationStamp, DataChecksum requestedChecksum, CachingStrategy cachingStrategy) throws IOException { previousOpClientName = clientname;//from w w w. j a va 2 s . co m updateCurrentThreadName("Receiving block " + block); isDatanode = clientname.length() == 0; isClient = !isDatanode; isTransfer = stage == BlockConstructionStage.TRANSFER_RBW || stage == BlockConstructionStage.TRANSFER_FINALIZED; this.stage = stage; this.block = block; this.latestGenerationStamp = latestGenerationStamp; this.minBytesRcvd = minBytesRcvd; // check single target for transfer-RBW/Finalized if (isTransfer && targets.length > 0) { throw new IOException(stage + " does not support multiple targets " + Arrays.asList(targets)); } if (LOG.isDebugEnabled()) { LOG.debug("opWriteBlock: stage=" + stage + ", clientname=" + clientname + "\n block =" + block + ", newGs=" + latestGenerationStamp + ", bytesRcvd=[" + minBytesRcvd + ", " + maxBytesRcvd + "]" + "\n targets=" + Arrays.asList(targets) + "; pipelineSize=" + pipelineSize + ", srcDataNode=" + srcDataNode); LOG.debug("isDatanode=" + isDatanode + ", isClient=" + isClient + ", isTransfer=" + isTransfer); LOG.debug("writeBlock receive buf size " + peer.getReceiveBufferSize() + " tcp no delay " + peer.getTcpNoDelay()); } // We later mutate block's generation stamp and length, but we need to // forward the original version of the block to downstream mirrors, so // make a copy here. final ExtendedBlock originalBlock = new ExtendedBlock(block); block.setNumBytes(DataXceiverServer.estimateBlockSize); LOG.info("Receiving " + block + " src: " + remoteAddress + " dest: " + localAddress); // reply to upstream datanode or client replyOut = new DataOutputStream( new BufferedOutputStream(getOutputStream(), HdfsConstants.SMALL_BUFFER_SIZE)); checkAccess(replyOut, isClient, block, blockToken, Op.WRITE_BLOCK, BlockTokenSecretManager.AccessMode.WRITE); mirrorOut = null; // stream to next target mirrorIn = null; // reply from next target Socket mirrorSock = null; // socket to next target blockReceiver = null; // responsible for data handling String mirrorNode = null; // the name:port of next target String firstBadLink = ""; // first datanode that failed in connection setup Status mirrorInStatus = SUCCESS; try { if (isDatanode || stage != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) { // open a block receiver blockReceiver = new DWRRBlockReceiver(block, in, peer.getRemoteAddressString(), peer.getLocalAddressString(), stage, latestGenerationStamp, minBytesRcvd, maxBytesRcvd, clientname, srcDataNode, datanode, requestedChecksum, cachingStrategy); storageUuid = blockReceiver.getStorageUuid(); } else { storageUuid = datanode.data.recoverClose(block, latestGenerationStamp, minBytesRcvd); } // // Connect to downstream machine, if appropriate // if (targets.length > 0) { InetSocketAddress mirrorTarget = null; // Connect to backup machine mirrorNode = targets[0].getXferAddr(connectToDnViaHostname); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to datanode " + mirrorNode); } mirrorTarget = NetUtils.createSocketAddr(mirrorNode); mirrorSock = datanode.newSocket(); try { int timeoutValue = dnConf.socketTimeout + (HdfsServerConstants.READ_TIMEOUT_EXTENSION * targets.length); int writeTimeout = dnConf.socketWriteTimeout + (HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * targets.length); NetUtils.connect(mirrorSock, mirrorTarget, timeoutValue); mirrorSock.setSoTimeout(timeoutValue); mirrorSock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); OutputStream unbufMirrorOut = NetUtils.getOutputStream(mirrorSock, writeTimeout); InputStream unbufMirrorIn = NetUtils.getInputStream(mirrorSock); if (dnConf.encryptDataTransfer && !dnConf.trustedChannelResolver.isTrusted(mirrorSock.getInetAddress())) { IOStreamPair encryptedStreams = DataTransferEncryptor.getEncryptedStreams(unbufMirrorOut, unbufMirrorIn, datanode.blockPoolTokenSecretManager .generateDataEncryptionKey(block.getBlockPoolId())); unbufMirrorOut = encryptedStreams.out; unbufMirrorIn = encryptedStreams.in; } mirrorOut = new DataOutputStream( new BufferedOutputStream(unbufMirrorOut, HdfsConstants.SMALL_BUFFER_SIZE)); mirrorIn = new DataInputStream(unbufMirrorIn); new Sender(mirrorOut).writeBlock(originalBlock, blockToken, clientname, targets, srcDataNode, stage, pipelineSize, minBytesRcvd, maxBytesRcvd, latestGenerationStamp, requestedChecksum, cachingStrategy); mirrorOut.flush(); // read connect ack (only for clients, not for replication req) if (isClient) { BlockOpResponseProto connectAck = BlockOpResponseProto .parseFrom(PBHelper.vintPrefixed(mirrorIn)); mirrorInStatus = connectAck.getStatus(); firstBadLink = connectAck.getFirstBadLink(); if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) { LOG.info("Datanode " + targets.length + " got response for connect ack " + " from downstream datanode with firstbadlink as " + firstBadLink); } } } catch (IOException e) { if (isClient) { BlockOpResponseProto.newBuilder().setStatus(ERROR) // NB: Unconditionally using the xfer addr w/o hostname .setFirstBadLink(targets[0].getXferAddr()).build().writeDelimitedTo(replyOut); replyOut.flush(); } IOUtils.closeStream(mirrorOut); mirrorOut = null; IOUtils.closeStream(mirrorIn); mirrorIn = null; IOUtils.closeSocket(mirrorSock); mirrorSock = null; if (isClient) { LOG.error(datanode + ":Exception transfering block " + block + " to mirror " + mirrorNode + ": " + e); throw e; } else { LOG.info(datanode + ":Exception transfering " + block + " to mirror " + mirrorNode + "- continuing without the mirror", e); } } } // send connect-ack to source for clients and not transfer-RBW/Finalized if (isClient && !isTransfer) { if (LOG.isDebugEnabled() || mirrorInStatus != SUCCESS) { LOG.info("Datanode " + targets.length + " forwarding connect ack to upstream firstbadlink is " + firstBadLink); } BlockOpResponseProto.newBuilder().setStatus(mirrorInStatus).setFirstBadLink(firstBadLink).build() .writeDelimitedTo(replyOut); replyOut.flush(); } // receive the block and mirror to the next target if (blockReceiver != null) { LOG.info("CAMAMILLA " + classId + " receive the block and mirror to the next target"); // TODO TODO log entra String mirrorAddr = (mirrorSock == null) ? null : mirrorNode; int len = blockReceiver.receiveBlock(mirrorOut, mirrorIn, replyOut, mirrorAddr, null, targets); DWRRRequestObject newReq = new DWRRRequestObject(this, classId, op, len); dwrrmanager.addOp(newReq, classId); LOG.info("CAMAMILLA " + classId + " encuada peticio WRITE "); // TODO TODO log } } catch (IOException ioe) { LOG.info("opWriteBlock " + block + " received exception " + ioe); throw ioe; } finally { // close all opened streams IOUtils.closeSocket(mirrorSock); } }
From source file:Tcpbw100.java
public boolean test_c2s(Protocol ctl) throws IOException { // byte buff2[] = new byte[8192]; byte buff2[] = new byte[64 * 1024]; Message msg = new Message(); if ((tests & TEST_C2S) == TEST_C2S) { showStatus(messages.getString("outboundTest")); results.append(messages.getString("runningOutboundTest") + " "); statistics.append(messages.getString("runningOutboundTest") + " "); emailText += messages.getString("runningOutboundTest") + " "; pub_status = "runningOutboundTest"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; }/*from w ww . j a va 2 s. co m*/ if (msg.type != TEST_PREPARE) { errmsg = messages.getString("outboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int c2sport = Integer.parseInt(new String(msg.body)); final Socket outSocket; try { outSocket = new Socket(host, c2sport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = messages.getString("unknownServer") + "\n"; return true; } catch (IOException e) { System.err.println("Couldn't get 2nd connection to: " + host); errmsg = messages.getString("serverBusy15s") + "\n"; return true; } // Get server IP address from the outSocket. pub_host = outSocket.getInetAddress().getHostAddress().toString(); final OutputStream out = outSocket.getOutputStream(); // wait here for signal from server application // This signal tells the client to start pumping out data if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_START) { errmsg = messages.getString("outboundWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } byte c = '0'; int i; for (i = 0; i < lth; i++) { if (c == 'z') c = '0'; buff2[i] = c++; } System.err.println("Send buffer size =" + i); pkts = 0; t = System.currentTimeMillis(); pub_time = t; new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println(e); } try { out.close(); outSocket.close(); } catch (IOException e) { System.out.println(e); } } }.start(); while (true) { // System.err.println("Send pkt = " + pkts + "; at " + System.currentTimeMillis()); try { out.write(buff2, 0, buff2.length); } catch (SocketException e) { System.out.println(e); break; } // catch (InterruptedIOException iioe) { catch (IOException ioe) { System.out.println("Client socket timed out"); break; } pkts++; pub_bytes = (pkts * lth); } t = System.currentTimeMillis() - t; System.err.println(t + "sec test completed"); if (t == 0) { t = 1; } System.out.println((8.0 * pkts * buff2.length) / t + " kb/s outbound"); c2sspd = ((8.0 * pkts * buff2.length) / 1000) / t; /* receive the c2sspd from the server */ if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("outboundWrongMessage"); if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } String tmpstr3 = new String(msg.body); sc2sspd = Double.parseDouble(tmpstr3) / 1000.0; if (sc2sspd < 1.0) { results.append(prtdbl(sc2sspd * 1000) + "kb/s\n"); statistics.append(prtdbl(sc2sspd * 1000) + "kb/s\n"); emailText += prtdbl(sc2sspd * 1000) + "kb/s\n%0A"; } else { results.append(prtdbl(sc2sspd) + "Mb/s\n"); statistics.append(prtdbl(sc2sspd) + "Mb/s\n"); emailText += prtdbl(sc2sspd) + "Mb/s\n%0A"; } // Expose upload speed to JavaScript clients pub_c2sspd = sc2sspd; uplLbl.setText(String.format(padding + "%.3f Mbps", sc2sspd)); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_FINALIZE) { errmsg = messages.getString("outboundWrongMessage"); if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } } return false; }
From source file:org.eredlab.g4.ccl.net.ftp.FTPClient.java
/** * Establishes a data connection with the FTP server, returning * a Socket for the connection if successful. If a restart * offset has been set with {@link #setRestartOffset(long)}, * a REST command is issued to the server with the offset as * an argument before establishing the data connection. Active * mode connections also cause a local PORT command to be issued. * <p>//from w ww . ja v a2 s .com * @param command The text representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is * set to null, then the command is sent with no argument. * @return A Socket corresponding to the established data connection. * Null is returned if an FTP protocol error is reported at * any point during the establishment and initialization of * the connection. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. */ protected Socket _openDataConnection_(int command, String arg) throws IOException { Socket socket; if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) return null; if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { ServerSocket server; server = _socketFactory_.createServerSocket(0, 1, getLocalAddress()); if (!FTPReply.isPositiveCompletion(port(getLocalAddress(), server.getLocalPort()))) { server.close(); return null; } if ((__restartOffset > 0) && !restart(__restartOffset)) { server.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { server.close(); return null; } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) server.setSoTimeout(__dataTimeout); socket = server.accept(); server.close(); } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) return null; __parsePassiveModeReply((String) _replyLines.elementAt(0)); socket = _socketFactory_.createSocket(__passiveHost, __passivePort); if ((__restartOffset > 0) && !restart(__restartOffset)) { socket.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } } if (__remoteVerificationEnabled && !verifyRemote(socket)) { InetAddress host1, host2; host1 = socket.getInetAddress(); host2 = getRemoteAddress(); socket.close(); throw new IOException("Host attempting data connection " + host1.getHostAddress() + " is not same as server " + host2.getHostAddress()); } if (__dataTimeout >= 0) socket.setSoTimeout(__dataTimeout); return socket; }
From source file:Tcpbw100.java
public boolean test_mid(Protocol ctl) throws IOException { byte buff[] = new byte[8192]; Message msg = new Message(); if ((tests & TEST_MID) == TEST_MID) { /* now look for middleboxes (firewalls, NATs, and other boxes that * muck with TCP's end-to-end priciples */// w w w .j av a 2 s . c o m showStatus(messages.getString("middleboxTest")); results.append(messages.getString("checkingMiddleboxes") + " "); statistics.append(messages.getString("checkingMiddleboxes") + " "); emailText = messages.getString("checkingMiddleboxes") + " "; pub_status = "checkingMiddleboxes"; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_PREPARE) { errmsg = messages.getString("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } int midport = Integer.parseInt(new String(msg.body)); Socket in2Socket = null; try { in2Socket = new Socket(host, midport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + host); errmsg = messages.getString("unknownServer") + "\n"; return true; } catch (IOException e) { System.err.println("Couldn't perform middlebox testing to: " + host); errmsg = messages.getString("middleboxFail") + "\n"; return true; } InputStream srvin2 = in2Socket.getInputStream(); OutputStream srvout2 = in2Socket.getOutputStream(); int largewin = 128 * 1024; in2Socket.setSoTimeout(6500); int bytes = 0; int inlth; t = System.currentTimeMillis(); pub_TimeStamp = new Date(); try { while ((inlth = srvin2.read(buff, 0, buff.length)) > 0) { bytes += inlth; pub_bytes = bytes; if ((System.currentTimeMillis() - t) > 5500) break; } } catch (IOException e) { } t = System.currentTimeMillis() - t; System.out.println(bytes + " bytes " + (8.0 * bytes) / t + " kb/s " + t / 1000 + " secs"); s2cspd = ((8.0 * bytes) / 1000) / t; if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_MSG) { errmsg = messages.getString("mboxWrongMessage") + "\n"; if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } tmpstr2 = new String(msg.body); String tmpstr4 = Double.toString(s2cspd * 1000); System.out.println("Sending '" + tmpstr4 + "' back to server"); ctl.send_msg(TEST_MSG, tmpstr4.getBytes()); try { tmpstr2 += in2Socket.getInetAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain Servers IP addresses: using " + host); errmsg = "getInetAddress() called failed\n"; tmpstr2 += host + ";"; results.append(messages.getString("lookupError") + "\n"); } System.err.println("calling in2Socket.getLocalAddress()"); try { tmpstr2 += in2Socket.getLocalAddress() + ";"; } catch (SecurityException e) { System.err.println("Unable to obtain local IP address: using 127.0.0.1"); errmsg = "getLocalAddress() call failed\n"; tmpstr2 += "127.0.0.1;"; } srvin2.close(); srvout2.close(); in2Socket.close(); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; return true; } if (msg.type != TEST_FINALIZE) { errmsg = messages.getString("mboxWrongMessage"); if (msg.type == MSG_ERROR) { errmsg += "ERROR MSG: " + Integer.parseInt(new String(msg.body), 16) + "\n"; } return true; } results.append(messages.getString("done") + "\n"); statistics.append(messages.getString("done") + "\n"); emailText += messages.getString("done") + "\n%0A"; } return false; }
From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java
/** * Establishes a data connection with the FTP server, returning * a Socket for the connection if successful. If a restart * offset has been set with {@link #setRestartOffset(long)}, * a REST command is issued to the server with the offset as * an argument before establishing the data connection. Active * mode connections also cause a local PORT command to be issued. * <p>/*from www. j av a 2 s .c o m*/ * @param command The text representation of the FTP command to send. * @param arg The arguments to the FTP command. If this parameter is * set to null, then the command is sent with no argument. * @return A Socket corresponding to the established data connection. * Null is returned if an FTP protocol error is reported at * any point during the establishment and initialization of * the connection. * @exception IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. * @since 3.1 */ protected Socket _openDataConnection_(String command, String arg) throws IOException { if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) { return null; } final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address; Socket socket; if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { // if no activePortRange was set (correctly) -> getActivePort() = 0 // -> new ServerSocket(0) -> bind to any free local port ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress()); try { // Try EPRT only if remote server is over IPv6, if not use PORT, // because EPRT has no advantage over PORT on IPv4. // It could even have the disadvantage, // that EPRT will make the data connection fail, because // today's intelligent NAT Firewalls are able to // substitute IP addresses in the PORT command, // but might not be able to recognize the EPRT command. if (isInet6Address) { if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) { return null; } } else { if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) { return null; } } if ((__restartOffset > 0) && !restart(__restartOffset)) { return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { return null; } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) { server.setSoTimeout(__dataTimeout); } socket = server.accept(); // Ensure the timeout is set before any commands are issued on the new socket if (__dataTimeout >= 0) { socket.setSoTimeout(__dataTimeout); } if (__receiveDataSocketBufferSize > 0) { socket.setReceiveBufferSize(__receiveDataSocketBufferSize); } if (__sendDataSocketBufferSize > 0) { socket.setSendBufferSize(__sendDataSocketBufferSize); } } finally { server.close(); } } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE // Try EPSV command first on IPv6 - and IPv4 if enabled. // When using IPv4 with NAT it has the advantage // to work with more rare configurations. // E.g. if FTP server has a static PASV address (external network) // and the client is coming from another internal network. // In that case the data connection after PASV command would fail, // while EPSV would make the client succeed by taking just the port. boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address; if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) { _parseExtendedPassiveModeReply(_replyLines.get(0)); } else { if (isInet6Address) { return null; // Must use EPSV for IPV6 } // If EPSV failed on IPV4, revert to PASV if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) { return null; } _parsePassiveModeReply(_replyLines.get(0)); } socket = _socketFactory_.createSocket(); if (__receiveDataSocketBufferSize > 0) { socket.setReceiveBufferSize(__receiveDataSocketBufferSize); } if (__sendDataSocketBufferSize > 0) { socket.setSendBufferSize(__sendDataSocketBufferSize); } if (__passiveLocalHost != null) { socket.bind(new InetSocketAddress(__passiveLocalHost, 0)); } // For now, let's just use the data timeout value for waiting for // the data connection. It may be desirable to let this be a // separately configurable value. In any case, we really want // to allow preventing the accept from blocking indefinitely. if (__dataTimeout >= 0) { socket.setSoTimeout(__dataTimeout); } socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout); if ((__restartOffset > 0) && !restart(__restartOffset)) { socket.close(); return null; } if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { socket.close(); return null; } } if (__remoteVerificationEnabled && !verifyRemote(socket)) { socket.close(); throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress() + " is not same as server " + getRemoteAddress().getHostAddress()); } return socket; }
From source file:Tcpbw100.java
public void dottcp(StatusPanel sPanel) throws IOException { Socket ctlSocket = null; if (!isApplication) { /************************************************************************* * Added by Seth Peery//w w w. jav a 2 s . c o m * Instead of using the getCodeBase().getHost() value for the testing server, * which assumes this applet is being served from the web100srv server, * use a parameter provided in the APPLET tag. * Note that for this to work the applet must be signed because you are * potentially accessing a server outside the source domain. */ if (host == null) { host = getParameter("testingServer"); System.err.println("host set to " + host); } reportHost = getParameter("reportHost"); String reportPortString = getParameter("reportPort"); userId = getParameter("userId"); connectionId = getParameter("connectionId"); /************************************************************************/ /* fall back to the old behaviour if the APPLET tag is not set */ if (host == null) { host = getCodeBase().getHost(); System.err.println("host set to " + host); } pub_host = host; if (reportHost == null) { reportHost = host; } if (reportPortString == null) { reportPort = 33001; } else { reportPort = new Integer(reportPortString); } } results.append("web100srv: '" + host + "' [" + InetAddress.getByName(host) + "]\n"); int ctlport = 3001; double wait2; int sbuf, rbuf; int i, wait, swait = 0; for (int iter = 0; iter < 2; iter++) { failed = false; String actual_host = host; try { if (preferIPv6.isSelected()) { try { System.setProperty("java.net.preferIPv6Addresses", "true"); System.setProperty("java.net.preferIPv4Stack", "false"); System.err.println("java.net.preferIPv6Addresses = " + System.getProperty("java.net.preferIPv6Addresses")); System.err.println( "java.net.preferIPv4Stack = " + System.getProperty("java.net.preferIPv4Stack")); } catch (SecurityException e) { System.err.println("Couldn't set system property. Check your security settings."); } } //this disables the checkbox while measuring preferIPv6.setEnabled(false); //preferIPv6Addresses does not seem to do anything . //So I'll try a different approach if (preferIPv6.isSelected()) { outerloop: for (InetAddress addr : InetAddress.getAllByName(host)) { System.err.println(host + " resolves to " + addr.getHostAddress()); if (addr instanceof Inet6Address) { actual_host = addr.getHostAddress(); System.err.println("host set to IPv6 address:" + actual_host); break outerloop; } } } else { System.err.println("trying with IPv6 resolving disabled, using " + actual_host); } if ((InetAddress.getByName(host) instanceof Inet6Address) && (!preferIPv6.isSelected())) { System.err.println("prefer IPv6 is not selected but the host supplied is an IPv6 address"); throw new UnknownHostException("fdsfds"); } ctlSocket = new Socket(actual_host, ctlport); } catch (UnknownHostException e) { System.err.println("Don't know about host: " + actual_host); errmsg = messages.getString("unknownServer") + "\n"; failed = true; return; } catch (IOException e) { System.err.println("Couldn't get the connection to: " + actual_host + " " + ctlport); errmsg = messages.getString("serverNotRunning") + " (" + actual_host + ":" + ctlport + ")\n"; if (preferIPv6.isSelected()) { preferIPv6.setSelected(false); continue; //if preferIPv6 is true, we can try once more with false, go again at the start of the for loop } failed = true; return; } break;//if we made it here, then we need not do the for loop again } Protocol ctl = new Protocol(ctlSocket); Message msg = new Message(); /* The beginning of the protocol */ if (ctlSocket.getInetAddress() instanceof Inet6Address) { results.append(messages.getString("connected") + " " + host + messages.getString("usingIpv6") + "\n"); } else { results.append(messages.getString("connected") + " " + host + messages.getString("usingIpv4") + "\n"); } /* write our test suite request */ ctl.send_msg(MSG_LOGIN, tests); /* read the specially crafted data that kicks off the old clients */ if (ctl.readn(msg, 13) != 13) { errmsg = messages.getString("unsupportedClient") + "\n"; failed = true; return; } for (;;) { if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; failed = true; return; } if (msg.type != SRV_QUEUE) { errmsg = messages.getString("loggingWrongMessage") + "\n"; failed = true; return; } String tmpstr3 = new String(msg.body); wait = Integer.parseInt(tmpstr3); System.out.println("wait flag received = " + wait); if (wait == 0) { break; } if (wait == 9988) { if (swait == 0) { errmsg = messages.getString("serverBusy") + "\n"; failed = true; return; } else { errmsg = messages.getString("serverFault") + "\n"; failed = true; return; } } if (wait == 9999) { errmsg = messages.getString("serverBusy60s") + "\n"; failed = true; return; } if (wait == 9990) { // signal from the server to see if the client is still alive ctl.send_msg(MSG_WAITING, tests); continue; } // Each test should take less than 30 seconds, so tell them 45 sec * number of // tests in the queue. wait = (wait * 45); results.append(messages.getString("otherClient") + wait + messages.getString("seconds") + ".\n"); swait = 1; } f.toBack(); ff.toBack(); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; failed = true; return; } if (msg.type != MSG_LOGIN) { errmsg = messages.getString("versionWrongMessage") + "\n"; failed = true; return; } String vVersion = new String(msg.body); if (!vVersion.startsWith("v")) { errmsg = messages.getString("incompatibleVersion"); failed = true; return; } System.out.println("Server version: " + vVersion.substring(1)); if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; failed = true; return; } if (msg.type != MSG_LOGIN) { errmsg = messages.getString("testsuiteWrongMessage") + "\n"; failed = true; return; } StringTokenizer tokenizer = new StringTokenizer(new String(msg.body), " "); while (tokenizer.hasMoreTokens()) { if (sPanel.wantToStop()) { ctl.send_msg(MSG_ERROR, "Manually stopped by the user".getBytes()); ctl.close(); ctlSocket.close(); errmsg = "\n" + messages.getString("stopped") + "\n"; failed = true; return; } int testId = Integer.parseInt(tokenizer.nextToken()); switch (testId) { case TEST_MID: sPanel.setText(messages.getString("middlebox")); simple_progressBar.setValue(1); simple_progressBar.setString(res.getString("step1")); progress_completed = 10; if (test_mid(ctl)) { results.append(errmsg); results.append(messages.getString("middleboxFail2") + "\n"); tests &= (~TEST_MID); } break; case TEST_SFW: sPanel.setText(messages.getString("simpleFirewall")); simple_progressBar.setValue(2); simple_progressBar.setString(res.getString("step2")); progress_completed = 20; if (test_sfw(ctl)) { results.append(errmsg); results.append(messages.getString("sfwFail") + "\n"); tests &= (~TEST_SFW); } break; case TEST_C2S: sPanel.setText(messages.getString("c2sThroughput")); simple_progressBar.setValue(4); simple_progressBar.setString(res.getString("step3")); progress_completed = 40; if (test_c2s(ctl)) { results.append(errmsg); results.append(messages.getString("c2sThroughputFailed") + "\n"); tests &= (~TEST_C2S); } break; case TEST_S2C: sPanel.setText(messages.getString("s2cThroughput")); simple_progressBar.setValue(7); simple_progressBar.setString(res.getString("step4")); progress_completed = 70; if (test_s2c(ctl, ctlSocket)) { results.append(errmsg); results.append(messages.getString("s2cThroughputFailed") + "\n"); tests &= (~TEST_S2C); } break; case TEST_META: System.err.println("testing meta!!"); sPanel.setText(messages.getString("meta")); if (test_meta(ctl, isApplication ? app_id : applet_id)) { results.append(errmsg); results.append(messages.getString("metaFailed") + "\n"); tests &= (~TEST_META); } break; default: errmsg = messages.getString("unknownID") + "\n"; failed = true; return; } } if (sPanel.wantToStop()) { ctl.send_msg(MSG_ERROR, "Manually stopped by the user".getBytes()); ctl.close(); ctlSocket.close(); errmsg = messages.getString("stopped") + "\n"; failed = true; return; } sPanel.setText(messages.getString("receiving")); i = 0; try { for (;;) { if (ctl.recv_msg(msg) != 0) { errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16) + " instead\n"; failed = true; return; } if (msg.type == MSG_LOGOUT) { break; } if (msg.type != MSG_RESULTS) { errmsg = messages.getString("resultsWrongMessage") + "\n"; failed = true; return; } tmpstr += new String(msg.body); i++; } } catch (IOException e) { } if (i == 0) { results.append(messages.getString("resultsTimeout") + "\n"); } System.err.println("Calling InetAddress.getLocalHost() twice"); try { diagnosis.append(messages.getString("client") + ": " + InetAddress.getLocalHost() + "\n"); } catch (SecurityException e) { diagnosis.append(messages.getString("client") + ": 127.0.0.1\n"); results.append(messages.getString("unableToObtainIP") + "\n"); System.err.println("Unable to obtain local IP address: using 127.0.0.1"); } try { emailText += messages.getString("client") + ": " + InetAddress.getLocalHost() + "\n%0A"; } catch (SecurityException e) { emailText += messages.getString("client") + ": " + "127.0.0.1" + "\n%0A"; } ctl.close(); ctlSocket.close(); try { testResults(tmpstr); } catch (Exception ex) { results.append(messages.getString("resultsParseError") + "\n"); results.append(ex + "\n"); } if ((tests & TEST_MID) == TEST_MID) { middleboxResults(tmpstr2); } pub_isReady = "yes"; pub_errmsg = "All tests completed OK."; pub_status = "done"; }
From source file:com.mirth.connect.plugins.dashboardstatus.DashboardConnectorStatusMonitor.java
public void updateStatus(String connectorId, ConnectorType type, Event event, Socket socket) { String stateImage = COLOR_BLACK; String stateText = STATE_UNKNOWN; boolean updateStatus = true; switch (event) { case INITIALIZED: switch (type) { case LISTENER: stateImage = COLOR_YELLOW;/*from w w w . j a v a 2 s . c o m*/ stateText = STATE_WAITING; break; case READER: stateImage = COLOR_YELLOW; stateText = STATE_IDLE; break; } break; case CONNECTED: switch (type) { case LISTENER: if (socket != null) { addConnectionToSocketSet(socket, connectorId); stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")"; } else { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED; } break; case READER: stateImage = COLOR_GREEN; stateText = STATE_POLLING; break; } break; case DISCONNECTED: switch (type) { case LISTENER: if (socket != null) { removeConnectionInSocketSet(socket, connectorId); int connectedSockets = getSocketSetCount(connectorId); if (connectedSockets == 0) { stateImage = COLOR_YELLOW; stateText = STATE_WAITING; } else { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + connectedSockets + ")"; } } else { clearSocketSet(connectorId); stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; } break; case READER: stateImage = COLOR_RED; stateText = STATE_NOT_POLLING; break; case WRITER: stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; break; case SENDER: stateImage = COLOR_RED; stateText = STATE_DISCONNECTED; break; } break; case BUSY: switch (type) { case READER: stateImage = COLOR_GREEN; stateText = STATE_READING; break; case LISTENER: stateImage = COLOR_GREEN; stateText = STATE_RECEIVING; break; case WRITER: stateImage = COLOR_YELLOW; stateText = STATE_WRITING; break; case SENDER: stateImage = COLOR_YELLOW; stateText = STATE_SENDING; break; } break; case DONE: switch (type) { case READER: stateImage = COLOR_YELLOW; stateText = STATE_IDLE; break; case LISTENER: if (socket != null) { stateImage = COLOR_GREEN; stateText = STATE_CONNECTED + " (" + getSocketSetCount(connectorId) + ")"; } else { stateImage = COLOR_YELLOW; stateText = STATE_WAITING; } break; } break; case ATTEMPTING: switch (type) { case WRITER: stateImage = COLOR_YELLOW; stateText = STATE_ATTEMPTING; break; case SENDER: stateImage = COLOR_YELLOW; stateText = STATE_ATTEMPTING; break; } break; default: updateStatus = false; break; } if (updateStatus) { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); String channelName = ""; // this will be overwritten down below. If not, something's wrong. String connectorType = type.toString(); String information = ""; /* * check 'connectorId' - contains destination_1_connector, etc. * connectorId consists of id_source_connector for sources, and * id_destination_x_connector for destinations. i.e. tokenCount will * be 3 for sources and 4 for destinations. Note that READER and * LISTENER are sources, and WRITER and SENDER are destinations. */ StringTokenizer tokenizer = new StringTokenizer(connectorId, "_"); String channelId = tokenizer.nextToken(); int destinationIndex; LinkedList<String[]> channelLog = null; Channel channel = ControllerFactory.getFactory().createChannelController() .getDeployedChannelById(channelId); if (channel != null) { channelName = channel.getName(); // grab the channel's log from the HashMap, if not exist, create // one. if (connectorInfoLogs.containsKey(channelName)) { channelLog = connectorInfoLogs.get(channelName); } else { channelLog = new LinkedList<String[]>(); } Connector connector = null; switch (type) { case READER: connectorType = "Source: " + channel.getSourceConnector().getTransportName() + " (" + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> " + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")"; break; case LISTENER: connectorType = "Source: " + channel.getSourceConnector().getTransportName() + " (" + channel.getSourceConnector().getTransformer().getInboundProtocol().toString() + " -> " + channel.getSourceConnector().getTransformer().getOutboundProtocol().toString() + ")"; break; case WRITER: tokenizer.nextToken(); // destinationId begins from 1, so subtract by 1 for the // arrayIndex. destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1; connector = channel.getDestinationConnectors().get(destinationIndex); connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName(); if (connector.getTransportName().equals(FileWriterProperties.name)) { // Destination - File Writer. switch (event) { case BUSY: information = FileWriterProperties.getInformation(connector.getProperties()); break; } } else if (connector.getTransportName().equals(DatabaseWriterProperties.name)) { // Destination - Database Writer. information = DatabaseWriterProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(JMSWriterProperties.name)) { // Destination - JMS Writer. information = JMSWriterProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(DocumentWriterProperties.name)) { // Destination - Document Writer. information = DocumentWriterProperties.getInformation(connector.getProperties()); } break; case SENDER: tokenizer.nextToken(); // destinationId begins from 1, so subtract by 1 for the // arrayIndex. destinationIndex = Integer.valueOf(tokenizer.nextToken()) - 1; connector = channel.getDestinationConnectors().get(destinationIndex); connectorType = "Destination: " + connector.getTransportName() + " - " + connector.getName(); if (connector.getTransportName().equals(HttpSenderProperties.name)) { // Destination - HTTP Sender. information = HttpSenderProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(ChannelWriterProperties.name)) { // Destination - Channel Writer. Channel targetChannel = ControllerFactory.getFactory().createChannelController() .getDeployedChannelById( ChannelWriterProperties.getInformation(connector.getProperties())); if (targetChannel == null) { information = "Target Channel: None"; } else { information = "Target Channel: " + targetChannel.getName(); } } else if (connector.getTransportName().equals(SmtpSenderProperties.name)) { // Destination - SMTP Sender. information = SmtpSenderProperties.getInformation(connector.getProperties()); } else if (connector.getTransportName().equals(TCPSenderProperties.name)) { // Destination - TCP Sender. // The useful info for TCP Sender - host:port will // be taken care of by the socket below. } else if (connector.getTransportName().equals(LLPSenderProperties.name)) { // Destination - LLP Sender. // The useful info for LLP Sender - host:port will // be taken care of by the socket below. } else if (connector.getTransportName().equals(WebServiceSenderProperties.name)) { // Destination - Web Service Sender. // information = ""; } break; } } if (socket != null) { String sendingAddress = socket.getLocalAddress().toString() + ":" + socket.getLocalPort(); String receivingAddress = socket.getInetAddress().toString() + ":" + socket.getPort(); // If addresses begin with a slash "/", remove it. if (sendingAddress.startsWith("/")) { sendingAddress = sendingAddress.substring(1); } if (receivingAddress.startsWith("/")) { receivingAddress = receivingAddress.substring(1); } information += "Sender: " + sendingAddress + " Receiver: " + receivingAddress; } if (channelLog != null) { synchronized (this) { if (channelLog.size() == MAX_LOG_SIZE) { channelLog.removeLast(); } channelLog.addFirst(new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp), connectorType, event.toString(), information }); if (entireConnectorInfoLogs.size() == MAX_LOG_SIZE) { entireConnectorInfoLogs.removeLast(); } entireConnectorInfoLogs.addFirst(new String[] { String.valueOf(logId), channelName, dateFormat.format(timestamp), connectorType, event.toString(), information }); logId++; // put the channel log into the HashMap. connectorInfoLogs.put(channelName, channelLog); } } connectorStateMap.put(connectorId, new String[] { stateImage, stateText }); } }