List of usage examples for java.net InetAddress getLocalHost
public static InetAddress getLocalHost() throws UnknownHostException
From source file:com.ery.ertc.estorm.util.DNS.java
/** * Returns all the IPs associated with the provided interface, if any, in textual form. * //from w w w . j a v a 2 s.c o m * @param strInterface * The name of the network interface or subinterface to query (eg eth0 or eth0:0) or the string "default" * @param returnSubinterfaces * Whether to return IPs associated with subinterfaces of the given interface * @return A string vector of all the IPs associated with the provided interface * @throws UnknownHostException * If an UnknownHostException is encountered in querying the default interface or the given interface can not be found * */ public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException { if ("default".equals(strInterface)) { return new String[] { InetAddress.getLocalHost().getHostAddress() }; } NetworkInterface netIf; try { netIf = NetworkInterface.getByName(strInterface); if (netIf == null) { netIf = getSubinterface(strInterface); if (netIf == null) { throw new UnknownHostException("Unknown interface " + strInterface); } } } catch (SocketException e) { LOG.warn("Unable to get IP for interface " + strInterface, e); return new String[] { InetAddress.getLocalHost().getHostAddress() }; } // NB: Using a LinkedHashSet to preserve the order for callers // that depend on a particular element being 1st in the array. // For example, getDefaultIP always returns the first element. LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>(); allAddrs.addAll(Collections.list(netIf.getInetAddresses())); if (!returnSubinterfaces) { allAddrs.removeAll(getSubinterfaceInetAddrs(netIf)); } String ips[] = new String[allAddrs.size()]; int i = 0; for (InetAddress addr : allAddrs) { ips[i++] = addr.getHostAddress(); } return ips; }
From source file:com.shareplaylearn.resources.File.java
/** * TODO: Once we have an async form, send access token in header, not in form * @param filestream//from w w w . java 2 s . c om * @param contentDisposition * @param filename * @param userId * @param accessToken * @return */ @POST @Path("/form") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response postFileForm(@FormDataParam("file") InputStream filestream, @FormDataParam("file") FormDataContentDisposition contentDisposition, //we'll let this be optional, derive from the contentDisposition for now //and add this where we want/need to @FormDataParam("filename") String filename, @FormDataParam("user_name") String userName, @FormDataParam("user_id") String userId, @FormDataParam("access_token") String accessToken, @HeaderParam("Content-Length") String contentLength) { try { //these still show up as null, despite annotations if (filestream == null || contentDisposition == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("Content Disposition or file not supplied " + filestream + "," + contentDisposition) .build(); } if (filename == null || filename.trim().length() == 0) { filename = contentDisposition.getFileName(); if (filename == null || filename.trim().length() == 0) { return Response.status(Response.Status.BAD_REQUEST) .entity("Filename not specified and not preseent in the content disposition").build(); } } if (userId == null || userId.trim().length() == 0) { return Response.status(Response.Status.BAD_REQUEST).entity("No user id given.").build(); } if (accessToken == null || accessToken.trim().length() == 0) { return Response.status(Response.Status.BAD_REQUEST).entity("No access token given.").build(); } if (userName == null || userId.trim().length() == 0) { return Response.status(Response.Status.BAD_REQUEST).entity("No user name given.").build(); } Response tokenResponse = OAuth2Callback.validateToken(accessToken); if (tokenResponse.getStatus() != Response.Status.OK.getStatusCode()) { return tokenResponse; } byte[] fileBuffer = org.apache.commons.io.IOUtils.toByteArray(filestream); UserItemManager userItemManager = new UserItemManager(userName, userId); userItemManager.addItem(filename, fileBuffer); //this had something to do with making it work locally for testing //possibly when I did a SEE OTHER return code. //TODO: confirm that we can rip this out at some point String[] host = InetAddress.getLocalHost().toString().split("/"); if (host[0].trim().length() == 0) { return Response.status(Response.Status.CREATED) .entity(filename + " stored under user id " + userId + " " + InetAddress.getLocalHost()) .build(); } else { String hostname = host[0].trim().toLowerCase(); if (!hostname.equals("shareplaylearn.com") && !hostname.equals("shareplaylearn.net")) { hostname = "localhost"; } return Response.status(Response.Status.CREATED).entity(this.uploadSuccessEntity(filename)).build(); } } catch (InternalErrorException ie) { String error = Exceptions.asString(ie); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (RuntimeException r) { String error = Exceptions.asString(r); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (Throwable t) { String error = Exceptions.asString(t); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } }
From source file:com.ikon.servlet.ValidateLicenseServlet.java
/** * get MacId of the server./*from ww w. j av a 2 s .com*/ * @return * @throws IOException */ static String getMacAddress() throws IOException { InetAddress inetAddress; NetworkInterface networkInterface; StringBuilder sb = new StringBuilder(); try { inetAddress = InetAddress.getLocalHost(); networkInterface = NetworkInterface.getByInetAddress(inetAddress); byte[] mac = networkInterface.getHardwareAddress(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } } catch (UnknownHostException e) { throw new IOException("Unknown Host. Please try again later."); } catch (SocketException e) { throw new IOException("Could not connect to the socket. Please try again later."); } return sb.toString(); }
From source file:com.asquareb.kaaval.MachineKey.java
/** * Method to encrypt a string. Accepts the string to be encrypted and the * name of the file to store the key vale which can be used for decryption *//* ww w . j a v a 2 s . c om*/ public static String encrypt(String property, String app) throws IOException, KaavalException { InetAddress ip = null; String ipAddress = null; ObjectOutputStream os = null; NetworkInterface macAddress = null; byte[] macId = null; Cipher pbeCipher = null; Random rand = new Random(); rand.nextBytes(salt); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password)); ip = InetAddress.getLocalHost(); ipAddress = ip.getHostAddress(); macAddress = NetworkInterface.getByInetAddress(ip); macId = macAddress.getHardwareAddress(); MachineKey mKey = new MachineKey(); mKey.api = ipAddress; mKey.macad = new String(macId); mKey.yek = key; mKey.tlas = salt; mKey.eti = rand.nextInt(1000); os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(app))); os.writeObject(mKey); os.close(); pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, mKey.eti)); return base64Encode(pbeCipher.doFinal(property.getBytes())); } catch (IOException e) { throw new KaavalException(1, "Error in key file during encryption", e); } catch (Exception e) { throw new KaavalException(2, "Errors during encryption", e); } finally { if (os != null) os.close(); } }
From source file:com.uber.stream.kafka.mirrormaker.manager.TestManagerConf.java
@Test public void testDefaultCmdControllerConf() throws ParseException { try {//w w w .ja v a2 s.c o m String[] args = new String[] {}; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.fail("Expected exception to be thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().equals("Missing option: --zookeeper")); } try { String[] args = new String[] { "-zookeeper", "localhost:2181/test" }; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.fail("Expected exception to be thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().equals("Missing option: --managerPort")); } try { String[] args = new String[] { "-zookeeper", "localhost:2181/test", "-managerPort", "9090" }; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.fail("Expected exception to be thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().equals("Missing option: --deployment")); } try { String[] args = new String[] { "-zookeeper", "localhost:2181/test", "-managerPort", "9090", "-deployment", "testing" }; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.fail("Expected exception to be thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().equals("Missing option: --env")); } try { String[] args = new String[] { "-zookeeper", "localhost:2181/test", "-managerPort", "9090", "-deployment", "testing", "-env", "dc.testing" }; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.fail("Expected exception to be thrown"); } catch (RuntimeException e) { Assert.assertTrue(e.getMessage().equals("Missing option: --controllerPort")); } try { String[] args = new String[] { "-zookeeper", "localhost:2181/test", "-managerPort", "9090", "-deployment", "testing", "-controllerPort", "8080", "-env", "dc.testing" }; CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(ManagerConf.constructManagerOptions(), args); ManagerConf conf = ManagerConf.getManagerConf(cmd); Assert.assertTrue(conf.getSourceClusters().isEmpty()); Assert.assertTrue(conf.getDestinationClusters().isEmpty()); Assert.assertEquals(conf.getManagerZkStr(), "localhost:2181/test"); Assert.assertEquals(conf.getManagerPort().toString(), "9090"); Assert.assertEquals(conf.getManagerDeployment(), "testing"); Assert.assertEquals(conf.getManagerInstanceId(), InetAddress.getLocalHost().getHostName()); Assert.assertEquals(conf.getControllerPort().toString(), "8080"); Assert.assertEquals(conf.getC3Host(), "localhost"); Assert.assertEquals(conf.getC3Port().toString(), "0"); Assert.assertEquals(conf.getWorkloadRefreshPeriodInSeconds().toString(), "600"); Assert.assertEquals(conf.getInitMaxNumPartitionsPerRoute().toString(), "10"); Assert.assertEquals(conf.getMaxNumPartitionsPerRoute().toString(), "20"); Assert.assertEquals(conf.getInitMaxNumWorkersPerRoute().toString(), "3"); Assert.assertEquals(conf.getMaxNumWorkersPerRoute().toString(), "5"); } catch (Exception e) { Assert.fail("No exception is expected"); } }
From source file:com.gemstone.gemfire.management.internal.cli.commands.SharedConfigurationCommandsDUnitTest.java
@SuppressWarnings("unchecked") public void testExportImportSharedConfiguration() { disconnectAllFromDS();/* w w w . j a v a2 s .c om*/ final String region1Name = "r1"; final String region2Name = "r2"; final String groupName = "testRegionSharedConfigGroup"; final String sharedConfigZipFileName = "sharedConfig.zip"; final String deployedJarName = "DeployCommandsDUnit1.jar"; final String logLevel = "info"; final String startArchiveFileName = "stats.gfs"; final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(3); // TODO Sourabh - the code below is similar to CliCommandTestBase.createDefaultSetup(..); we may want to consider // refactoring this and combine the duplicate code blocks using either the Template Method and/or Strategy design // patterns. We can talk about this. // Start the Locator and wait for shared configuration to be available final int locator1Port = ports[0]; final String locator1Name = "locator1-" + locator1Port; VM locatorAndMgr = Host.getHost(0).getVM(3); Object[] result = (Object[]) locatorAndMgr.invoke(new SerializableCallable() { @Override public Object call() { int httpPort; int jmxPort; String jmxHost; try { jmxHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ignore) { jmxHost = "localhost"; } final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2); jmxPort = ports[0]; httpPort = ports[1]; final File locatorLogFile = new File("locator-" + locator1Port + ".log"); final Properties locatorProps = new Properties(); locatorProps.setProperty(DistributionConfig.NAME_NAME, locator1Name); locatorProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); locatorProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "config"); locatorProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "true"); locatorProps.setProperty(DistributionConfig.JMX_MANAGER_NAME, "true"); locatorProps.setProperty(DistributionConfig.JMX_MANAGER_START_NAME, "true"); locatorProps.setProperty(DistributionConfig.JMX_MANAGER_BIND_ADDRESS_NAME, String.valueOf(jmxHost)); locatorProps.setProperty(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(jmxPort)); locatorProps.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(httpPort)); try { final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator1Port, locatorLogFile, null, locatorProps); DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() { @Override public boolean done() { return locator.isSharedConfigurationRunning(); } @Override public String description() { return "Waiting for shared configuration to be started"; } }; DistributedTestCase.waitForCriterion(wc, TIMEOUT, INTERVAL, true); } catch (IOException ioex) { fail("Unable to create a locator with a shared configuration"); } final Object[] result = new Object[4]; result[0] = jmxHost; result[1] = jmxPort; result[2] = httpPort; result[3] = CliUtil.getAllNormalMembers(CacheFactory.getAnyInstance()); return result; } }); HeadlessGfsh gfsh = getDefaultShell(); String jmxHost = (String) result[0]; int jmxPort = (Integer) result[1]; int httpPort = (Integer) result[2]; Set<DistributedMember> normalMembers1 = (Set<DistributedMember>) result[3]; shellConnect(jmxHost, jmxPort, httpPort, gfsh); // Create a cache in VM 1 VM dataMember = Host.getHost(0).getVM(1); normalMembers1 = (Set<DistributedMember>) dataMember.invoke(new SerializableCallable() { @Override public Object call() { Properties localProps = new Properties(); localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); localProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locator1Port); localProps.setProperty(DistributionConfig.GROUPS_NAME, groupName); localProps.setProperty(DistributionConfig.NAME_NAME, "DataMember"); getSystem(localProps); Cache cache = getCache(); assertNotNull(cache); return CliUtil.getAllNormalMembers(cache); } }); // Create a JAR file try { this.classBuilder.writeJarFromName("DeployCommandsDUnitA", this.newDeployableJarFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Deploy the JAR CommandResult cmdResult = executeCommand("deploy --jar=" + deployedJarName); assertEquals(Result.Status.OK, cmdResult.getStatus()); //Create the region1 on the group CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION); commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, region1Name); commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE"); commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true"); commandStringBuilder.addOption(CliStrings.CREATE_REGION__GROUP, groupName); cmdResult = executeCommand(commandStringBuilder.toString()); assertEquals(Result.Status.OK, cmdResult.getStatus()); commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION); commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, region2Name); commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION"); commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true"); cmdResult = executeCommand(commandStringBuilder.toString()); assertEquals(Result.Status.OK, cmdResult.getStatus()); //Alter runtime configuration commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL, logLevel); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, "50"); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT, "32"); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT, "49"); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, "120"); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, startArchiveFileName); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED, "true"); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, "10"); cmdResult = executeCommand(commandStringBuilder.getCommandString()); String resultString = commandResultToString(cmdResult); getLogWriter().info("#SB Result\n"); getLogWriter().info(resultString); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); commandStringBuilder = new CommandStringBuilder(CliStrings.STATUS_SHARED_CONFIG); cmdResult = executeCommand(commandStringBuilder.getCommandString()); resultString = commandResultToString(cmdResult); getLogWriter().info("#SB Result\n"); getLogWriter().info(resultString); assertEquals(Status.OK, cmdResult.getStatus()); commandStringBuilder = new CommandStringBuilder(CliStrings.EXPORT_SHARED_CONFIG); commandStringBuilder.addOption(CliStrings.EXPORT_SHARED_CONFIG__FILE, sharedConfigZipFileName); cmdResult = executeCommand(commandStringBuilder.getCommandString()); resultString = commandResultToString(cmdResult); getLogWriter().info("#SB Result\n"); getLogWriter().info(resultString); assertEquals(Status.OK, cmdResult.getStatus()); //Import into a running system should fail commandStringBuilder = new CommandStringBuilder(CliStrings.IMPORT_SHARED_CONFIG); commandStringBuilder.addOption(CliStrings.IMPORT_SHARED_CONFIG__ZIP, sharedConfigZipFileName); cmdResult = executeCommand(commandStringBuilder.getCommandString()); assertEquals(Status.ERROR, cmdResult.getStatus()); //Stop the data members and remove the shared configuration in the locator. dataMember.invoke(new SerializableCallable() { @Override public Object call() throws Exception { Cache cache = getCache(); cache.close(); assertTrue(cache.isClosed()); disconnectFromDS(); return null; } }); //Clear shared configuration in this locator to test the import shared configuration locatorAndMgr.invoke(new SerializableCallable() { @Override public Object call() throws Exception { InternalLocator locator = InternalLocator.getLocator(); SharedConfiguration sc = locator.getSharedConfiguration(); assertNotNull(sc); sc.clearSharedConfiguration(); return null; } }); //Now execute import shared configuration //Now import the shared configuration and it should succeed. commandStringBuilder = new CommandStringBuilder(CliStrings.IMPORT_SHARED_CONFIG); commandStringBuilder.addOption(CliStrings.IMPORT_SHARED_CONFIG__ZIP, sharedConfigZipFileName); cmdResult = executeCommand(commandStringBuilder.getCommandString()); assertEquals(Status.OK, cmdResult.getStatus()); //Start a new locator , test if it has all the imported shared configuration artifacts VM newLocator = Host.getHost(0).getVM(2); final int locator2Port = ports[1]; final String locator2Name = "Locator2-" + locator2Port; newLocator.invoke(new SerializableRunnable() { @Override public void run() { final File locatorLogFile = new File("locator-" + locator2Port + ".log"); final Properties locatorProps = new Properties(); locatorProps.setProperty(DistributionConfig.NAME_NAME, locator2Name); locatorProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); locatorProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "fine"); locatorProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "true"); locatorProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locator1Port); try { final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator2Port, locatorLogFile, null, locatorProps); DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() { @Override public boolean done() { return locator.isSharedConfigurationRunning(); } @Override public String description() { return "Waiting for shared configuration to be started"; } }; DistributedTestCase.waitForCriterion(wc, 5000, 500, true); SharedConfiguration sc = locator.getSharedConfiguration(); assertNotNull(sc); Configuration groupConfig = sc.getConfiguration(groupName); assertNotNull(groupConfig); assertTrue(groupConfig.getCacheXmlContent().contains(region1Name)); Configuration clusterConfig = sc.getConfiguration(SharedConfiguration.CLUSTER_CONFIG); assertNotNull(clusterConfig); assertTrue(clusterConfig.getCacheXmlContent().contains(region2Name)); assertTrue(clusterConfig.getJarNames().contains(deployedJarName)); assertTrue(clusterConfig.getGemfireProperties().getProperty(DistributionConfig.LOG_LEVEL_NAME) .equals(logLevel)); assertTrue(clusterConfig.getGemfireProperties() .getProperty(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME) .equals(startArchiveFileName)); } catch (IOException ioex) { fail("Unable to create a locator with a shared configuration"); } catch (Exception e) { fail("Error occurred in cluster configuration service", e); } } }); //Clean up File sharedConfigZipFile = new File(sharedConfigZipFileName); FileUtils.deleteQuietly(sharedConfigZipFile); FileUtils.deleteQuietly(newDeployableJarFile); }
From source file:adams.core.net.InternetHelper.java
/** * Returns the IP address of the local host as string. * * @return the IP address, null if not available *///from ww w . j a v a 2 s. c om public static synchronized String getLocalHostIP() { String result; if (m_IP == null) { try { result = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { result = getIPFromNetworkInterface(); } m_IP = result; } else { result = m_IP; } return result; }
From source file:com.amazonaws.util.AwsHostNameUtils.java
/** * Returns the host name for the local host. If the operation is not allowed * by the security check, the textual representation of the IP address of * the local host is returned instead. If the ip address of the local host * cannot be resolved or if there is any other failure, "localhost" is * returned as a fallback./*from w ww . j av a 2 s. c o m*/ */ public static String localHostName() { try { InetAddress localhost = InetAddress.getLocalHost(); return localhost.getHostName(); } catch (Exception e) { LogFactory.getLog(AwsHostNameUtils.class) .debug("Failed to determine the local hostname; fall back to " + "use \"localhost\".", e); return "localhost"; } }
From source file:com.nridge.connector.fs.con_fs.restlet.RestletApplication.java
/** * Returns a Restlet instance used to identify inbound requests for the * web service endpoints.//from w w w . j a v a 2 s . c o m * * @return Restlet instance. */ @Override public Restlet createInboundRoot() { Restlet restletRoot; Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); Context restletContext = getContext(); Router restletRouter = new Router(restletContext); String propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.host_names"; String hostNames = mAppMgr.getString(propertyName); if (StringUtils.isEmpty(hostNames)) { try { InetAddress inetAddress = InetAddress.getLocalHost(); routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT); routerAttachEndPoints(restletRouter, inetAddress.getHostName()); routerAttachEndPoints(restletRouter, inetAddress.getHostAddress()); routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName()); } catch (UnknownHostException e) { appLogger.error(e.getMessage(), e); routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT); } } else { if (mAppMgr.isPropertyMultiValue(propertyName)) { String[] hostNameList = mAppMgr.getStringArray(propertyName); for (String hostName : hostNameList) routerAttachEndPoints(restletRouter, hostName); } else routerAttachEndPoints(restletRouter, hostNames); } RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext); propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.allow_addresses"; String allowAddresses = mAppMgr.getString(propertyName); if (StringUtils.isNotEmpty(allowAddresses)) { if (mAppMgr.isPropertyMultiValue(propertyName)) { String[] allowAddressList = mAppMgr.getStringArray(propertyName); for (String allowAddress : allowAddressList) { restletFilter.add(allowAddress); appLogger.debug("Filter Allow Address: " + allowAddress); } } else { restletFilter.add(allowAddresses); appLogger.debug("Filter Allow Address: " + allowAddresses); } restletFilter.setNext(restletRouter); restletRoot = restletFilter; } else restletRoot = restletRouter; appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return restletRoot; }
From source file:util.PiazzaLogger.java
/** * Generates a LoggerPayload with default values populated * /*from w w w.j a v a2s.co m*/ * @return LoggerPayload payload object */ private LoggerPayload getLoggerPayload() { LoggerPayload loggerPayload = new LoggerPayload(); loggerPayload.setApplication(serviceName); loggerPayload.setProcess(ManagementFactory.getRuntimeMXBean().getName()); try { loggerPayload.setHostName(InetAddress.getLocalHost().getHostName()); } catch (Exception exception) { LOGGER.error("Could not get hostname for component.", exception); } return loggerPayload; }