List of usage examples for java.net InetAddress getHostName
public String getHostName()
From source file:org.apache.hadoop.mapred.JobClient.java
/** * Internal method for submitting jobs to the system. * @param job the configuration to submit * @return a proxy object for the running job * @throws FileNotFoundException/*from w w w . j av a2s . co m*/ * @throws ClassNotFoundException * @throws InterruptedException * @throws IOException */ public RunningJob submitJobInternal(final JobConf job) throws FileNotFoundException, ClassNotFoundException, InterruptedException, IOException { /* * configure the command line options correctly on the submitting dfs */ return ugi.doAs(new PrivilegedExceptionAction<RunningJob>() { public RunningJob run() throws FileNotFoundException, ClassNotFoundException, InterruptedException, IOException { JobConf jobCopy = job; Path jobStagingArea = JobSubmissionFiles.getStagingDir(JobClient.this, jobCopy); JobID jobId = jobSubmitClient.getNewJobId(); Path submitJobDir = new Path(jobStagingArea, jobId.toString()); jobCopy.set("mapreduce.job.dir", submitJobDir.toString()); JobStatus status = null; try { populateTokenCache(jobCopy, jobCopy.getCredentials()); copyAndConfigureFiles(jobCopy, submitJobDir); // get delegation token for the dir TokenCache.obtainTokensForNamenodes(jobCopy.getCredentials(), new Path[] { submitJobDir }, jobCopy); Path submitJobFile = JobSubmissionFiles.getJobConfPath(submitJobDir); int reduces = jobCopy.getNumReduceTasks(); InetAddress ip = InetAddress.getLocalHost(); if (ip != null) { job.setJobSubmitHostAddress(ip.getHostAddress()); job.setJobSubmitHostName(ip.getHostName()); } JobContext context = new JobContext(jobCopy, jobId); // Check the output specification if (reduces == 0 ? jobCopy.getUseNewMapper() : jobCopy.getUseNewReducer()) { org.apache.hadoop.mapreduce.OutputFormat<?, ?> output = ReflectionUtils .newInstance(context.getOutputFormatClass(), jobCopy); output.checkOutputSpecs(context); } else { jobCopy.getOutputFormat().checkOutputSpecs(fs, jobCopy); } jobCopy = (JobConf) context.getConfiguration(); // Create the splits for the job FileSystem fs = submitJobDir.getFileSystem(jobCopy); LOG.debug("Creating splits at " + fs.makeQualified(submitJobDir)); int maps = writeSplits(context, submitJobDir); jobCopy.setNumMapTasks(maps); // write "queue admins of the queue to which job is being submitted" // to job file. String queue = jobCopy.getQueueName(); AccessControlList acl = jobSubmitClient.getQueueAdmins(queue); jobCopy.set(QueueManager.toFullPropertyName(queue, QueueACL.ADMINISTER_JOBS.getAclName()), acl.getACLString()); // Write job file to JobTracker's fs FSDataOutputStream out = FileSystem.create(fs, submitJobFile, new FsPermission(JobSubmissionFiles.JOB_FILE_PERMISSION)); try { jobCopy.writeXml(out); } finally { out.close(); } // // Now, actually submit the job (using the submit name) // printTokens(jobId, jobCopy.getCredentials()); status = jobSubmitClient.submitJob(jobId, submitJobDir.toString(), jobCopy.getCredentials()); JobProfile prof = jobSubmitClient.getJobProfile(jobId); if (status != null && prof != null) { return new NetworkedJob(status, prof, jobSubmitClient); } else { throw new IOException("Could not launch job"); } } finally { if (status == null) { LOG.info("Cleaning up the staging area " + submitJobDir); if (fs != null && submitJobDir != null) fs.delete(submitJobDir, true); } } } }); }
From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java
/** * This method is responsible for inserting new entries into the * ipInterface table for each interface found to be associated with the * suspect interface during the capabilities scan. * * @param dbc Database connection. * @param node DbNodeEntry object representing the suspect interface's * parent node table entry * @param useExistingNode False if a new node was created for the suspect interface. * True if an existing node entry was found under which the the * suspect interface is to be added. * @param ifaddr Suspect interface * @param collector Interface collector containing SMB and SNMP info collected * from the remote device. * @throws java.sql.SQLException if an error occurs adding interfaces to the ipInterface * table./*from w w w . j a v a 2 s .c o m*/ */ private void addInterfaces(Connection dbc, DbNodeEntry node, boolean useExistingNode, InetAddress ifaddr, IfCollector collector) throws SQLException { CapsdConfig cFactory = capsdConfig; Date now = new Date(); int nodeId = node.getNodeId(); DbIpInterfaceEntry ipIfEntry = DbIpInterfaceEntry.create(nodeId, ifaddr); ipIfEntry.setLastPoll(now); ipIfEntry.setHostname(ifaddr.getHostName()); /* * NOTE: (reference internal bug# 201) If the ip is 'managed', it * might still be 'not polled' based on the poller configuration The * package filter evaluation requires that the ip be in the database - * at this point the ip is NOT in db, so insert as active and update * afterward Try to avoid re-evaluating the ip against filters for * each service, try to get the first package here and use that for * service evaluation */ boolean addrUnmanaged = cFactory.isAddressUnmanaged(ifaddr); if (addrUnmanaged) { LOG.debug("addInterfaces: {} is unmanaged", ifaddr); ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED); } else { LOG.debug("addInterfaces: {} is managed", ifaddr); ipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED); } ipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE); ipIfEntry.store(dbc); // now update if necessary org.opennms.netmgt.config.poller.Package ipPkg = getPackageForNewInterface(dbc, ifaddr, ipIfEntry, addrUnmanaged); int ifIndex = addSnmpInterfaces(dbc, ifaddr, nodeId, collector, ipIfEntry); // Add supported protocols addSupportedProtocols(node, ifaddr, collector.getSupportedProtocols(), addrUnmanaged, ifIndex, ipPkg); /* * If the useExistingNode flag is true, then we're done. The interface * is most likely an alias and the subinterfaces collected via SNMP * should already be in the database. */ if (useExistingNode == true) { return; } getSubInterfacesForNewInterface(dbc, node, ifaddr, collector, now, nodeId, ifIndex); }
From source file:es.caib.seycon.ng.servei.XarxaServiceImpl.java
/** * Lanzar el VNC contra la sesin indicada. Se verificar que el usuario * est autorizado a lanzar capturas en la red asociada * //from w ww .j a v a 2s . c o m * @param sessioId * id de la sesin que se quiere capturar * @return true si el usuario acepta la captura de pantalla y teclado * @throws InternalErrorException * error en la configuracin del servidor * @throws es.caib.seycon.util.TimedOutException * el usuario no ha respondido en el tiempo especificado * @throws java.io.IOException * error en la comunicacin con el puesto de trabajo */ protected Boolean handleLaunchVNC(Long sessioId) throws java.io.IOException, TimedOutException, InternalErrorException { try { SessioEntity sessio = getSessioEntityDao().findById(sessioId); if (sessio == null) throw new InternalErrorException( String.format(Messages.getString("XarxaServiceImpl.NoSessionIDFound"), //$NON-NLS-1$ sessioId)); if (sessio.getMaquinaClient() != null) return false; // Mirem si s autoritzat (autoritzaci o acls) if (internalGetAccessLevel(sessio.getMaquina().getNom(), sessio.getMaquina().getXarxa().getCodi()) < SUPORT) throw new java.lang.SecurityException(Messages.getString("XarxaServiceImpl.NoPermissionMessage")); //$NON-NLS-1$ InetAddress addr = InetAddress.getLocalHost(); if (addr == null) throw new InternalErrorException(Messages.getString("XarxaServiceImpl.NoGetInetAddress")); //$NON-NLS-1$ TimedProcess t = new TimedProcess(20000); if (addr.getHostName().toLowerCase().startsWith("epreinf14")) //$NON-NLS-1$ t.exec(new String[] { "rsh", "spreinfsun2", "rsh", sessio.getMaquina().getNom(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ "vnc" }); //$NON-NLS-1$ else t.exec(new String[] { "rsh", sessio.getMaquina().getNom(), "vnc" }); //$NON-NLS-1$ //$NON-NLS-2$ if (t.getOutput().indexOf("concedit") > 0) { //$NON-NLS-1$ auditaVNC(sessio, "S"); //$NON-NLS-1$ /* * registraAuditoria (sessio.getMaquina().Name, * usuaris.getIdUsuari(autor), sessio.getUsuari()!=null ? * sessio.getUsuari().User : "", "S"); */ return true; } else auditaVNC(sessio, "N"); //$NON-NLS-1$ /* * registraAuditoria( sessio.getMaquina().Name, * usuaris.getIdUsuari(autor), sessio.getUsuari() != null ? * sessio.getUsuari().User : "", "N"); */ return false; } catch (java.net.UnknownHostException e) { throw new InternalErrorException(e.toString()); } }
From source file:de.unibi.techfak.bibiserv.BiBiTools.java
/** * publiv static helper method that search and load (if found) bibiserv * properties./* w ww . j a v a2 s . c o m*/ * * - Used by getProperty to load static properties variable with content, * during 1st time call. - Could be used to "reload" Properties content * during runtime (e.g. for reconfiguration). * * @return a Properties object * */ public static void loadBiBiProperties() throws BiBiToolsException { properties = new Properties(); InputStream rin = null; /* first check if a System Property bibiserv2.property.location is set */ log.info("Check for property 'bibiserv2.property.location'."); if (System.getProperty("de.unibi.techfak.bibiserv.config") != null) { try { rin = new FileInputStream(System.getProperty("de.unibi.techfak.bibiserv.config")); } catch (FileNotFoundException e) { // do nothing, in the case this exception occurs try second possibility log.warn( "Property 'de.unibi.techfak.bibiserv.config' is set, but property value doesn't point to a xml configuration."); } } /* second, check if bibiserv property is located in domain root folder ${catalina.home}*/ if (rin == null) { log.info("Check for ${catalina.home}/bibiserv_properties.xml"); if (System.getProperty("catalina.home") != null) { try { rin = new FileInputStream(System.getProperty("catalina.home") + "/bibiserv_properties.xml"); } catch (FileNotFoundException e) { // do nothing, in the case this exception occure try third possibility } } } /* third, check for bibiserv property in classpath (load as resource) */ if (rin == null) { log.info("Check for bibiserv.properties in classpath!"); rin = ClassLoader.getSystemResourceAsStream("bibiserv_properties.xml"); } /* load properties from Inputstream */ if (rin != null) { try { properties.loadFromXML(rin); } catch (IOException e) { log.fatal("Can't read BiBiServ Properties file!", e); throw new BiBiToolsException("Can't read BiBiServ Properties file!", e); } } else { throw new BiBiToolsException("BiBiServ Properties file not found!\n" + "1) set Java system property 'de.unibi.techfak.bibiserv.config'\n" + "2) place bibiserv_properties.xml in ${catalina.home} base folder\n" + "3) place bibiserv_properties.xml in Java classpath!"); } // add Hostname of localhost to properties try { InetAddress addr = InetAddress.getLocalHost(); properties.setProperty("hostname", addr.getHostName()); log.info("Hostname is " + addr.getHostName() + " !"); } catch (UnknownHostException e) { log.fatal("Fatal error occurred when detecting hostname of local machine\n" + e.getMessage()); throw new RuntimeException(e); } }
From source file:org.apache.coyote.tomcat5.CoyoteRequest.java
/** * Returns the host name of the Internet Protocol (IP) interface on * which the request was received./* www .j av a2 s . c o m*/ */ public String getLocalName() { if (localName == null) { if (socket != null) { InetAddress inet = socket.getLocalAddress(); localName = inet.getHostName(); } else { coyoteRequest.action(ActionCode.ACTION_REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest); localName = coyoteRequest.localName().toString(); } } return localName; }
From source file:org.apache.coyote.tomcat5.CoyoteRequest.java
/** * Return the remote host name making this Request. *//*from w w w.j a va2 s. co m*/ public String getRemoteHost() { if (remoteHost == null) { if (!connector.getEnableLookups()) { remoteHost = getRemoteAddr(); } else if (socket != null) { InetAddress inet = socket.getInetAddress(); remoteHost = inet.getHostName(); } else { coyoteRequest.action(ActionCode.ACTION_REQ_HOST_ATTRIBUTE, coyoteRequest); remoteHost = coyoteRequest.remoteHost().toString(); } } return remoteHost; }
From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java
/** * This method is responsble for inserting a new node into the node table. * * @param dbc Database connection. * @param ifaddr Suspect interface//from www . j a v a 2 s.c om * @param collector Interface collector containing SMB and SNMP info collected * from the remote device. * @return DbNodeEntry object associated with the newly inserted node * table entry. * @throws java.sql.SQLException if an error occurs inserting the new node. */ private DbNodeEntry createNode(Connection dbc, InetAddress ifaddr, IfCollector collector) throws SQLException { // Determine primary interface for the node. Primary interface // is needed for determining the node label. // InetAddress primaryIf = determinePrimaryInterface(collector); // Get Snmp and Smb collector objects // IfSnmpCollector snmpc = collector.getSnmpCollector(); IfSmbCollector smbc = collector.getSmbCollector(); // First create a node entry for the new interface // DbNodeEntry entryNode = DbNodeEntry.create(); // fill in the node information // Date now = new Date(); entryNode.setCreationTime(now); entryNode.setLastPoll(now); entryNode.setNodeType(OnmsNode.NodeType.ACTIVE); entryNode.setLabel(primaryIf.getHostName()); if (entryNode.getLabel().equals(str(primaryIf))) { entryNode.setLabelSource(OnmsNode.NodeLabelSource.ADDRESS); } else { entryNode.setLabelSource(OnmsNode.NodeLabelSource.HOSTNAME); } if (snmpc != null) { if (snmpc.hasSystemGroup()) { SystemGroup sysgrp = snmpc.getSystemGroup(); // sysObjectId String sysObjectId = sysgrp.getSysObjectID(); if (sysObjectId != null) { entryNode.setSystemOID(sysObjectId); } else { LOG.warn("SuspectEventProcessor: {} has NO sysObjectId!!!!", str(ifaddr)); } // sysName String str = sysgrp.getSysName(); LOG.debug("SuspectEventProcessor: {} has sysName: {}", str(ifaddr), str); if (str != null && str.length() > 0) { entryNode.setSystemName(str); // Hostname takes precedence over sysName so only replace // label if // hostname was not available. if (entryNode.getLabelSource() == OnmsNode.NodeLabelSource.ADDRESS) { entryNode.setLabel(str); entryNode.setLabelSource(OnmsNode.NodeLabelSource.SYSNAME); } } // sysDescription str = sysgrp.getSysDescr(); LOG.debug("SuspectEventProcessor: {} has sysDescription: {}", str(ifaddr), str); if (str != null && str.length() > 0) { entryNode.setSystemDescription(str); } // sysLocation str = sysgrp.getSysLocation(); LOG.debug("SuspectEventProcessor: {} has sysLocation: {}", str(ifaddr), str); if (str != null && str.length() > 0) { entryNode.setSystemLocation(str); } // sysContact str = sysgrp.getSysContact(); LOG.debug("SuspectEventProcessor: {} has sysContact: {}", str(ifaddr), str); if (str != null && str.length() > 0) { entryNode.setSystemContact(str); } } } // check for SMB information // if (smbc != null) { // Netbios Name and Domain // Note: only override if the label source is not HOSTNAME if (smbc.getNbtName() != null && entryNode.getLabelSource() != OnmsNode.NodeLabelSource.HOSTNAME) { entryNode.setLabel(smbc.getNbtName()); entryNode.setLabelSource(OnmsNode.NodeLabelSource.NETBIOS); entryNode.setNetBIOSName(entryNode.getLabel()); if (smbc.getDomainName() != null) { entryNode.setDomainName(smbc.getDomainName()); } } } entryNode.store(dbc); return entryNode; }
From source file:tachyon.master.MasterInfo.java
/** * Get the address of a worker.// w w w . j av a2 s . c o m * * @param random If true, select a random worker * @param host If <code>random</code> is false, select a worker on this host * @return the address of the selected worker, or null if no address could be found */ public NetAddress getWorker(boolean random, String host) throws UnknownHostException { synchronized (mWorkers) { if (mWorkerAddressToId.isEmpty()) { return null; } if (random) { int index = new Random(mWorkerAddressToId.size()).nextInt(mWorkerAddressToId.size()); for (NetAddress address : mWorkerAddressToId.keySet()) { if (index == 0) { LOG.debug("getRandomWorker: {}", address); return address; } index--; } for (NetAddress address : mWorkerAddressToId.keySet()) { LOG.debug("getRandomWorker: {}", address); return address; } } else { for (NetAddress address : mWorkerAddressToId.keySet()) { InetAddress inetAddress = InetAddress.getByName(address.getMHost()); if (inetAddress.getHostName().equals(host) || inetAddress.getHostAddress().equals(host) || inetAddress.getCanonicalHostName().equals(host)) { LOG.debug("getLocalWorker: {}" + address); return address; } } } } LOG.info("getLocalWorker: no local worker on " + host); return null; }
From source file:org.apache.ambari.controller.rest.agent.ControllerResource.java
/** * Sample Ambari heartbeat message//from w w w . j a va 2s . c om * * @response.representation.200.example * { "responseId": "-1", "timestamp": "1318955147616", "hostname": "host.example.com", "hardwareProfile": { "coreCount": "8", "diskCount": "4", "ramSize": "16442752", "cpuSpeed": "2003", "netSpeed": "1000", "cpuFlags": "vmx est tm2..." }, "installedRoleStates": [ { "clusterId": "cluster-003", "clusterDefinitionRevision": "2", "componentName": "hdfs", "roleName": "datanode", "serverStatus": "STARTED" } ], "actionResults": [ { "clusterId": "cluster-001", "id": "action-001", "kind": "STOP_ACTION", "clusterDefinitionRevision": "1" }, { "clusterId": "cluster-002", "kind": "START_ACTION", "commandResult": { "exitCode": "0", "stdout": "stdout", "stderr": "stderr" }, "cleanUpCommandResult": { "exitCode": "0", "stdout": "stdout", "stderr": "stderr" }, "component": "hdfs", "role": "datanode", "clusterDefinitionRevision": "2" } ], "idle": "false" } * @response.representation.200.doc Print example of Ambari heartbeat message * @response.representation.200.mediaType application/json * @param stackId Stack ID * @return Heartbeat message */ @Path("heartbeat/sample") @GET @Produces(MediaType.APPLICATION_JSON) public HeartBeat getHeartBeat(@DefaultValue("stack-123") @QueryParam("stackId") String stackId) { try { InetAddress addr = InetAddress.getLocalHost(); List<ActionResult> actionResults = new ArrayList<ActionResult>(); ActionResult actionResult = new ActionResult(); actionResult.setClusterDefinitionRevision(1); actionResult.setId("action-001"); actionResult.setClusterId("cluster-001"); actionResult.setKind(Kind.STOP_ACTION); ActionResult actionResult2 = new ActionResult(); actionResult2.setClusterDefinitionRevision(2); actionResult2.setClusterId("cluster-002"); actionResult2.setCommandResult(new CommandResult(0, "stdout", "stderr")); actionResult2.setCleanUpResult(new CommandResult(0, "stdout", "stderr")); actionResult2.setKind(Kind.START_ACTION); actionResult2.setComponent("hdfs"); actionResult2.setRole("datanode"); actionResults.add(actionResult); actionResults.add(actionResult2); HardwareProfile hp = new HardwareProfile(); hp.setCoreCount(8); hp.setCpuFlags( "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx lm constant_tsc pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 lahf_lm"); hp.setCpuSpeed(2003); hp.setDiskCount(4); hp.setNetSpeed(1000); hp.setRamSize(16442752); List<AgentRoleState> agentRoles = new ArrayList<AgentRoleState>(2); AgentRoleState agentRole1 = new AgentRoleState(); agentRole1.setClusterDefinitionRevision(2); agentRole1.setClusterId("cluster-003"); agentRole1.setComponentName("hdfs"); agentRole1.setRoleName("datanode"); agentRole1.setServerStatus(AgentRoleState.State.STARTED); agentRoles.add(agentRole1); HeartBeat hb = new HeartBeat(); hb.setResponseId((short) -1); hb.setTimestamp(System.currentTimeMillis()); hb.setHostname(addr.getHostName()); hb.setActionResults(actionResults); hb.setHardwareProfile(hp); hb.setInstalledRoleStates(agentRoles); hb.setIdle(false); return hb; } catch (UnknownHostException e) { throw new WebApplicationException(e); } }
From source file:slash.navigation.mapview.browser.BrowserMapView.java
protected void checkLocalhostResolution() { try {/*from w ww . j a va 2 s. c o m*/ InetAddress localhost = InetAddress.getByName("localhost"); log.info("localhost is resolved to: " + localhost); String localhostName = localhost.getHostAddress(); log.info("IP of localhost is: " + localhostName); if (!localhostName.equals("127.0.0.1")) throw new Exception("localhost does not resolve to 127.0.0.1"); InetAddress ip = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); log.info("127.0.0.1 is resolved to: " + ip); String ipName = localhost.getHostName(); log.info("Name of 127.0.0.1 is: " + ipName); if (!ipName.equals("localhost")) throw new Exception("127.0.0.1 does not resolve to localhost"); } catch (Exception e) { final String message = "Probably faulty network setup: " + getLocalizedMessage(e) + ".\nPlease check your network settings."; log.severe(message); invokeLater(new Runnable() { public void run() { showMessageDialog(getComponent(), message, "Error", ERROR_MESSAGE); } }); } }