List of usage examples for java.net UnknownHostException getMessage
public String getMessage()
From source file:com.abiquo.nodecollector.domain.collectors.HyperVCollector.java
/** * Gets the physical state of the node./*from www .j a v a 2 s. c o m*/ * * @throws CollectorException When the Node Collector cannot connect to the Hypervisor. * @throws NoManagedException if the HyperV is running but not prepared for manage with abicloud */ public void checkPhysicalState() throws CollectorException, NoManagedException { try { URL urlAddress = new URL("http://" + getIpAddress()); SWbemLocator loc = new SWbemLocator(); final WsmanCollector wsmanColl = new WsmanCollectorImpl(hyperVuser, hyperVpassword, 5985); wsmanColl.pingWsmanService(urlAddress.getHost()); virtService = loc.connect(urlAddress.getHost(), "127.0.0.1", HyperVConstants.VIRTUALIZATION_NS, hyperVuser, hyperVpassword); List<IJIDispatch> results = HyperVUtils .execQuery("Select * from Msvm_ComputerSystem where Name = ElementName", virtService); if (results == null || results.isEmpty()) { // State is PROVISIONED throw new CollectorException(MessageValues.HYP_CONN_EXCP); } IJIDispatch dispatch = results.get(0); int rawState = dispatch.get("EnabledState").getObjectAsInt(); HyperVState state = HyperVState.fromValue(rawState); if (state != HyperVState.POWER_ON) { // State is PROVISIONED throw new CollectorException(MessageValues.HYP_CONN_EXCP); } } catch (JIException ex) { throw new CollectorException(MessageValues.COLL_EXCP_DC, ex); } catch (UnknownHostException e) { throw new CollectorException(MessageValues.HYP_CONN_EXCP, e); } catch (MalformedURLException e) { throw new CollectorException(MessageValues.COLL_EXCP_DC, e); } catch (WsmanException e) { throw new NoManagedException(e.getMessage(), e); } }
From source file:com.mobilyzer.util.PhoneUtils.java
/** * Use MLabNS slices to check IPv4/IPv6 domain name resolvable * @param ip_detect_type -- "ipv4" or "ipv6" * @return DN_UNRESOLVABLE, DN_RESOLVABLE *///from w w w .j a v a 2s. co m private int checkDomainNameResolvable(String ip_detect_type) { if (!ip_detect_type.equals("ipv4") && !ip_detect_type.equals("ipv6")) { return DN_UNKNOWN; } try { ArrayList<String> ipAddressList = MLabNS.Lookup(context, "mobiperf", ip_detect_type, "fqdn"); String ipAddress; // MLabNS returns one fqdn each time if (ipAddressList.size() == 1) { ipAddress = ipAddressList.get(0); } else { return DN_UNKNOWN; } InetAddress inet = InetAddress.getByName(ipAddress); if (inet != null) return DN_RESOLVABLE; } catch (UnknownHostException e) { // Fail to resolve domain name Logger.e("UnknownHostException in checkDomainNameResolvable() " + e.getMessage()); return DN_UNRESOLVABLE; } catch (InvalidParameterException e) { // MLabNS service lookup fail Logger.e("InvalidParameterException in checkIPCompatibility(). " + e.getMessage()); return DN_UNRESOLVABLE; } catch (Exception e) { // "catch-all" Logger.e("Unexpected Exception: " + e.getMessage()); return DN_UNRESOLVABLE; } return DN_UNKNOWN; }
From source file:com.microsoft.azure.remote.AzureVMAgentSSHLauncher.java
@Override public void launch(final SlaveComputer agentComputer, final TaskListener listener) { if (agentComputer == null || !(agentComputer instanceof AzureVMComputer)) { LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: AgentComputer is invalid {0}", agentComputer); return;//from w w w .j a va 2s.c o m } AzureVMComputer computer = (AzureVMComputer) agentComputer; AzureVMAgent agent = computer.getNode(); if (agent == null) { LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: Agent Node is null"); return; } LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: launch method called for agent {0}", computer.getName()); // Check if VM is already stopped or stopping or getting deleted , if yes then there is no point in trying to connect // Added this check - since after restarting jenkins master, jenkins is trying to connect to all the agents although agents are suspended. // This still means that a delete agent will eventually get cleaned up. try { if (!agent.isVMAliveOrHealthy()) { LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: Agent {0} is shut down, deleted, etc. Not attempting to connect", computer.getName()); return; } } catch (Exception e1) { // ignoring exception purposefully } // Block cleanup while we attempt to start. agent.blockCleanUpAction(); PrintStream logger = listener.getLogger(); boolean successful = false; Session session = null; try { session = connectToSsh(agent); } catch (UnknownHostException e) { LOGGER.log(Level.SEVERE, "AzureVMAgentSSHLauncher: launch: " + "Got unknown host exception. Virtual machine might have been deleted already", e); } catch (ConnectException e) { LOGGER.log(Level.SEVERE, "AzureVMAgentSSHLauncher: launch: Got connect exception. Might be due to firewall rules", e); handleLaunchFailure(agent, Constants.AGENT_POST_PROV_CONN_FAIL); } catch (Exception e) { // Checking if we need to mark template as disabled. Need to re-visit this logic based on tests. if (e.getMessage() != null && e.getMessage().equalsIgnoreCase("Auth fail")) { LOGGER.log(Level.SEVERE, "AzureVMAgentSSHLauncher: launch: " + "Authentication failure. Image may not be supporting password authentication", e); handleLaunchFailure(agent, Constants.AGENT_POST_PROV_AUTH_FAIL); } else { LOGGER.log(Level.SEVERE, "AzureVMAgentSSHLauncher: launch: Got exception", e); handleLaunchFailure(agent, Constants.AGENT_POST_PROV_CONN_FAIL + e.getMessage()); } } finally { if (session == null) { agent.getComputer().setAcceptingTasks(false); agent.setCleanUpAction(CleanUpAction.DELETE, Messages._Agent_Failed_To_Connect()); return; } } Localizable cleanUpReason = null; try { final Session cleanupSession = session; String initScript = agent.getInitScript(); // Executing script only if script is not executed even once if (StringUtils.isNotBlank(initScript) && executeRemoteCommand(session, "test -e ~/.azure-agent-init", logger) != 0) { LOGGER.info( "AzureVMAgentSSHLauncher: launch: Init script is not null, preparing to execute script remotely"); copyFileToRemote(session, new ByteArrayInputStream(initScript.getBytes("UTF-8")), remoteInitFileName); // Execute initialization script // Make sure to change file permission for execute if needed. TODO: need to test // Grab the username/pass StandardUsernamePasswordCredentials creds = AzureUtil.getCredentials(agent.getVMCredentialsId()); String command = "sh " + remoteInitFileName; int exitStatus = executeRemoteCommand(session, command, logger, agent.getExecuteInitScriptAsRoot(), creds.getPassword().getPlainText()); if (exitStatus != 0) { if (agent.getDoNotUseMachineIfInitFails()) { LOGGER.log(Level.SEVERE, "AzureVMAgentSSHLauncher: launch: init script failed: exit code={0} (marking agent for deletion)", exitStatus); cleanUpReason = Messages._Agent_Failed_Init_Script(); return; } else { LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: init script failed: exit code={0} (ignoring)", exitStatus); } } else { LOGGER.info("AzureVMAgentSSHLauncher: launch: init script got executed successfully"); } /* Create a new session after the init script has executed to * make sure we pick up whatever new settings have been set up * for our user * * https://issues.jenkins-ci.org/browse/JENKINS-40291 */ session.disconnect(); session = connectToSsh(agent); // Create tracking file executeRemoteCommand(session, "touch ~/.azure-agent-init", logger); } LOGGER.info("AzureVMAgentSSHLauncher: launch: checking for java runtime"); if (executeRemoteCommand(session, "java -fullversion", logger) != 0) { LOGGER.info("AzureVMAgentSSHLauncher: launch: Java not found. " + "At a minimum init script should ensure that java runtime is installed"); handleLaunchFailure(agent, Constants.AGENT_POST_PROV_JAVA_NOT_FOUND); return; } LOGGER.info("AzureVMAgentSSHLauncher: launch: java runtime present, copying slave.jar to remote"); InputStream inputStream = new ByteArrayInputStream( Jenkins.getInstance().getJnlpJars("slave.jar").readFully()); copyFileToRemote(session, inputStream, "slave.jar"); String jvmopts = agent.getJvmOptions(); String execCommand = "java " + (StringUtils.isNotBlank(jvmopts) ? jvmopts : "") + " -jar slave.jar"; LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: launching agent: {0}", execCommand); final ChannelExec jschChannel = (ChannelExec) session.openChannel("exec"); jschChannel.setCommand(execCommand); jschChannel.connect(); LOGGER.info("AzureVMAgentSSHLauncher: launch: Connected successfully"); computer.setChannel(jschChannel.getInputStream(), jschChannel.getOutputStream(), logger, new Listener() { @Override public void onClosed(Channel channel, IOException cause) { if (jschChannel != null) { jschChannel.disconnect(); } if (cleanupSession != null) { cleanupSession.disconnect(); } } }); LOGGER.info("AzureVMAgentSSHLauncher: launch: launched agent successfully"); // There's a chance that it was marked as delete (for instance, if the node // was unreachable and then someone hit connect and it worked. Reset the node cleanup // state to the default for the node. agent.clearCleanUpAction(); successful = true; } catch (Exception e) { LOGGER.log(Level.INFO, "AzureVMAgentSSHLauncher: launch: got exception ", e); } finally { if (!successful) { session.disconnect(); if (cleanUpReason == null) { cleanUpReason = Messages._Agent_Failed_To_Connect(); } agent.getComputer().setAcceptingTasks(false); // Set the machine to be deleted by the cleanup task agent.setCleanUpAction(CleanUpAction.DELETE, cleanUpReason); } } }
From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java
/** * @return/*from www . ja v a 2 s.co m*/ */ private DB getMongoDBConnection() throws StoringException { MongoClient mongoClient = null; DB database = null; try { MongoClientURI uri = null; if (!_userName.equalsIgnoreCase(EMPTY) && !_password.equalsIgnoreCase(EMPTY)) { uri = new MongoClientURI("mongodb://" + _userName + ":" + _password + "@" + _hostName + ":" + _port + "/?authSource=" + _databaseName); } else { uri = new MongoClientURI("mongodb://" + _hostName + ":" + _port); } mongoClient = new MongoClient(uri); database = mongoClient.getDB(_databaseName); } catch (UnknownHostException e) { throw new StoringException(e.getMessage()); } catch (CommandFailureException e) { if (e.getCode() == 18) { throw new StoringException("Authentication Exception:Invalid Credentials"); } else { throw new StoringException(e.getMessage()); } } catch (Exception e) { throw new StoringException(e.getMessage()); } return database; }
From source file:cn.caimatou.canting.utils.http.asynchttp.AsyncHttpRequest.java
private void makeRequestWithRetries() throws ConnectException { // This is an additional layer of retry logic lifted from droid-fu // See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java boolean retry = true; IOException cause = null;/*from w ww. ja va 2 s.c o m*/ HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "can't resolve host"); } return; } catch (SocketException e) { // Added to detect host unreachable if (responseHandler != null) { responseHandler.sendFailureMessage(e, "can't resolve host"); } return; } catch (SocketTimeoutException e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, "socket time out"); } return; } catch (IOException e) { cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { // there's a bug in HttpClient 4.0.x that on some occasions causes // DefaultRequestExecutor to throw an NPE, see // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient" + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } } // no retries left, crap out with exception ConnectException ex = new ConnectException(); ex.initCause(cause); throw ex; }
From source file:zsk.YTDownloadThread.java
boolean downloadone(String sURL) { boolean rc = false; boolean rc204 = false; boolean rc302 = false; this.iRecursionCount++; // stop recursion try {/*from w w w . j av a2 s . c om*/ if (sURL.equals("")) return (false); } catch (NullPointerException npe) { return (false); } if (JFCMainClient.getbQuitrequested()) return (false); // try to get information about application shutdown debugoutput("start."); // TODO GUI option for proxy? // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube // using local squid to save download time for tests try { // determine http_proxy environment variable if (!this.getProxy().equals("")) { String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", ""); this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""), Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http"); SchemeRegistry supportedSchemes = new SchemeRegistry(); supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); ClientConnectionManager ccm = new PoolingClientConnectionManager(supportedSchemes); // with proxy this.httpclient = new DefaultHttpClient(ccm, params); this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } else { // without proxy this.httpclient = new DefaultHttpClient(); this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); } this.httpget = new HttpGet(getURI(sURL)); if (sURL.toLowerCase().startsWith("https")) this.target = new HttpHost(getHost(sURL), 443, "https"); else this.target = new HttpHost(getHost(sURL), 80, "http"); } catch (Exception e) { debugoutput(e.getMessage()); } debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString())); debugoutput("uri: ".concat(this.httpget.getURI().toString())); debugoutput("host: ".concat(this.target.getHostName())); debugoutput("using proxy: ".concat(this.getProxy())); // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work) /* this.localContext = new BasicHttpContext(); if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context) ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient */ // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again? try { this.response = this.httpclient.execute(this.target, this.httpget, this.localContext); } catch (ClientProtocolException cpe) { debugoutput(cpe.getMessage()); } catch (UnknownHostException uhe) { output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ") .concat(uhe.getMessage())); debugoutput(uhe.getMessage()); } catch (IOException ioe) { debugoutput(ioe.getMessage()); } catch (IllegalStateException ise) { debugoutput(ise.getMessage()); } /* CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN); CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC); CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ; try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( ))); } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute try { debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString())); debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString())); debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString())); } catch (NullPointerException npe) { } */ try { debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString())); //for (int i = 0; i < response.getAllHeaders().length; i++) { // debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue())); //} // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL? if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)")) & !(rc204 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)204(.*)")) & !(rc302 = this.response.getStatusLine().toString().toLowerCase() .matches("^(http)(.*)302(.*)"))) { debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL)); output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\"")); return (rc & rc204 & rc302); } if (rc204) { debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID())); rc = downloadone(this.vNextVideoURL.get(0).getsURL()); return (rc); } if (rc302) debugoutput( "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString())); } catch (NullPointerException npe) { // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because // response.getStatusLine() == null this.sVideoURL = null; } HttpEntity entity = null; try { entity = this.response.getEntity(); } catch (NullPointerException npe) { } // try to read HTTP response body if (entity != null) { try { if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)")) this.textreader = new BufferedReader(new InputStreamReader(entity.getContent())); else this.binaryreader = new BufferedInputStream(entity.getContent()); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { // test if we got a webpage this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase(); if (this.sContentType.matches("^text/html(.*)")) { rc = savetextdata(); // test if we got the binary content } else if (this.sContentType.matches("video/(.)*")) { if (JFCMainClient.getbNODOWNLOAD()) reportheaderinfo(); else savebinarydata(); } else { // content-type is not video/ rc = false; this.sVideoURL = null; } } catch (IOException ex) { try { throw ex; } catch (IOException e) { e.printStackTrace(); } } catch (RuntimeException ex) { try { throw ex; } catch (Exception e) { e.printStackTrace(); } } } //if (entity != null) this.httpclient.getConnectionManager().shutdown(); debugoutput("done: ".concat(sURL)); if (this.sVideoURL == null) this.sVideoURL = ""; // to prevent NPE if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) { // no more recursion - html source hase been read // test !rc than video could not downloaded because of some error (like wrong protocol or restriction) if (!rc) { debugoutput("cannot download video - URL does not seem to be valid or could not be found: " .concat(this.sURL)); output(JFCMainClient.isgerman() ? "es gab ein Problem die Video URL zu finden! evt. wegen Landesinschrnkung?!" : "there was a problem getting the video URL! perhaps not allowed in your country?!"); output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!" : "consider reporting the URL to author! - ").concat(this.sURL)); this.sVideoURL = null; } } else { // enter recursion - download video resource debugoutput("try to download video from URL: ".concat(this.sVideoURL)); rc = downloadone(this.sVideoURL); } this.sVideoURL = null; return (rc); }
From source file:ubic.gemma.loader.util.fetcher.FtpFetcher.java
/** * @param identifier/*from www.j a va 2 s .c o m*/ * @param seekFile * @return */ protected Collection<LocalFile> fetch(String identifier, String seekFile) { File existingFile = null; try { File newDir = mkdir(identifier); String outputFileName = formLocalFilePath(identifier, newDir); existingFile = new File(outputFileName); if (this.avoidDownload || (existingFile.canRead() && allowUseExisting)) { // log.info( outputFileName + " already exists." ); } if (ftpClient == null || !ftpClient.isConnected()) { ftpClient = this.getNetDataSourceUtil().connect(FTP.BINARY_FILE_TYPE); assert ftpClient != null; // otherwise should have gotten an exception from connect() } long expectedSize = getExpectedSize(seekFile); FutureTask<Boolean> future = this.defineTask(outputFileName, seekFile); Collection<LocalFile> result = this.doTask(future, expectedSize, seekFile, outputFileName); return result; } catch (UnknownHostException e) { if (force || !allowUseExisting || existingFile == null) throw new RuntimeException(e); if (!avoidDownload) throw new RuntimeException(e); log.warn("Could not connect to " + this.getNetDataSourceUtil().getHost() + " to check size of " + seekFile + ", using existing file"); Collection<LocalFile> fallback = getExistingFile(existingFile, seekFile); return fallback; } catch (IOException e) { /* * Note: this block can trigger if you cancel. */ if (force || !allowUseExisting || existingFile == null) { /* * Printing to log here because runtime error does not deliver message when passed through * java.util.concurrent.FutureTask (only throws InterruptedException and ExecutionException) */ log.error("Runtime exception thrown: " + e.getMessage() + ". \n Stack trace follows:", e); throw new RuntimeException( "Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server and permissions are granted.", e); } if (Thread.currentThread().isInterrupted()) { throw new CancellationException(); } log.warn("Cancelled, or couldn't fetch " + seekFile + ", make sure the file exists on the remote server.," + e + ", using existing file"); Collection<LocalFile> fallback = getExistingFile(existingFile, seekFile); return fallback; } finally { try { if (ftpClient != null && ftpClient.isConnected()) ftpClient.disconnect(); } catch (IOException e) { throw new RuntimeException("Could not disconnect: " + e.getMessage()); } } }
From source file:act.installer.reachablesexplorer.Loader.java
/** * Constructor for Loader. Instantiates connexions to Mongo databases * and Virtuoso triple store (Pubchem synonyms only) * @param host The host for the target Reachables MongoDB * @param port The port for the target Reachables MongoDB * @param targetDB The database for the target Reachables MongoDB * @param targetCollection The collection for the target Reachables MongoDB * @param targetSequenceCollection The collection for the target SequenceData MongoDB * @param renderingCache A directory where rendered images should live *///from w ww .j a v a 2 s . com public Loader(String host, Integer port, String sourceDB, String targetDB, String targetCollection, String targetSequenceCollection, String renderingCache) { // when the caller does not intend to touch the sourceDB, it can pass null as a param and we // won't setup a "source" connection. Creating a connection with "dummy" params leads mongod // to create (!) those dummy collections, mucking up our database with empty dbs/collections if (sourceDB != null) { sourceDBconn = new MongoDB(host, port, sourceDB); wordCloudGenerator = new WordCloudGenerator(host, port, sourceDB, renderingCache); } pubchemSynonymsDriver = new PubchemMeshSynonyms(); moleculeRenderer = new MoleculeRenderer(new File(renderingCache)); MongoClient mongoClient; try { mongoClient = new MongoClient(new ServerAddress(host, port)); } catch (UnknownHostException e) { LOGGER.error( "Connection to MongoClient failed. Please double check the target database's host and port."); throw new RuntimeException(e); } DB reachables = mongoClient.getDB(targetDB); // TODO: this unsafe initialization does not belong in the constructor. try { calculator = new PhysiochemicalPropertiesCalculator.Factory().build(); } catch (PluginException e) { LOGGER.error("Unable to initialize physiochemical calculator: %s", e.getMessage()); throw new RuntimeException(e); } if (targetCollection != null) { jacksonReachablesCollection = JacksonDBCollection.wrap(reachables.getCollection(targetCollection), Reachable.class, String.class); jacksonReachablesCollection.ensureIndex(new BasicDBObject(Reachable.INCHI_FIELD_NAME, "hashed")); } if (targetSequenceCollection != null) { jacksonSequenceCollection = JacksonDBCollection.wrap(reachables.getCollection(targetSequenceCollection), SequenceData.class, String.class); jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.SEQUENCE_FIELD_NAME, "hashed")); jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.ORGANISM_FIELD_NAME, 1)); } }
From source file:eu.stratosphere.nephele.taskmanager.TaskManager.java
/** * Constructs a new task manager, starts its IPC service and attempts to discover the job manager to * receive an initial configuration. All parameters are obtained from the * {@link GlobalConfiguration}, which must be loaded prior to instantiating the task manager. *///w w w. ja v a 2s. co m public TaskManager() throws Exception { LOG.info("TaskManager started as user " + UserGroupInformation.getCurrentUser().getShortUserName()); LOG.info("User system property: " + System.getProperty("user.name")); // IMPORTANT! At this point, the GlobalConfiguration must have been read! final InetSocketAddress jobManagerAddress; { LOG.info("Reading location of job manager from configuration"); final String address = GlobalConfiguration.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, null); final int port = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT); if (address == null) { throw new Exception("Job manager address not configured in the GlobalConfiguration."); } // Try to convert configured address to {@link InetAddress} try { final InetAddress tmpAddress = InetAddress.getByName(address); jobManagerAddress = new InetSocketAddress(tmpAddress, port); } catch (UnknownHostException e) { LOG.fatal("Could not resolve JobManager host name."); throw new Exception("Could not resolve JobManager host name: " + e.getMessage(), e); } LOG.info("Connecting to JobManager at: " + jobManagerAddress); } // Create RPC connection to the JobManager try { this.jobManager = RPC.getProxy(JobManagerProtocol.class, jobManagerAddress, NetUtils.getSocketFactory()); } catch (IOException e) { LOG.fatal("Could not connect to the JobManager: " + e.getMessage(), e); throw new Exception("Failed to initialize connection to JobManager: " + e.getMessage(), e); } int ipcPort = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_IPC_PORT_KEY, -1); int dataPort = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_DATA_PORT_KEY, -1); if (ipcPort == -1) { ipcPort = getAvailablePort(); } if (dataPort == -1) { dataPort = getAvailablePort(); } // Determine our own public facing address and start the server { final InetAddress taskManagerAddress; try { taskManagerAddress = getTaskManagerAddress(jobManagerAddress); } catch (Exception e) { throw new RuntimeException("The TaskManager failed to determine its own network address.", e); } this.localInstanceConnectionInfo = new InstanceConnectionInfo(taskManagerAddress, ipcPort, dataPort); LOG.info("TaskManager connection information:" + this.localInstanceConnectionInfo); // Start local RPC server try { this.taskManagerServer = RPC.getServer(this, taskManagerAddress.getHostAddress(), ipcPort, IPC_HANDLER_COUNT); this.taskManagerServer.start(); } catch (IOException e) { LOG.fatal("Failed to start TaskManager server. " + e.getMessage(), e); throw new Exception("Failed to start taskmanager server. " + e.getMessage(), e); } } // Try to create local stub of the global input split provider try { this.globalInputSplitProvider = RPC.getProxy(InputSplitProviderProtocol.class, jobManagerAddress, NetUtils.getSocketFactory()); } catch (IOException e) { LOG.fatal(e.getMessage(), e); throw new Exception("Failed to initialize connection to global input split provider: " + e.getMessage(), e); } // Try to create local stub for the lookup service try { this.lookupService = RPC.getProxy(ChannelLookupProtocol.class, jobManagerAddress, NetUtils.getSocketFactory()); } catch (IOException e) { LOG.fatal(e.getMessage(), e); throw new Exception("Failed to initialize channel lookup protocol. " + e.getMessage(), e); } // Try to create local stub for the accumulators try { this.accumulatorProtocolProxy = RPC.getProxy(AccumulatorProtocol.class, jobManagerAddress, NetUtils.getSocketFactory()); } catch (IOException e) { LOG.fatal("Failed to initialize accumulator protocol: " + e.getMessage(), e); throw new Exception("Failed to initialize accumulator protocol: " + e.getMessage(), e); } // Load profiler if it should be used if (GlobalConfiguration.getBoolean(ProfilingUtils.ENABLE_PROFILING_KEY, false)) { final String profilerClassName = GlobalConfiguration.getString(ProfilingUtils.TASKMANAGER_CLASSNAME_KEY, "eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl"); this.profiler = ProfilingUtils.loadTaskManagerProfiler(profilerClassName, jobManagerAddress.getAddress(), this.localInstanceConnectionInfo); if (this.profiler == null) { LOG.error("Cannot find class name for the profiler."); } else { LOG.info("Profiling of jobs is enabled."); } } else { this.profiler = null; LOG.info("Profiling of jobs is disabled."); } // Get the directory for storing temporary files final String[] tmpDirPaths = GlobalConfiguration .getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH) .split(",|" + File.pathSeparator); checkTempDirs(tmpDirPaths); final int pageSize = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETWORK_BUFFER_SIZE_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_NETWORK_BUFFER_SIZE); // Initialize network buffer pool int numBuffers = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETWORK_NUM_BUFFERS_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_NETWORK_NUM_BUFFERS); int bufferSize = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETWORK_BUFFER_SIZE_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_NETWORK_BUFFER_SIZE); int numInThreads = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETTY_NUM_IN_THREADS_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_NETTY_NUM_IN_THREADS); int numOutThreads = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETTY_NUM_OUT_THREADS_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_NETTY_NUM_OUT_THREADS); int lowWaterMark = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETTY_LOW_WATER_MARK, ConfigConstants.DEFAULT_TASK_MANAGER_NETTY_LOW_WATER_MARK); int highWaterMark = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_NETTY_HIGH_WATER_MARK, ConfigConstants.DEFAULT_TASK_MANAGER_NETTY_HIGH_WATER_MARK); // Initialize the channel manager try { this.channelManager = new ChannelManager(this.lookupService, this.localInstanceConnectionInfo, numBuffers, bufferSize, numInThreads, numOutThreads, lowWaterMark, highWaterMark); } catch (IOException ioe) { LOG.error(StringUtils.stringifyException(ioe)); throw new Exception("Failed to instantiate Byte-buffered channel manager. " + ioe.getMessage(), ioe); } { HardwareDescription resources = HardwareDescriptionFactory.extractFromSystem(); // Check whether the memory size has been explicitly configured. if so that overrides the default mechanism // of taking as much as is mentioned in the hardware description long memorySize = GlobalConfiguration.getInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, -1); if (memorySize > 0) { // manually configured memory size. override the value in the hardware config resources = HardwareDescriptionFactory.construct(resources.getNumberOfCPUCores(), resources.getSizeOfPhysicalMemory(), memorySize * 1024L * 1024L); } this.hardwareDescription = resources; // Initialize the memory manager LOG.info("Initializing memory manager with " + (resources.getSizeOfFreeMemory() >>> 20) + " megabytes of memory. " + "Page size is " + pageSize + " bytes."); try { @SuppressWarnings("unused") final boolean lazyAllocation = GlobalConfiguration.getBoolean( ConfigConstants.TASK_MANAGER_MEMORY_LAZY_ALLOCATION_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_MEMORY_LAZY_ALLOCATION); this.memoryManager = new DefaultMemoryManager(resources.getSizeOfFreeMemory(), pageSize); } catch (Throwable t) { LOG.fatal("Unable to initialize memory manager with " + (resources.getSizeOfFreeMemory() >>> 20) + " megabytes of memory.", t); throw new Exception("Unable to initialize memory manager.", t); } } this.ioManager = new IOManager(tmpDirPaths); this.heartbeatThread = new Thread() { @Override public void run() { runHeartbeatLoop(); } }; this.heartbeatThread.setName("Heartbeat Thread"); this.heartbeatThread.start(); }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public boolean connect() { connection = null;/*from www. j a va 2 s .c o m*/ ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory(); String ip = null; try { ip = Inet4Address.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.severe("Unable to get localhost IP address."); } Connection connectiontmp = null; try { connectiontmp = connectionFactory.createConnection(); String url = ""; if (Jenkins.getInstance() != null) { url = Jenkins.getInstance().getRootUrl(); } connectiontmp.setClientID(provider.getName() + "_" + url + "_" + ip + "_" + jobname); connectiontmp.start(); } catch (JMSException e) { log.severe("Unable to connect to " + provider.getBroker() + " " + e.getMessage()); return false; } log.info("Connection started"); connection = connectiontmp; return true; }