List of usage examples for java.net InetAddress toString
public String toString()
From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java
@Override public OvsdbClient connectWithSsl(final InetAddress address, final int port, final SSLContext sslContext) { try {/*from w w w .ja va2s . c o m*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(65535, 65535, 65535)); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { if (sslContext != null) { /* First add ssl handler if ssl context is given */ SSLEngine engine = sslContext.createSSLEngine(address.toString(), port); engine.setUseClientMode(true); channel.pipeline().addLast("ssl", new SslHandler(engine)); } channel.pipeline().addLast( //new LoggingHandler(LogLevel.INFO), new JsonRpcDecoder(100000), new StringEncoder(CharsetUtil.UTF_8), new ExceptionHandler()); } }); ChannelFuture future = bootstrap.connect(address, port).sync(); Channel channel = future.channel(); OvsdbClient client = getChannelClient(channel, ConnectionType.ACTIVE, Executors.newFixedThreadPool(NUM_THREADS)); return client; } catch (InterruptedException e) { System.out.println("Thread was interrupted during connect"); } return null; }
From source file:org.apache.catalina.startup.Embedded.java
/** * Create, configure, and return a new TCP/IP socket connector * based on the specified properties./*from w w w . ja va2s . c om*/ * * @param address InetAddress to bind to, or <code>null</code> if the * connector is supposed to bind to all addresses on this server * @param port Port number to listen to * @param secure true if the generated connector is supposed to be * SSL-enabled, and false otherwise */ public Connector createConnector(InetAddress address, int port, boolean secure) { return createConnector(address != null ? address.toString() : null, port, secure); }
From source file:org.apache.catalina.startup.Embedded.java
public Connector createConnector(InetAddress address, int port, String protocol) { return createConnector(address != null ? address.toString() : null, port, protocol); }
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * Parses the result and fills the SampleResult with its info * @param httpRequest the executed request * @param localContext the Http context which was used * @param res the SampleResult which is to be filled * @param httpResponse the response which is to be parsed * @throws IllegalStateException/*from w w w .j ava 2 s . c om*/ * @throws IOException */ private void parseResponse(HttpRequestBase httpRequest, HttpContext localContext, HTTPSampleResult res, HttpResponse httpResponse) throws IllegalStateException, IOException { // Needs to be done after execute to pick up all the headers final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = (InetAddress) httpRequest.getParams() .getParameter(ConnRoutePNames.LOCAL_ADDRESS); if (localAddr != null) { request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } res.setRequestHeaders(getConnectionHeaders(request)); Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (contentType != null) { String ct = contentType.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); res.setResponseData(readResponse(res, instream, (int) entity.getContentLength())); } res.sampleEnd(); // Done with the sampling proper. currentRequest = null; // Now collect the results into the HTTPSampleResult: StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); res.setResponseCode(Integer.toString(statusCode)); res.setResponseMessage(statusLine.getReasonPhrase()); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseHeaders(getResponseHeaders(httpResponse)); if (res.isRedirect()) { final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException( "Missing location header in redirect for " + httpRequest.getRequestLine()); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); } // record some sizes to allow HTTPSampleResult.getBytes() with different options HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS); long headerBytes = res.getResponseHeaders().length() // condensed length (without \r) + httpResponse.getAllHeaders().length // Add \r for each header + 1 // Add \r for initial header + 2; // final \r\n before data long totalBytes = metrics.getReceivedBytesCount(); res.setHeadersSize((int) headerBytes); res.setBodySize((int) (totalBytes - headerBytes)); if (log.isDebugEnabled()) { log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); URI redirectURI = req.getURI(); if (redirectURI.isAbsolute()) { res.setURL(redirectURI.toURL()); } else { res.setURL(new URL(new URL(target.toURI()), redirectURI.toString())); } } }
From source file:org.starnub.starnubserver.connections.player.session.PlayerSession.java
public PlayerSession(Connection connection, String playerName, UUID playerUUID) { if (connection instanceof StarNubProxyConnection) { CONNECTION_TYPE = ConnectionType.PROXY_IN_GAME; } else if (connection instanceof StarNubConnection) { CONNECTION_TYPE = ConnectionType.REMOTE; } else {//from w w w. jav a2 s. com CONNECTION_TYPE = null; } CONNECTION = connection; InetAddress playerIP = connection.getClientIP(); StarNub.getConnections().getINTERNAL_IP_WATCHLIST().removeCache(playerIP); this.startTimeUtc = DateTime.now(); this.sessionIpString = StringUtils.remove(playerIP.toString(), "/"); this.playerCharacter = PlayerCharacter.getPlayerCharacter(playerName, playerUUID); this.gameName = playerCharacter.getName(); this.nickName = playerCharacter.getName(); this.cleanNickName = playerCharacter.getCleanName(); CharacterIP characterIP = new CharacterIP(playerCharacter, playerIP, false); characterIP.logCharacterIp(); this.idleTime = 0L; try { this.op = StarNub.getConnections().getCONNECTED_PLAYERS().getOPERATORS().collectionContains("uuids"); } catch (Exception e) { this.op = false; } loadPermissions(); PlayerSessionLog.getInstance().create(this); new StarNubEvent("Player_New_Session", playerCharacter); }
From source file:fr.cmoatoto.multishare.receiver.NanoHTTPDReceiver.java
/** * Override this to customize the server. * <p>// ww w. j a v a 2 s. co m * * (By default, this delegates to serveFile() and allows directory listing.) * * @param uri * Percent-decoded URI without parameters, for example "/index.cgi" * @param method * "GET", "POST" etc. * @param parms * Parsed, percent decoded parameters from URI and, in case of POST, data. * @param header * Header entries, percent decoded * @param inetAddress * @return HTTP response, see class Response for details */ public Response serve(String uri, String method, Properties header, Properties parms, Properties files, InetAddress inetAddress) { myOut.println(method + " '" + uri + "' " + inetAddress.toString()); Enumeration e = header.propertyNames(); String element = null; myOut.println("URI: " + uri); String value = null; String mimeType = null; String extension = null; while (e.hasMoreElements()) { element = (String) e.nextElement(); myOut.println(" HDR: '" + element + "' = '" + header.getProperty(element) + "'"); } e = parms.propertyNames(); while (e.hasMoreElements()) { element = (String) e.nextElement(); myOut.println(" PRM: '" + element + "' = '" + parms.getProperty(element) + "'"); if (element.equals("value")) { value = parms.getProperty(element); if (value.contains("http://remote_host:")) { value = value.replace("/remote_host", inetAddress.toString()); myOut.println(" PRM REPLACED BY: '" + element + "' = '" + value + "'"); } } else if (element.equals("mime")) { mimeType = parms.getProperty(element); } else if (element.equals("extension")) { extension = parms.getProperty(element); } if (value != null && mimeType != null) { if ("keyboard/key".equals(mimeType)) { try { RemotedKeyboard.sendKeyEvent(mContext, Integer.parseInt(value)); } catch (NumberFormatException e2) { myOut.println(Log.getStackTraceString(e2)); } } else { HttpServiceReceiver.show(mContext, value, mimeType, extension); } } } e = files.propertyNames(); while (e.hasMoreElements()) { element = (String) e.nextElement(); myOut.println(" UPLOADED: '" + value + "' = '" + files.getProperty(value) + "'"); } final StringBuilder buf = new StringBuilder(); for (Entry<Object, Object> kv : header.entrySet()) buf.append(kv.getKey() + " : " + kv.getValue() + "\n"); return new NanoHTTPDReceiver.Response(HTTP_OK, mimeType, uri); }
From source file:com.cloud.api.ApiServer.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override/* ww w .j av a 2s . com*/ public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { // get some information for the access log... StringBuffer sb = new StringBuffer(); HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection"); if (connObj instanceof SocketHttpServerConnection) { InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress(); sb.append(remoteAddr.toString() + " -- "); } sb.append(request.getRequestLine()); try { String uri = request.getRequestLine().getUri(); int requestParamsStartIndex = uri.indexOf('?'); if (requestParamsStartIndex >= 0) { uri = uri.substring(requestParamsStartIndex + 1); } String[] paramArray = uri.split("&"); if (paramArray.length < 1) { s_logger.info("no parameters received for request: " + uri + ", aborting..."); return; } Map parameterMap = new HashMap<String, String[]>(); String responseType = BaseCmd.RESPONSE_TYPE_XML; for (String paramEntry : paramArray) { String[] paramValue = paramEntry.split("="); if (paramValue.length != 2) { s_logger.info("malformed parameter: " + paramEntry + ", skipping"); continue; } if ("response".equalsIgnoreCase(paramValue[0])) { responseType = paramValue[1]; } else { // according to the servlet spec, the parameter map should be in the form (name=String, // value=String[]), so // parameter values will be stored in an array parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); } } try { // always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true); sb.insert(0, "(userId=" + User.UID_SYSTEM + " accountId=" + Account.ACCOUNT_ID_SYSTEM + " sessionId=" + null + ") "); String responseText = handleRequest(parameterMap, true, responseType, sb); sb.append(" 200 " + ((responseText == null) ? 0 : responseText.length())); writeResponse(response, responseText, HttpStatus.SC_OK, responseType, null); } catch (ServerApiException se) { String responseText = getSerializedApiError(se.getErrorCode(), se.getDescription(), parameterMap, responseType, se); writeResponse(response, responseText, se.getErrorCode(), responseType, se.getDescription()); sb.append(" " + se.getErrorCode() + " " + se.getDescription()); } catch (RuntimeException e) { // log runtime exception like NullPointerException to help identify the source easier s_logger.error("Unhandled exception, ", e); throw e; } } finally { s_accessLogger.info(sb.toString()); UserContext.unregisterContext(); } }
From source file:ui.FtpDialog.java
private void loginBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginBtActionPerformed String host = hostAddressField.getText(); int port = (int) portNumberSp.getValue(); String user = userNameField.getText(); char[] password = passField.getPassword(); String pass = new String(password); String hostIP = null;//w ww. java2s . c o m Trace.connectionFtp = true; InetAddress address = null; if (!connected) { try { address = InetAddress.getByName(host); ; hostIP = StringUtils.substringAfter(address.toString(), "/"); if (hostIP == null || hostIP.equals("127.0.0.1")) { JOptionPane.showMessageDialog(rootFrame, "Host name not set", "Error", JOptionPane.ERROR_MESSAGE); return; } if (port == 0) { JOptionPane.showMessageDialog(rootFrame, "Invalid port number", "Error", JOptionPane.ERROR_MESSAGE); } if (Trace.connectionFtp) { Trace.trc("Host IP address: " + hostIP); } } catch (UnknownHostException e) { JOptionPane.showMessageDialog(rootFrame, "Cannot resolve host address", "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } try { if (address != null && port != 0 && user != null && pass != null) { connected = ftpHandler.doConnect(hostIP, port, user, pass); Arrays.fill(password, '0'); if (!connected) { JOptionPane.showMessageDialog(rootFrame, "Problem iniating connection to the FTP server, please check your login credentials", "Error", JOptionPane.ERROR_MESSAGE); return; } } } catch (IOException e) { e.printStackTrace(); } if (connected) { try { if (Trace.connectionFtp) { Trace.trc("Attempting to list the remote directory..."); } String dirList = ftpHandler.list(); lastKnownDir = ftpHandler.pwd(); outputTextArea.setText(dirList); remoteSiteText.setText(ftpHandler.pwd()); } catch (IOException e) { e.printStackTrace(); } } } else { JOptionPane.showMessageDialog(rootFrame, "Already connected to a FTP server, cannot reconnect!", "Error", JOptionPane.ERROR_MESSAGE); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//from w w w.j ava 2 s. co m * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HttpMethodBase httpMethod = null; HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time try { // May generate IllegalArgumentException if (method.equals(HTTPConstants.POST)) { httpMethod = new PostMethod(urlStr); } else if (method.equals(HTTPConstants.GET)) { httpMethod = new GetMethod(urlStr); } else if (method.equals(HTTPConstants.PUT)) { httpMethod = new PutMethod(urlStr); } else if (method.equals(HTTPConstants.HEAD)) { httpMethod = new HeadMethod(urlStr); } else if (method.equals(HTTPConstants.TRACE)) { httpMethod = new TraceMethod(urlStr); } else if (method.equals(HTTPConstants.OPTIONS)) { httpMethod = new OptionsMethod(urlStr); } else if (method.equals(HTTPConstants.DELETE)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.DELETE; } }; } else if (method.equals(HTTPConstants.PATCH)) { httpMethod = new EntityEnclosingMethod(urlStr) { @Override public String getName() { // HC3.1 does not have the method return HTTPConstants.PATCH; } }; } else { throw new IllegalArgumentException("Unexpected method: '" + method + "'"); } final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection HttpClient client = setupConnection(url, httpMethod, res); savedClient = client; // Handle the various methods if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData((PostMethod) httpMethod); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT) || method.equals(HTTPConstants.PATCH) || method.equals(HTTPConstants.DELETE)) { String putBody = sendEntityData((EntityEnclosingMethod) httpMethod); res.setQueryString(putBody); } int statusCode = client.executeMethod(httpMethod); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = client.getHostConfiguration().getLocalAddress(); if (localAddr != null) { httpMethod.addRequestHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: InputStream instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD instream = new CountingInputStream(instream); try { Header responseHeader = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (responseHeader != null && HTTPConstants.ENCODING_GZIP.equals(responseHeader.getValue())) { InputStream tmpInput = new GZIPInputStream(instream); // tmp inputstream needs to have a good counting res.setResponseData( readResponse(res, tmpInput, (int) httpMethod.getResponseContentLength())); } else { res.setResponseData( readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } } finally { JOrphanUtils.closeQuietly(instream); } } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; Header h = httpMethod.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); if (res.isRedirect()) { final Header headerLocation = httpMethod.getResponseHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException("Missing location header"); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); // in case sanitising fails } // record some sizes to allow HTTPSampleResult.getBytes() with different options if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); } res.setHeadersSize(calculateHeadersSize(httpMethod)); if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(new URL(httpMethod.getURI().toString())); } // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } // Follow redirects and download page resources if appropriate: res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IllegalArgumentException e) { // e.g. some kinds of invalid URL res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod can be null if method is unexpected if (httpMethod != null) { res.setRequestHeaders(getConnectionHeaders(httpMethod)); } errorResult(e, res); return res; } catch (IOException e) { res.sampleEnd(); // pick up headers if failed to execute the request // httpMethod cannot be null here, otherwise // it would have been caught in the previous catch block res.setRequestHeaders(getConnectionHeaders(httpMethod)); errorResult(e, res); return res; } finally { savedClient = null; if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:at.alladin.rmbt.controlServer.LogResource.java
@Post("json") public String request(final String entity) { addAllowOrigin();/*from w ww . j a va2 s. co m*/ JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); final InetAddress clientAddress = InetAddresses.forString(clientIpRaw); System.out.println(MessageFormat.format(labels.getString("NEW_LOG_REQ"), clientIpRaw)); if (entity != null && !entity.isEmpty()) { try { request = new JSONObject(entity); UUID uuid = null; final String uuidString = request.optString("uuid", ""); if (uuidString.length() != 0) { uuid = UUID.fromString(uuidString); } final Platform platform = Platform.valueOf(request.getString("plattform").toUpperCase(Locale.US)); final String logFileName = request.getString("logfile"); final File logPath = new File(LOG_PATH, platform.name().toLowerCase(Locale.US)); final File logFile = new File(logPath, logFileName); final boolean appendClientInfo = !logFile.exists(); try (PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter(logFile, logFile.exists())))) { final String content = request.getString("content"); request.remove("content"); if (appendClientInfo) { out.println("client IP: " + clientAddress.toString()); out.println("\n#############################################\n"); out.println(request.toString(3)); out.println("\n#############################################\n"); } out.println(content); } final JSONObject fileTimes = request.optJSONObject("file_times"); if (fileTimes != null) { try { final Long created = fileTimes.getLong("created"); final Long lastAccess = fileTimes.getLong("last_access"); final Long lastModified = fileTimes.getLong("last_modified"); BasicFileAttributeView attributes = Files.getFileAttributeView( Paths.get(logFile.getAbsolutePath()), BasicFileAttributeView.class); FileTime lastModifiedTime = FileTime .fromMillis(TimeUnit.MILLISECONDS.convert(lastModified, TimeUnit.SECONDS)); FileTime lastAccessTime = FileTime .fromMillis(TimeUnit.MILLISECONDS.convert(lastAccess, TimeUnit.SECONDS)); FileTime createdTime = FileTime .fromMillis(TimeUnit.MILLISECONDS.convert(created, TimeUnit.SECONDS)); attributes.setTimes(lastModifiedTime, lastAccessTime, createdTime); } catch (Exception e) { } // final Long lastModified = fileTimes.getLong("last_modified"); // logFile.setLastModified(TimeUnit.MILLISECONDS.convert(lastModified, TimeUnit.SECONDS)); } answer.put("status", "OK"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSON Data " + e.toString()); } catch (final Exception e) { errorList.addError("ERROR_LOG_WRITE"); System.out.println("Error writing Log " + e.toString()); } } else { errorList.addErrorString("Expected request is missing."); } try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); return answerString; }