List of usage examples for java.net UnknownHostException getMessage
public String getMessage()
From source file:org.apache.hadoop.mapreduce.v2.hs.CompletedJob.java
private void constructJobReport() { report = Records.newRecord(JobReport.class); report.setJobId(jobId);//from w w w .j av a 2 s. c o m report.setJobState(JobState.valueOf(jobInfo.getJobStatus())); report.setSubmitTime(jobInfo.getSubmitTime()); report.setStartTime(jobInfo.getLaunchTime()); report.setFinishTime(jobInfo.getFinishTime()); report.setJobName(jobInfo.getJobname()); report.setUser(jobInfo.getUsername()); report.setDiagnostics(jobInfo.getErrorInfo()); if (getTotalMaps() == 0) { report.setMapProgress(1.0f); } else { report.setMapProgress((float) getCompletedMaps() / getTotalMaps()); } if (getTotalReduces() == 0) { report.setReduceProgress(1.0f); } else { report.setReduceProgress((float) getCompletedReduces() / getTotalReduces()); } report.setJobFile(getConfFile().toString()); String historyUrl = "N/A"; try { historyUrl = MRWebAppUtil.getApplicationWebURLOnJHSWithScheme(conf, jobId.getAppId()); } catch (UnknownHostException e) { LOG.error("Problem determining local host: " + e.getMessage()); } report.setTrackingUrl(historyUrl); report.setAMInfos(getAMInfos()); report.setIsUber(isUber()); }
From source file:org.openhab.binding.onkyo.internal.OnkyoConnection.java
/** * Connects to the receiver by opening a socket connection through the * IP and port./* www . j a v a 2 s . c om*/ **/ private synchronized boolean connectSocket() { if (eiscpSocket == null || !connected || !eiscpSocket.isConnected()) { try { // Creating a socket to connect to the server eiscpSocket = new Socket(); // start connection tester if (connectionSupervisor == null) { connectionSupervisor = new ConnectionSupervisor(CONNECTION_TEST_INTERVAL); } eiscpSocket.connect(new InetSocketAddress(ip, port), CONNECTION_TIMEOUT); logger.debug("Connected to {}:{}", ip, port); // Get Input and Output streams outStream = new DataOutputStream(eiscpSocket.getOutputStream()); inStream = new DataInputStream(eiscpSocket.getInputStream()); eiscpSocket.setSoTimeout(SOCKET_TIMEOUT); outStream.flush(); connected = true; // start status update listener if (dataListener == null) { dataListener = new DataListener(); dataListener.start(); } } catch (UnknownHostException unknownHost) { logger.error("You are trying to connect to an unknown host: {}", unknownHost.getMessage()); } catch (IOException ioException) { logger.error("Can't connect: {}", ioException.getMessage()); } } return connected; }
From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java
/** * Callback from the OSGi <code>ConfigurationAdmin</code> on configuration * changes.//from w w w .j a va2s . co m * * @param properties * the configuration properties * @throws ConfigurationException * if configuration fails */ @Override public void updated(Dictionary properties) throws ConfigurationException { // Read the mail server properties mailProperties.clear(); // The mail host is mandatory String propName = getConfigurationKey(OPT_SMTP_HOST); mailHost = StringUtils.trimToNull((String) properties.get(propName)); if (mailHost == null) { mailHost = DEFAULT_SMTP_HOST; logger.debug("Mail server defaults to '{}'", mailHost); } else { logger.debug("Mail host is {}", mailHost); } mailProperties.put(getJavaMailSmtpKey(OPT_SMTP_HOST), mailHost); // Mail port propName = getConfigurationKey(OPT_SMTP_PORT); String mailPort = StringUtils.trimToNull((String) properties.get(propName)); if (mailPort == null) { mailPort = DEFAULT_SMTP_PORT; logger.debug("Mail server port defaults to '{}'", mailPort); } else { logger.debug("Mail server port is '{}'", mailPort); } mailProperties.put(getJavaMailSmtpKey(OPT_SMTP_PORT), mailPort); // TSL over SMTP support propName = getConfigurationKey(OPT_SMTP_TLS); String smtpStartTLSStr = StringUtils.trimToNull((String) properties.get(propName)); boolean smtpStartTLS = Boolean.parseBoolean(smtpStartTLSStr); if (smtpStartTLS) { mailProperties.put(getJavaMailSmtpKey(OPT_SMTP_TLS) + ".enable", "true"); logger.debug("TLS over SMTP is enabled"); } else { logger.debug("TLS over SMTP is disabled"); } // Mail user propName = getConfigurationKey(OPT_SMTP_USER); mailUser = StringUtils.trimToNull((String) properties.get(propName)); if (mailUser != null) { mailProperties.put(getJavaMailKey(OPT_SMTP_USER), mailUser); logger.debug("Mail user is '{}'", mailUser); } else { logger.debug("Sending mails to {} without authentication", mailHost); } // Mail password propName = getConfigurationKey(OPT_SMTP_PASSWORD); mailPassword = StringUtils.trimToNull((String) properties.get(propName)); if (mailPassword != null) { mailProperties.put(getJavaMailKey(OPT_SMTP_PASSWORD), mailPassword); logger.debug("Mail password set"); } // Mail sender propName = getConfigurationKey(OPT_SMTP_FROM); String mailFrom = StringUtils.trimToNull((String) properties.get(propName)); if (mailFrom == null) { try { mailFrom = "weblounge@" + InetAddress.getLocalHost().getCanonicalHostName(); logger.info("Mail sender defaults to '{}'", mailFrom); } catch (UnknownHostException e) { logger.error("Error retreiving localhost hostname used to create default sender address: {}", e.getMessage()); throw new ConfigurationException(OPT_SMTP_FROM, "Error retreiving localhost hostname used to create default sender address"); } } else { logger.debug("Mail sender is '{}'", mailFrom); } mailProperties.put(getJavaMailKey(OPT_SMTP_FROM), mailFrom); // Authentication propName = getConfigurationKey(OPT_SMTP_AUTH); mailProperties.put(getJavaMailSmtpKey(OPT_SMTP_AUTH), Boolean.toString(mailUser != null)); // Mail debugging propName = getConfigurationKey(OPT_SMTP_DEBUG); String mailDebug = StringUtils.trimToNull((String) properties.get(propName)); if (mailDebug != null) { boolean mailDebugEnabled = Boolean.parseBoolean(mailDebug); mailProperties.put(getJavaMailKey(OPT_SMTP_DEBUG), Boolean.toString(mailDebugEnabled)); logger.info("Mail debugging is {}", mailDebugEnabled ? "enabled" : "disabled"); } defaultMailSession = null; logger.info("Mail service configured with {}", mailHost); // Test propName = getConfigurationKey(OPT_SMTP_TEST); String mailTest = StringUtils.trimToNull((String) properties.get(propName)); if (mailTest != null) { try { sendTestMessage(mailTest); } catch (MessagingException e) { logger.error("Error sending test message to " + mailTest + ": " + e.getMessage()); throw new ConfigurationException(OPT_SMTP_PREFIX + MAIL_TRANSPORT + OPT_SMTP_HOST, "Failed to send test message to " + mailTest); } } }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {//from w ww. ja va 2 s .com DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:org.sipfoundry.preflight.ConsoleTestRunner.java
@SuppressWarnings("static-access") public void validate(String[] args) { InetAddress bindAddress = null; ResultCode results;/* w w w.j av a 2s . c o m*/ NetworkResources networkResources = new NetworkResources(); // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); Option verbose = OptionBuilder.withLongOpt("verbose") .withDescription("Enable verbose test progress output.").create('v'); Option dhcpTest = OptionBuilder.withLongOpt("dhcp-test") .withDescription( "Verify that the networks DHCP server is running and properly issuing IP addresses.") .create(); Option dnsTest = OptionBuilder.withLongOpt("dns-test").withDescription( "Verify that the DNS server(s) supplied by the DHCP server can properly resolve the given sip domain.") .withValueSeparator('=').hasArg().withArgName("realm").create(); Option ntpTest = OptionBuilder.withLongOpt("ntp-test").withDescription( "Verify that the NTP server(s) supplied by the DHCP server are properly servicing NTP time requests.") .withValueSeparator('=').hasOptionalArg().withArgName("server").create(); Option tftpTest = OptionBuilder.withLongOpt("tftp-test") .withDescription("Verify that the specified TFTP server is functioning properly.") .withValueSeparator('=').hasOptionalArg().withArgName("server").create(); Option ftpTest = OptionBuilder.withLongOpt("ftp-test") .withDescription("Verify that the specified FTP server is functioning properly.") .withValueSeparator('=').hasOptionalArg().withArgName("server").create(); Option httpTest = OptionBuilder.withLongOpt("http-test") .withDescription("Verify that the specified HTTP server is functioning properly.") .withValueSeparator('=').hasOptionalArg().withArgName("server").create(); Option sipTest = OptionBuilder.withLongOpt("120-test") .withDescription("Verify that DHCP server is properly issuing Option 120 addresses.").create(); Option testInterface = OptionBuilder.withLongOpt("interface") .withDescription("IP address of the interface that the tests should run over.") .withValueSeparator('=').hasArg().withArgName("address").create(); Option help = OptionBuilder.withLongOpt("help").withDescription("Display preflight usage documentation.") .create(); options.addOption(dhcpTest); options.addOption(dnsTest); options.addOption(ntpTest); options.addOption(tftpTest); options.addOption(ftpTest); options.addOption(httpTest); options.addOption(sipTest); options.addOption(verbose); options.addOption(testInterface); options.addOption(help); // Check that there is at least 1 argument. if (args.length < 1) { printHelp(options); System.exit(0); } try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { String helpText = "usage: preflight [-v, --verbose] [--dhcp-test] [--dns-test=<realm>] [--ntp-test]\n" + " [--tftp-test=<server>] [--ftp-test=<server] [--http-test <server>]" + "\n" + "Invoke preflight with one or more of the following test switches. Each test will\n" + "be run in the order specified. If a given test fails, the program will terminate,\n" + "returning an exit code specifying the error condition. The supported test switches\n" + "are:\n" + "\n" + "-v, --verbose Enable verbose test progress output.\n" + "\n" + "--dhcp-test Verify that the networks DHCP server is running and properly\n" + " issuing IP addresses. Possible error conditions:\n" + " 130: Timeout waiting for network response.\n" + " 133: Multiple DHCP servers detected.\n" + " 134: Unrecognized response received.\n" + " 135: DHCP DISCOVER was rejected.\n" + " 136: DHCP REQUEST was rejected.\n" + " 137: Missing mandatory DHCP configuration parameters.\n" + "\n" + "--dns-test=<sip domain> Verify that the DNS server(s) supplied by the DHCP server can\n" + " properly resolve the given sip domain. Possible error conditions:\n" + " 139: SRV target could not be resolved.\n" + " 140: SRV target is unreachable.\n" + " 141: Unable to resolve SIP domain.\n" + " 142: SIP domain is unreachable.\n" + " 143: DNS Server did not report any SRV records.\n" + "\n" + "--ntp-test Verify that the NTP server(s) supplied by the DHCP server are\n" + " properly servicing NTP time requests. Possible error conditions:\n" + " 144: No NTP servers available.\n" + " 146: NTP Server request failure.\n" + "\n" + "--tftp-test=<server> Verify that the specified TFTP server is functioning properly.\n" + " Possible error conditions:\n" + " 147: No TFTP server available.\n" + " 148: TFTP Server address is malformed.\n" + " 149: TFTP server address could not be resolved.\n" + " 150: Mismatch in DNS configuration server records.\n" + " 151: TFTP server is unreachable.\n" + " 152: TFTP client encountered unrecoverable error.\n" + " 153: TFTP get of test file failed.\n" + " 154: TFTP test file did not verify.\n" + "\n" + "--ftp-test=<server> Verify that the specified FTP server is functioning properly.\n" + " Possible error conditions:\n" + " 155: FTP Server address is malformed.\n" + " 156: FTP server address could not be resolved.\n" + " 157: FTP server is unreachable.\n" + " 158: FTP client encountered unrecoverable error.\n" + " 159: FTP get of test file failed.\n" + " 160: FTP test file did not verify.\n" + "\n" + "--http-test=<server> Verify that the specified HTTP server is functioning properly.\n" + " Possible error conditions:\n" + " 161: HTTP URL is malformed.\n" + " 162: HTTP server address could not be resolved.\n" + " 163: HTTP server is unreachable.\n" + " 164: HTTP client encountered unrecoverable error.\n" + " 165: HTTP get of test file failed.\n" + " 166: HTTP test file did not verify.\n" + "\n" + "--120-test Verify that the DHCP server is properly issuing\n" + " Option 120 addresses. Possible error conditions:\n" + " 167: No SIP servers supplied.\n" + " 168: No SIP server is reachable.\n" + "--interface=<address> IP address of the interface that the tests should run over.\n" + "\n"; System.out.println(helpText); System.exit(0); } if (line.hasOption("verbose")) { journalService.enable(); } else { journalService.disable(); } String interfaceAddress; if (line.hasOption("interface")) { interfaceAddress = line.getOptionValue("interface"); } else { interfaceAddress = "0.0.0.0"; } try { bindAddress = InetAddress.getByName(interfaceAddress); } catch (UnknownHostException e) { System.err.println(e.getMessage()); System.exit(-1); } // Always run the DHCP test first, regardless of what other tests are called for. DHCP dhcp = new DHCP(); results = dhcp.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } if (line.hasOption("dns-test")) { networkResources.sipDomainName = line.getOptionValue("dns-test"); DNS dns = new DNS(); results = dns.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } if (line.hasOption("ntp-test")) { NTP ntp = new NTP(); String ntpServer = line.getOptionValue("ntp-test"); if (ntpServer != null) { networkResources.ntpServers = new LinkedList<InetAddress>(); try { networkResources.ntpServers.add(InetAddress.getByName(ntpServer)); } catch (UnknownHostException e) { journalService.println("Invalid NTP server specified on command line."); networkResources.ntpServers = null; } } results = ntp.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } if (line.hasOption("tftp-test")) { TFTP tftp = new TFTP(); String configServer = line.getOptionValue("tftp-test"); if (configServer != null) { networkResources.configServer = configServer; } results = tftp.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } if (line.hasOption("ftp-test")) { FTP ftp = new FTP(); String configServer = line.getOptionValue("ftp-test"); if (configServer != null) { networkResources.configServer = configServer; } results = ftp.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } if (line.hasOption("http-test")) { HTTP http = new HTTP(); String configServer = line.getOptionValue("http-test"); if (configServer != null) { networkResources.configServer = configServer; } results = http.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } if (line.hasOption("120-test")) { SIPServerTest sipServerTest = new SIPServerTest(); results = sipServerTest.validate(10, networkResources, journalService, bindAddress); if (results != NONE) { System.err.println(results.toString()); System.exit(results.toInt()); } } } catch (ParseException exp) { System.out.println(exp.getMessage()); printHelp(options); System.exit(0); } }
From source file:de.steilerdev.myVerein.server.controller.init.InitController.java
License:asdf
/** * This function is validating the provided information of the MongoDB server, by establishing a test connection. * @param databaseHost The hostname of the MongoDB server. * @param databasePort The port of the MongoDB server. * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed). * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed). * @param databaseCollection The name of the database collection. * @return True if the connection was successfully established, false otherwise. *//* ww w.ja v a 2s.c o m*/ private boolean mongoIsAvailable(String databaseHost, int databasePort, String databaseUser, String databasePassword, String databaseCollection) { logger.trace("Testing MongoDB connection"); if (!databaseUser.isEmpty() && !databasePassword.isEmpty()) { logger.debug("Credentials have been provided"); mongoCredential = Arrays.asList(MongoCredential.createMongoCRCredential(databaseUser, databaseCollection, databasePassword.toCharArray())); } try { logger.debug("Creating server address"); mongoAddress = new ServerAddress(databaseHost, databasePort); } catch (UnknownHostException e) { logger.warn("Unable to resolve server host: " + e.getMessage()); return false; } logger.debug("Creating mongo client"); MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential); try { //Checking if connection REALLY works logger.debug("Establishing connection now."); List<String> databases = mongoClient.getDatabaseNames(); if (databases == null) { logger.warn("The returned list of databases is null"); return false; } else if (databases.isEmpty()) { logger.info("The databases are empty"); return true; } else { logger.debug("The database connection seems okay"); return true; } } catch (MongoException e) { logger.warn("Unable to receive list of present databases: " + e.getMessage()); return false; } finally { logger.debug("Closing mongo client"); mongoClient.close(); } }
From source file:org.artifactory.config.CentralConfigServiceImpl.java
private void setDescriptor(CentralConfigDescriptor descriptor, boolean save) { log.trace("Setting central config descriptor for config #{}.", System.identityHashCode(this)); if (save) {//from w ww . jav a 2s . c o m assertSaveDescriptorAllowd(); // call the interceptors before saving the new descriptor interceptors.onBeforeSave(descriptor); } this.descriptor = descriptor; checkUniqueProxies(); //Create the date formatter String dateFormat = descriptor.getDateFormat(); dateFormatter = DateTimeFormat.forPattern(dateFormat); //Get the server name serverName = descriptor.getServerName(); if (serverName == null) { log.debug("No custom server name in configuration. Using hostname instead."); try { serverName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.warn("Could not use local hostname as the server instance id: {}", e.getMessage()); serverName = "localhost"; } } if (save) { log.info("Saving new configuration in storage..."); String configString = JaxbHelper.toXml(descriptor); configsService.addOrUpdateConfig(ArtifactoryHome.ARTIFACTORY_CONFIG_FILE, configString); log.info("New configuration saved."); } }
From source file:org.apache.usergrid.persistence.actorsystem.ActorSystemManagerImpl.java
/** * Init Akka ActorSystems and wait for request actors to start. *//*from w ww.ja v a 2 s. co m*/ @Override public void start() { if (!StringUtils.isEmpty(actorSystemFig.getHostname())) { this.hostname = actorSystemFig.getHostname(); } else { try { this.hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.error("Cannot get hostname, defaulting to 'localhost': " + e.getMessage()); } } this.currentRegion = actorSystemFig.getRegionLocal(); this.port = null; initAkka(); waitForClientActor(); }
From source file:com.youzu.android.framework.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }/*from w w w . j a v a 2s. c om*/ if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { // ResponseInfo<T> responseInfo = null; // if (!isCancelled()) { // HttpResponse response = client.execute(request, context); // responseInfo = handleResponse(response); //// CookieStore store = client.getCookieStore(); // } // return responseInfo; requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseInfo<T>(null, (T) result, true); } } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { Log.e("APP", "HttpHandler sendRequest UnknownHostException:" + e.getMessage()); exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { Log.e("APP", "HttpHandler sendRequest IOException: " + e.toString()); exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { Log.e("APP", "HttpHandler sendRequest NullPointerException:" + e.getMessage()); exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { Log.e("APP", "HttpHandler sendRequest HttpException:" + e.getMessage()); throw e; } catch (Throwable e) { Log.e("APP", "HttpHandler sendRequest Throwable:" + e.getMessage()); exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } Log.e("APP", "retry:" + retry); if (!retry) { HttpException httpException = new HttpException(exception); Log.e("APP", "HttpHandler sendRequest HttpException:" + httpException.getMessage()); // callback.onFailure(httpException,httpException.getMessage()); throw httpException; } } }
From source file:sos.util.SOSHttpPost.java
private void sendFile(File inputFile, String outputFile) throws Exception { this.log_info("sending " + inputFile.getCanonicalPath() + " ..."); int responseCode = -1; try {//from w w w . j a va2 s. c o m String suffix = null; String contentType = null; if (inputFile.getName().lastIndexOf('.') != -1) { suffix = inputFile.getName().substring(inputFile.getName().lastIndexOf('.') + 1); if (suffix.equals("htm") || suffix.equals("html")) contentType = "text/html"; if (suffix.equals("xml")) contentType = "text/xml"; } // encoding ermitteln if (contentType != null) if (contentType.equals("text/html") || contentType.equals("text/xml")) { BufferedReader br = new BufferedReader(new FileReader(inputFile)); String buffer = ""; String line = null; int c = 0; // die ersten 5 Zeilen nach einem encoding durchsuchen while ((line = br.readLine()) != null || ++c > 5) buffer += line; Pattern p = Pattern.compile("encoding[\\s]*=[\\s]*['\"](.*?)['\"]", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(buffer); if (m.find()) contentType += "; charset=" + m.group(1); br.close(); } if (contentType == null) contentType = "text/plain"; PostMethod post = new PostMethod(this.targetURL); post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(inputFile), inputFile.length())); post.setRequestHeader("Content-Type", contentType); //post.setFollowRedirects(true); HttpClient httpClient = new HttpClient(); responseCode = httpClient.executeMethod(post); // Response Code berprfen // codes 200 - 399 gehen durch if (responseCode < 200 || responseCode >= 400) throw new HttpException(this.targetURL.toString() + " returns " + post.getStatusLine().toString()); // response String writeMsg = ""; if (outputFile != null) writeMsg = this.writeResponse(post.getResponseBodyAsStream(), outputFile); // abschlieende Meldung this.log_info(inputFile.getCanonicalPath() + " sent" + writeMsg); } catch (UnknownHostException uhx) { throw new Exception("UnknownHostException: " + uhx.getMessage()); } catch (FileNotFoundException nfx) { throw new Exception("FileNotFoundException: " + nfx.getMessage()); } catch (HttpException htx) { throw new Exception("HttpException: " + htx.getMessage()); } catch (IOException iox) { throw new Exception("IOException: " + iox.getMessage()); } }