List of usage examples for java.net InetAddress getHostName
public String getHostName()
From source file:org.apache.openjpa.event.TCPRemoteCommitProvider.java
/** * Sets the list of addresses of peers to which this provider will * send events to. The peers are semicolon-separated <code>names</code> * list in the form of "myhost1:portA;myhost2:portB". *//*from ww w. j a va2 s. c o m*/ public void setAddresses(String names) throws UnknownHostException { // NYI. Could look for equivalence of addresses and avoid // changing those that didn't change. _addressesLock.lock(); try { for (Iterator iter = _addresses.iterator(); iter.hasNext();) { ((HostAddress) iter.next()).close(); } String[] toks = Strings.split(names, ";", 0); _addresses = new ArrayList(toks.length); InetAddress localhost = InetAddress.getLocalHost(); String localhostName = localhost.getHostName(); for (int i = 0; i < toks.length; i++) { String host = toks[i]; String hostname; int tmpPort; int colon = host.indexOf(':'); if (colon != -1) { hostname = host.substring(0, colon); tmpPort = Integer.parseInt(host.substring(colon + 1)); } else { hostname = host; tmpPort = DEFAULT_PORT; } InetAddress tmpAddress = AccessController.doPrivileged(J2DoPrivHelper.getByNameAction(hostname)); // bleair: For each address we would rather make use of // the jdk1.4 isLinkLocalAddress () || isLoopbackAddress (). // (Though in practice on win32 they don't work anyways!) // Instead we will check hostname. Not perfect, but // it will match often enough (people will typically // use the DNS machine names and be cutting/pasting.) if (localhostName.equals(hostname)) { // This string matches the hostname for for ourselves, we // don't actually need to send ourselves messages. if (log.isTraceEnabled()) { log.trace(s_loc.get("tcp-address-asself", tmpAddress.getHostName() + ":" + tmpPort)); } } else { HostAddress newAddress = new HostAddress(host); _addresses.add(newAddress); if (log.isTraceEnabled()) { log.trace(s_loc.get("tcp-address-set", newAddress._address.getHostName() + ":" + newAddress._port)); } } } } catch (PrivilegedActionException pae) { throw (UnknownHostException) pae.getException(); } finally { _addressesLock.unlock(); } }
From source file:org.apache.hadoop.hdfs.server.common.StorageClover.java
protected void fillLocalNode() { PoolFile pf = new PoolFile(); String name = ""; ///hostname:portNumber String hostname = ""; int rpcport = 9000; //default int socketport = 9001; //default int colon;/*from ww w . j a v a2s. c om*/ //get local socket addr, name try { InetAddress ia = InetAddress.getLocalHost(); hostname = ia.getHostName(); LOG.info("localhost name: " + hostname); } catch (UnknownHostException e) { LOG.error("can't get local hostname"); } name = conf.get("dfs.poolnode.address", "0.0.0.0:60011"); colon = name.indexOf(":"); if (colon > 0) { socketport = Integer.parseInt(name.substring(colon + 1)); } name = conf.get("dfs.poolnode.ipc.address", "0.0.0.0:60021"); colon = name.indexOf(":"); if (colon > 0) rpcport = Integer.parseInt(name.substring(colon + 1)); localnode = pf.new NameNodeInfo(hostname, rpcport, socketport); }
From source file:org.ejbca.core.ejb.services.ServiceSessionBean.java
/** * @return The host's name or null if it could not be determined. *//* w ww. j a va 2s. c om*/ private String getHostName() { String hostname = null; try { InetAddress addr = InetAddress.getLocalHost(); // Get hostname hostname = addr.getHostName(); } catch (UnknownHostException e) { log.error("Hostname could not be determined", e); } return hostname; }
From source file:org.fcrepo.server.access.DefaultAccess.java
private String getReposBaseURL(String protocol, String port) { String reposBaseURL = null;//ww w . j av a 2 s. c o m String fedoraServerHost = getServer().getParameter("fedoraServerHost"); if (fedoraServerHost == null || fedoraServerHost.isEmpty()) { logger.warn("Configuration parameter fedoraServerHost is empty."); try { InetAddress hostIP = InetAddress.getLocalHost(); fedoraServerHost = hostIP.getHostName(); } catch (UnknownHostException e) { logger.error("Unable to resolve host of Fedora server", e); fedoraServerHost = "localhost"; } } reposBaseURL = protocol + "://" + fedoraServerHost + ":" + port; return reposBaseURL; }
From source file:org.voltdb.client.Distributer.java
Distributer(int expectedOutgoingMessageSize, int arenaSizes[], boolean useMultipleThreads, StatsUploaderSettings statsSettings, int backpressureWait) { if (statsSettings != null) { m_statsLoader = new ClientStatsLoader(statsSettings, this); } else {//from w w w. ja va 2 s . c om m_statsLoader = null; } m_useMultipleThreads = useMultipleThreads; m_backpressureWait = backpressureWait; m_network = new VoltNetwork(useMultipleThreads, true, 3); m_expectedOutgoingMessageSize = expectedOutgoingMessageSize; m_network.start(); m_pool = new DBBPool(false, arenaSizes, false); String hostname = ""; try { java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost(); hostname = localMachine.getHostName(); } catch (java.net.UnknownHostException uhe) { } m_hostname = hostname; if (debug.get()) LOG.debug(String.format("Created new Distributer for %s [multiThread=%s, backpressureWait=%d]", m_hostname, m_useMultipleThreads, m_backpressureWait)); // new Thread() { // @Override // public void run() { // long lastBytesRead = 0; // long lastBytesWritten = 0; // long lastRuntime = System.currentTimeMillis(); // try { // while (true) { // Thread.sleep(10000); // final long now = System.currentTimeMillis(); // org.voltdb.utils.Pair<Long, Long> counters = m_network.getCounters(); // final long read = counters.getFirst(); // final long written = counters.getSecond(); // final long readDelta = read - lastBytesRead; // final long writeDelta = written - lastBytesWritten; // final long timeDelta = now - lastRuntime; // lastRuntime = now; // final double seconds = timeDelta / 1000.0; // final double megabytesRead = readDelta / (double)(1024 * 1024); // final double megabytesWritten = writeDelta / (double)(1024 * 1024); // final double readRate = megabytesRead / seconds; // final double writeRate = megabytesWritten / seconds; // lastBytesRead = read; // lastBytesWritten = written; // System.err.printf("Read rate %.2f Write rate %.2f\n", readRate, writeRate); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // }.start(); }
From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java
/** * @param outputRepository/*from w ww . j a va 2s . c o m*/ * @throws MojoFailureException * @throws MojoExecutionException */ private void createBuildInfo(File outputRepository, File buildinfoFolder) throws MojoFailureException, MojoExecutionException { ModelNode jsonProperties = new ModelNode(); jsonProperties.get("timestamp").set(System.currentTimeMillis()); // TODO get it from build metadata try { jsonProperties.get("revision").set(createRevisionObject()); } catch (FileNotFoundException ex) { getLog().error("Could not add revision to " + BUILDINFO_JSON + ": not a Git repository", ex); } catch (Exception ex) { throw new MojoFailureException("Could not add revision to " + BUILDINFO_JSON, ex); } // get hostname and load into HOSTNAME java.net.InetAddress localMachine; try { localMachine = java.net.InetAddress.getLocalHost(); System.setProperty("HOSTNAME", localMachine.getHostName()); } catch (UnknownHostException e) { e.printStackTrace(); } // if WORKSPACE is null, use current directory if (System.getProperty("WORKSPACE") == null || System.getProperty("WORKSPACE").equals("")) { System.setProperty("WORKSPACE", Paths.get("").toAbsolutePath().toString()); } ModelNode sysProps = new ModelNode(); for (String propertyName : this.systemProperties) { sysProps.get(propertyName).set(String.valueOf(System.getProperty(propertyName))); } jsonProperties.get("properties").set(sysProps); try { jsonProperties.get(UPSTREAM_ELEMENT).set(aggregateUpstreamMetadata(buildinfoFolder)); } catch (Exception ex) { throw new MojoExecutionException("Could not get upstream metadata", ex); } try { // put buildinfo.json inside the target/buildinfo/ folder FileUtils.fileWrite(new File(buildinfoFolder, BUILDINFO_JSON), jsonProperties.toJSONString(false)); // put a copy inside the target/repository/ folder (and site zip) FileUtils.fileWrite(new File(outputRepository, BUILDINFO_JSON), jsonProperties.toJSONString(false)); } catch (Exception ex) { throw new MojoFailureException("Could not generate properties file", ex); } }
From source file:org.sakaiproject.event.impl.UsageSessionServiceAdaptor.java
/** * @inheritDoc/* www. j ava 2 s . c om*/ */ public UsageSession startSession(String userId, String remoteAddress, String userAgent) { // do we have a current session? Session s = sessionManager().getCurrentSession(); if (s != null) { UsageSession session = (UsageSession) s.getAttribute(USAGE_SESSION_KEY); if (session != null) { // If we have a session for this user, simply reuse if (userId != null && userId.equals(session.getUserId())) { return session; } // if it is for another user, we will create a new session, log a warning, and unbound/close the existing one s.setAttribute(USAGE_SESSION_KEY, null); M_log.warn("startSession: replacing existing UsageSession: " + session.getId() + " user: " + session.getUserId() + " for new user: " + userId); } // resolve the hostname if required String hostName = null; if (serverConfigurationService().getBoolean("session.resolvehostname", false)) { try { InetAddress inet = InetAddress.getByName(remoteAddress); hostName = inet.getHostName(); } catch (UnknownHostException e) { M_log.debug("Cannot resolve host address " + remoteAddress); } } // create the usage session and bind it to the session session = new BaseUsageSession(this, idManager().createUuid(), serverConfigurationService().getServerIdInstance(), userId, remoteAddress, hostName, userAgent); // store if (m_storage.addSession(session)) { // set a CSRF token StringBuffer sb = new StringBuffer(); sb.append(System.currentTimeMillis()); sb.append(session.getId()); MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(sb.toString().getBytes("UTF-8")); String hashedSessionId = byteArray2Hex(digest); s.setAttribute(SAKAI_CSRF_SESSION_ATTRIBUTE, hashedSessionId); } catch (NoSuchAlgorithmException e) { M_log.error( "Failed to create a hashed session id for use as CSRF token because no SHA-256 support", e); } catch (UnsupportedEncodingException e) { M_log.error( "Failed to create a hashed session id for use as CSRF token because could not get UTF-8 bytes of session id", e); } // set as the current session s.setAttribute(USAGE_SESSION_KEY, session); return session; } } return null; }
From source file:org.ebayopensource.winder.quartz.QuartzSchedulerManager.java
private void init() { WinderConfiguration configuration = engine.getConfiguration(); DirectSchedulerFactory factory = DirectSchedulerFactory.getInstance(); int numThreads = configuration.getInt("winder.quartz.numThreads", 50); String quartzType = configuration.getString("winder.quartz.scheduler_type"); dataSourceName = configuration.getString("winder.quartz.datasource"); Scheduler scheduler = null;/*w w w .j a v a 2 s.com*/ boolean inMemoryScheduler = false; try { if ("IN_MEMORY_SCHEDULER".equals(quartzType) || (quartzType == null && dataSourceName == null)) { factory.createVolatileScheduler(numThreads); scheduler = factory.getScheduler(); inMemoryScheduler = true; if (log.isInfoEnabled()) { log.info("Scheduler manager starting IN_MEMORY_SCHEDULER"); } } else { ThreadPool threadPool = new SimpleThreadPool(numThreads, Thread.NORM_PRIORITY); threadPool.initialize(); String instanceId = (new SimpleInstanceIdGenerator()).generateInstanceId(); DBConnectionManager dbMgr = DBConnectionManager.getInstance(); int poolSize = configuration.getInt("winder.quartz.ds.pool_size", numThreads + 15); String jdbcUrl = dataSourceName; if ("ds".equals(dataSourceName)) { // String jdbcDriver = configuration.getString("winder.quartz.ds.driver"); jdbcUrl = configuration.getString("winder.quartz.ds.url"); String jdbcUser = configuration.getString("winder.quartz.ds.username"); String jdbcPassword = configuration.getString("winder.quartz.ds.password"); String validate = configuration.getString("winder.quartz.ds.validate_sql", "SELECT 1 /* ping */"); PoolingConnectionProvider pooling = new PoolingConnectionProvider(jdbcDriver, jdbcUrl, jdbcUser, jdbcPassword, poolSize, validate); dbMgr.addConnectionProvider(dataSourceName, pooling); } else { log.warn("Please make sure the data source:" + dataSourceName + " has already been initialized in somewhere else"); } boolean enableQuartz = configuration.getBoolean("winder.quartz.enable", true); if (enableQuartz) { String tablePrefix = configuration.getString("winder.quartz.ds.table_prefix", "WINDER_"); reformat(SELECT_JOBS_LIMIT, tablePrefix); reformat(SELECT_JOBS_LIMIT_BY_DATE_RANGE, tablePrefix); reformat(SELECT_JOBS_LIMIT_LIKE, tablePrefix); reformat(SELECT_JOBS_LIMIT_LIKE_BY_DATE_RANGE, tablePrefix); int checkInterval = configuration.getInt("winder.quartz.checkin_interval", 7500); String clusterName = engine.getClusterName(); JobStoreTX jdbcJobStore = new WinderJobStoreTx(); jdbcJobStore.setDataSource(dataSourceName); jdbcJobStore.setTablePrefix(tablePrefix); jdbcJobStore.setIsClustered(true); jdbcJobStore.setClusterCheckinInterval(checkInterval); String hostName; try { InetAddress inet = InetAddress.getLocalHost(); hostName = inet.getHostName(); } catch (UnknownHostException e) { hostName = "unknownHost"; } jdbcJobStore.setInstanceId(hostName); jdbcJobStore.setDriverDelegateClass("org.ebayopensource.winder.quartz.WinderJDBCDelegate"); jdbcJobStore.setThreadPoolSize(poolSize); // To fix the quartz misfire issue DefaultThreadExecutor executor = new DefaultThreadExecutor(); long idleWaitTime = configuration.getLong("winder.quartz.idle_wait_time", 30000L); long dbFailureRetryInterval = configuration.getLong("winder.quartz.db_failure_retry_interval", 10000L); long batchTimeWindow = configuration.getLong("winder.quartz.batch_time_window", 1000L); boolean enableQuartzPlugins = configuration.getBoolean("winder.quartz.plugins.enable", false); if (enableQuartzPlugins) { Map<String, SchedulerPlugin> schedulerPluginMap = new HashMap<String, SchedulerPlugin>(); schedulerPluginMap.put("LoggingTriggerHistoryPlugin", new LoggingTriggerHistoryPlugin()); schedulerPluginMap.put("LoggingJobHistoryPlugin", new LoggingJobHistoryPlugin()); factory.createScheduler(clusterName, instanceId, threadPool, executor, jdbcJobStore, schedulerPluginMap, null, 0, idleWaitTime, dbFailureRetryInterval, false, null, numThreads, batchTimeWindow); } else { factory.createScheduler(clusterName, instanceId, threadPool, executor, jdbcJobStore, null, null, 0, idleWaitTime, dbFailureRetryInterval, false, null, numThreads, batchTimeWindow); } scheduler = factory.getScheduler(clusterName); if (log.isInfoEnabled()) { log.info("Scheduler manager starting with:" + jdbcUrl); } } else { if (log.isInfoEnabled()) { log.info("Scheduler manager disabled!"); } } } this.quartzScheduler = scheduler; this.inMemoryScheduler = inMemoryScheduler; } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Failure initializing quartz", e); } throw new IllegalStateException("Unable to initialize quartz", e); } }
From source file:org.infoglue.cms.util.CmsPropertyHandler.java
public static String getServerName() { String serverName = "Unknown"; try {//ww w . ja v a2s .c om InetAddress localhost = InetAddress.getLocalHost(); serverName = localhost.getHostName(); } catch (Exception e) { } return serverName; }
From source file:edu.ku.brc.specify.toycode.RegPivot.java
/** * @param newTblName//w ww . j av a 2s .com * @param tblName * @param keyName */ private void process(final String newTblName, final String tblName, final String keyName, final String defSQL, final String fillSQL, final boolean isRegBuild) { String sql = String.format("SELECT DISTINCT Name FROM %s", tblName); String sql2 = "SELECT MAX(LENGTH(Value)) FROM " + tblName + " WHERE Name = '%s'"; int instCnt = 0; Statement stmt = null; try { stmt = connection.createStatement(); BasicSQLUtils.setDBConnection(connection); boolean doBuild = true; if (doBuild) { StringBuilder tblSQL = new StringBuilder(String .format("CREATE TABLE %s (`%s` INT(11) NOT NULL AUTO_INCREMENT, \n", newTblName, keyName)); Vector<String> dbFieldNames = new Vector<String>(); Vector<Integer> dbFieldTypes = new Vector<Integer>(); if (defSQL != null) { ResultSet rs = stmt.executeQuery(defSQL); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i > 1) tblSQL.append(",\n "); String name = rsmd.getColumnName(i); dbFieldNames.add(rsmd.getColumnName(i)); dbFieldTypes.add(rsmd.getColumnType(i)); switch (rsmd.getColumnType(i)) { case java.sql.Types.INTEGER: tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name)); break; case java.sql.Types.VARCHAR: tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, 64)); break; case java.sql.Types.TIMESTAMP: tblSQL.append(String.format("`%s` DATETIME DEFAULT NULL", name)); break; default: System.err.println(String.format("No case for %s %d", name, rsmd.getColumnType(i))); break; } } rs.close(); } int secInx = dbFieldNames.size() + 1; System.out.println("secInx: " + secInx + " " + tblSQL.toString()); HashSet<String> nameSet = new HashSet<String>(); int cnt = 0; for (Object nmObj : BasicSQLUtils.querySingleCol(connection, sql)) { String name = nmObj.toString(); if (name.endsWith("ID")) { continue; } name = StringUtils.replace(name, "(", "_"); name = StringUtils.replace(name, ")", "_"); if (nameSet.contains(name)) continue; nameSet.add(name); tblSQL.append(",\n "); if (name.startsWith("num_") || name.startsWith("Usage_")) { tblSQL.append(String.format("`%s` INT(11) DEFAULT NULL", name)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.INTEGER); } else if (name.endsWith("_number")) { tblSQL.append(String.format("`%s` VARCHAR(16) DEFAULT NULL", name)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.VARCHAR); } else { int maxLen = BasicSQLUtils.getCountAsInt(connection, String.format(sql2, name)); tblSQL.append(String.format("`%s` VARCHAR(%s) DEFAULT NULL", name, maxLen + 1)); dbFieldNames.add(name); dbFieldTypes.add(java.sql.Types.VARCHAR); } cnt++; } if (isRegBuild) { tblSQL.append(String.format(",\n`RecordType`INT(11) DEFAULT NULL")); } tblSQL.append(String.format(",\n PRIMARY KEY (`%s`)) ENGINE=InnoDB DEFAULT CHARSET=UTF8", keyName)); System.out.println(tblSQL.toString()); DBMSUserMgr dbMgr = DBMSUserMgr.getInstance(); dbMgr.setConnection(connection); if (dbMgr.doesDBHaveTable(newTblName)) { BasicSQLUtils.update(connection, "DROP TABLE " + newTblName); } BasicSQLUtils.update(connection, tblSQL.toString()); HashMap<Integer, String> inxToName = new HashMap<Integer, String>(); StringBuilder fields = new StringBuilder(); StringBuilder vals = new StringBuilder(); int inx = 0; for (String nm : dbFieldNames) { if (fields.length() > 0) fields.append(","); fields.append(nm); if (vals.length() > 0) vals.append(","); vals.append('?'); inxToName.put(inx, nm); inx++; } if (isRegBuild) { if (fields.length() > 0) fields.append(","); fields.append("RecordType"); if (vals.length() > 0) vals.append(","); vals.append('?'); } String insertSQL = String.format("INSERT INTO %s (%s) VALUES(%s)", newTblName, fields.toString(), vals.toString()); System.out.println(insertSQL); PreparedStatement pStmt = connection.prepareStatement(insertSQL); if (isRegBuild) { fillRegisterTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames, inxToName); } else { fillTrackTable(newTblName, stmt, pStmt, fillSQL, secInx, dbFieldTypes, dbFieldNames, inxToName); } System.out.println("InstCnt: " + instCnt); pStmt.close(); } boolean doIP = false; if (doIP) { HTTPGetter httpGetter = new HTTPGetter(); sql = "SELECT RegID, IP from reg"; PreparedStatement pStmt = connection.prepareStatement(String .format("UPDATE %s SET lookup=?, Country=?, City=? WHERE %s = ?", newTblName, keyName)); HashMap<String, String> ipHash = new HashMap<String, String>(); HashMap<String, Pair<String, String>> ccHash = new HashMap<String, Pair<String, String>>(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int regId = rs.getInt(1); String ip = rs.getString(2); String hostName = ipHash.get(ip); String country = null; String city = null; if (hostName == null) { String rvStr = new String( httpGetter.doHTTPRequest("http://api.hostip.info/get_html.php?ip=" + ip)); country = parse(rvStr, "Country:"); city = parse(rvStr, "City:"); System.out.println(rvStr + "[" + country + "][" + city + "]"); try { InetAddress addr = InetAddress.getByName(ip); hostName = addr.getHostName(); ipHash.put(ip, hostName); ccHash.put(ip, new Pair<String, String>(country, city)); } catch (UnknownHostException e) { e.printStackTrace(); } } else { Pair<String, String> p = ccHash.get(ip); if (p != null) { country = p.first; city = p.second; } } pStmt.setString(1, hostName); pStmt.setString(2, country); pStmt.setString(3, city); pStmt.setInt(4, regId); pStmt.executeUpdate(); } pStmt.close(); } stmt.close(); colDBConn.close(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Done."); }