List of usage examples for java.net InetAddress getLocalHost
public static InetAddress getLocalHost() throws UnknownHostException
From source file:com.facebook.tsdb.tsdash.server.TsdbServlet.java
protected String generatePlotURL(String filenamePath) throws UnknownHostException { File plot = new File(filenamePath); if (hostname == null) { hostname = InetAddress.getLocalHost().getHostName(); }/* ww w . j a v a2 s .co m*/ String URL = URLPattern.replace("%h", hostname); URL = URL.replace("%p", "" + DEFAULT_PLOT_PORT); URL = URL.replace("%f", plot.getName()); return URL; }
From source file:org.carewebframework.ui.util.RequestUtil.java
/** * Return local host IP. Note: HttpServletRequest#getLocalAddr() doesn't seem to be consistent. * This method uses java.net.InetAddress. * // ww w . j a v a 2 s.co m * @see InetAddress#getHostAddress() * @return server IP */ public static String getLocalHostAddress() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (final Exception e) { log.debug("Exception occurred obtaining localhost IP address", e); return null; } }
From source file:SampleKinesisApplication.java
private static void configure(String propertiesFile) throws IOException { if (propertiesFile != null) { loadProperties(propertiesFile);//from www. j a v a 2 s .c o m } // ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints). java.security.Security.setProperty("networkaddress.cache.ttl", "60"); String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID(); LOG.info("Using workerId: " + workerId); // Get credentials from IMDS. If unsuccessful, get them from the credential profiles file. AWSCredentialsProvider credentialsProvider = null; try { credentialsProvider = new InstanceProfileCredentialsProvider(); // Verify we can fetch credentials from the provider credentialsProvider.getCredentials(); LOG.info("Obtained credentials from the IMDS."); } catch (AmazonClientException e) { LOG.info("Unable to obtain credentials from the IMDS, trying classpath properties", e); credentialsProvider = new ProfileCredentialsProvider(); // Verify we can fetch credentials from the provider credentialsProvider.getCredentials(); LOG.info("Obtained credentials from the properties file."); } LOG.info("Using credentials with access key id: " + credentialsProvider.getCredentials().getAWSAccessKeyId()); kinesisClientLibConfiguration = new KinesisClientLibConfiguration(applicationName, streamName, credentialsProvider, workerId).withInitialPositionInStream(initialPositionInStream); }
From source file:at.treedb.backup.DBexportInfo.java
/** * Creates a {@code DBexportInfo} object. * //from w ww .ja va 2 s . c om * @param backupType * type of backup, e.g FULL * @param serialization * type of object serialization * @param compressionMethod * compression method * @throws Exception */ public DBexportInfo(BACKUP_TYPE backupType, Domain d, Serialization serialization, SevenZMethod compressionMethod) throws Exception { this.backupType = backupType; this.compressionMethod = compressionMethod; this.serialization = serialization; dbSchemaVersion = DBinfo.DB_SCHEMA_VERSION; // export the domain descriptions (different languages) if (d != null && d.getDescription() != 0) { domainDescription = new ArrayList<IstringDummy>(); for (Istring i : Istring.loadAllStrings(d.getDescription())) { domainDescription.add(new IstringDummy(i)); } } DAOiface dao = DAO.getDAO(); persistenceLayer = dao.getPersistenceLayer(); if (dao.getJPAimpl() != null) { jpaImplemantation = dao.getJPAimpl(); } if (DAO.getDAO().getDB() != null) { database = DAO.getDAO().getDB(); } hostName = InetAddress.getLocalHost().getHostName(); operatingSystem = System.getProperty("os.name"); entityCount = new ArrayList<String>(); }
From source file:com.sshtools.j2ssh.authentication.HostbasedAuthenticationClient.java
/** * * * @param authentication/*from www .j ava2 s .c o m*/ * @param serviceToStart * * @throws IOException * @throws TerminatedStateException * @throws AuthenticationProtocolException */ public void authenticate(AuthenticationProtocolClient authentication, String serviceToStart) throws IOException, TerminatedStateException { if ((getUsername() == null) || (key == null)) { throw new AuthenticationProtocolException("You must supply a username and a key"); } ByteArrayWriter baw = new ByteArrayWriter(); log.info("Generating data to sign"); SshPublicKey pub = key.getPublicKey(); InetAddress addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); log.info("Preparing hostbased authentication request for " + hostname); // Now prepare and send the message baw.writeString(pub.getAlgorithmName()); baw.writeBinaryString(pub.getEncoded()); baw.writeString(hostname); if (clientUser != null) { baw.writeString(clientUser); } else { baw.writeString(getUsername()); } // Create the signature data ByteArrayWriter data = new ByteArrayWriter(); data.writeBinaryString(authentication.getSessionIdentifier()); data.write(SshMsgUserAuthRequest.SSH_MSG_USERAUTH_REQUEST); data.writeString(getUsername()); data.writeString(serviceToStart); data.writeString(getMethodName()); data.writeString(pub.getAlgorithmName()); data.writeBinaryString(pub.getEncoded()); data.writeString(hostname); if (clientUser != null) { data.writeString(clientUser); } else { data.writeString(getUsername()); } // Generate the signature baw.writeBinaryString(key.generateSignature(data.toByteArray())); SshMsgUserAuthRequest msg = new SshMsgUserAuthRequest(getUsername(), serviceToStart, getMethodName(), baw.toByteArray()); authentication.sendMessage(msg); }
From source file:org.appverse.web.framework.backend.batch.services.business.impl.live.JobRunnerServiceImpl.java
@Override public boolean performNodeDelay(long nodeDelay) throws Exception { String host = InetAddress.getLocalHost().getCanonicalHostName(); IntegrationDataFilter filter = new IntegrationDataFilter(); filter.addStrictCondition("name", host); BatchNodeDTO batchNodeDTO = batchNodeRepository.retrieve(filter); if (batchNodeDTO == null) { batchNodeDTO = new BatchNodeDTO(); batchNodeDTO.setName(host);//from w ww .j a va 2 s . com batchNodeDTO.setActive("n"); batchNodeRepository.persist(batchNodeDTO); } long order = batchNodeDTO.getId(); long delay = (order - 1) * nodeDelay * 1000; if (batchNodeDTO.getActive().equalsIgnoreCase("y")) { logger.info("Batch waitting " + (order - 1) * nodeDelay + " seconds"); Thread.sleep(delay); return true; } else { logger.info("Batch run skipped"); return false; } }
From source file:org.usergrid.benchmark.commands.EventServiceTestBase.java
@Override public void runTool(CommandLine line) throws Exception { // set the hazelcast cluster property BEFORE starting spring System.setProperty("HZ_MEMBERS", line.getOptionValue("hazelcast")); startSpring();//from www. j a v a 2 s .co m int workers = Integer.parseInt(line.getOptionValue("workers")); String hostName = InetAddress.getLocalHost().getHostName(); int count = Integer.parseInt(line.getOptionValue("count")); logger.info("Starting workers"); doWork(line, hostName, workers, count); //wait until the user pressed CTRL +C if (line.hasOption("wait")) { new Semaphore(0).acquire(); } }
From source file:com.surfs.storage.common.util.CmdUtils.java
public static String getLocalhostIp() { try {/*from w w w . j av a2 s . co m*/ InetAddress inet = InetAddress.getLocalHost(); return inet.getHostAddress(); } catch (UnknownHostException e) { throw new NullPointerException("local ip is empty"); } }
From source file:com.esri.geoportal.commons.ags.client.AgsClient.java
/** * Generates token.// w w w . j a va 2 s.co m * * @param minutes expiration in minutes. * @param credentials credentials. * @return token response * @throws URISyntaxException if invalid URL * @throws IOException if accessing token fails */ public TokenResponse generateToken(int minutes, SimpleCredentials credentials) throws URISyntaxException, IOException { HttpPost post = new HttpPost(rootUrl.toURI().resolve("tokens/generateToken")); HashMap<String, String> params = new HashMap<>(); params.put("f", "json"); if (credentials != null) { params.put("username", StringUtils.trimToEmpty(credentials.getUserName())); params.put("password", StringUtils.trimToEmpty(credentials.getPassword())); } params.put("client", "ip"); params.put("ip", InetAddress.getLocalHost().getHostAddress()); params.put("expiration", Integer.toString(minutes)); HttpEntity entity = new UrlEncodedFormEntity(params.entrySet().stream() .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList())); post.setEntity(entity); try (CloseableHttpResponse httpResponse = httpClient.execute(post); InputStream contentStream = httpResponse.getEntity().getContent();) { if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } String responseContent = IOUtils.toString(contentStream, "UTF-8"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.readValue(responseContent, TokenResponse.class); } }
From source file:com.amazonaws.kinesis.dataviz.kinesisclient.KinesisApplication.java
private static void configure(String propertiesFile) throws IOException { if (propertiesFile != null) { loadProperties(propertiesFile);// w w w. j a v a 2s .c o m } // ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints). java.security.Security.setProperty("networkaddress.cache.ttl", "60"); String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID(); LOG.info("Using workerId: " + workerId); // Get credentials from IMDS. If unsuccessful, get them from the credential profiles file. AWSCredentialsProvider credentialsProvider = null; try { credentialsProvider = new InstanceProfileCredentialsProvider(); // Verify we can fetch credentials from the provider credentialsProvider.getCredentials(); LOG.info("Obtained credentials from the IMDS."); } catch (AmazonClientException e) { LOG.info("Unable to obtain credentials from the IMDS, trying classpath properties", e); credentialsProvider = new ProfileCredentialsProvider(); // Verify we can fetch credentials from the provider credentialsProvider.getCredentials(); LOG.info("Obtained credentials from the properties file."); } LOG.info("Using credentials with access key id: " + credentialsProvider.getCredentials().getAWSAccessKeyId()); kinesisClientLibConfiguration = new KinesisClientLibConfiguration(applicationName, streamName, credentialsProvider, workerId).withInitialPositionInStream(initialPositionInStream) .withRegionName(kinesisEndpoint); }