List of usage examples for java.net UnknownHostException getMessage
public String getMessage()
From source file:com.qk.applibrary.http.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 www. j a v a 2 s. co 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); } catch (Exception e) { if (responseHandler != null) { responseHandler.sendFailureMessage(e, e.getMessage()); } return; } } // no retries left, crap out with exception ConnectException ex = new ConnectException(); ex.initCause(cause); throw ex; }
From source file:org.openmrs.api.impl.AdministrationServiceImpl.java
/** * @see org.openmrs.api.AdministrationService#getSystemVariables() */// ww w . j a v a 2 s . com @Transactional(readOnly = true) public SortedMap<String, String> getSystemVariables() throws APIException { if (systemVariables == null) { systemVariables = new TreeMap<String, String>(); // Added the server's fully qualified domain name try { systemVariables.put("OPENMRS_HOSTNAME", InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { systemVariables.put("OPENMRS_HOSTNAME", "Unknown host: " + e.getMessage()); } systemVariables.put("OPENMRS_VERSION", String.valueOf(OpenmrsConstants.OPENMRS_VERSION)); systemVariables.put("DATABASE_NAME", OpenmrsConstants.DATABASE_NAME); systemVariables.put("DATABASE_BUSINESS_NAME", OpenmrsConstants.DATABASE_BUSINESS_NAME); systemVariables.put("OBSCURE_PATIENTS", String.valueOf(OpenmrsConstants.OBSCURE_PATIENTS)); systemVariables.put("OBSCURE_PATIENTS_FAMILY_NAME", OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME); systemVariables.put("OBSCURE_PATIENTS_GIVEN_NAME", OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME); systemVariables.put("OBSCURE_PATIENTS_MIDDLE_NAME", OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME); systemVariables.put("MODULE_REPOSITORY_PATH", ModuleUtil.getModuleRepository().getAbsolutePath()); systemVariables.put("OPERATING_SYSTEM_KEY", String.valueOf(OpenmrsConstants.OPERATING_SYSTEM_KEY)); systemVariables.put("OPERATING_SYSTEM", String.valueOf(OpenmrsConstants.OPERATING_SYSTEM)); } return systemVariables; }
From source file:com.flexive.shared.FxSharedUtils.java
/** * Get the current hosts name//from ww w . j a va2s. c o m * * @return current hosts name * @since 3.1 */ public synchronized static String getHostName() { if (hostname != null) return hostname; String _hostname; try { _hostname = InetAddress.getLocalHost().getHostName(); if (StringUtils.isBlank(_hostname)) { _hostname = "localhost"; LOG.warn("Hostname was empty, using \"localhost\""); } } catch (UnknownHostException e) { LOG.warn("Failed to determine node ID, using \"localhost\": " + e.getMessage(), e); _hostname = "localhost"; } hostname = _hostname; return hostname; }
From source file:com.elephant.http.AsyncHttpRequest.java
private void makeRequestWithRetries() throws ConnectException { // This is an additional layer of retry logic lifted from droid-fu // See:/*from ww w . j a va2 s . c o m*/ // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java boolean retry = true; IOException cause = null; 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:com.android.pchelper.http.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 v a 2 s .c o m*/ HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { makeRequest(); return; } catch (UnknownHostException e) { if (responseHandler != null) { responseHandler.sendErrorMessage(AsyncHttpClient.HTTP_RESPONSE_UNKNOWNHOST, e); } return; } catch (SocketException e) { // Added to detect host unreachable if (responseHandler != null) { responseHandler.sendErrorMessage(AsyncHttpClient.HTTP_RESPONSE_SOCKETERROR, e); } return; } catch (SocketTimeoutException e) { if (responseHandler != null) { responseHandler.sendErrorMessage(AsyncHttpClient.HTTP_RESPONSE_TTIMEOUT, e); } 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:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java
public void setup(int timeout) throws AgentStartException { AgentConfig cfg = this.getConfig(); AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig(); SSLProvider provider = new DefaultSSLProviderImpl(keystoreConfig, keystoreConfig.isAcceptUnverifiedCert()); SSLContext context = provider.getSSLContext(); SSLServerSocketFactory sFactory = context.getServerSocketFactory(); InetAddress addr;/*from w w w . j a va 2s .c om*/ try { addr = cfg.getListenIpAsAddr(); } catch (UnknownHostException exc) { throw new AgentStartException( "Failed to setup listen socket on '" + cfg.getListenIp() + "': unknown host"); } int port = cfg.getListenPort(); // Better to retry until this succeeds rather than give up and not allowing // the agent to start while (true) { try { listenSock = (SSLServerSocket) sFactory.createServerSocket(port, 50, addr); listenSock.setEnabledCipherSuites( getSupportedAndEnabledCiphers(cfg.getEnabledCipherList(), sFactory)); listenSock.setSoTimeout(timeout); break; } catch (IOException exc) { if (listenSock != null) { try { listenSock.close(); } catch (IOException e1) { log.debug(e1, e1); } } log.warn("Failed to listen at " + cfg.getListenIp() + ":" + port + ": " + exc.getMessage() + ". Will retry until up."); log.debug(exc, exc); try { Thread.sleep(30000); } catch (InterruptedException e) { log.debug(e, e); } } } }
From source file:eu.stratosphere.nephele.jobmanager.JobManager.java
public JobManager(ExecutionMode executionMode) throws Exception { final String ipcAddressString = GlobalConfiguration.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, null);/*from w w w . j a v a 2 s .c o m*/ InetAddress ipcAddress = null; if (ipcAddressString != null) { try { ipcAddress = InetAddress.getByName(ipcAddressString); } catch (UnknownHostException e) { throw new Exception("Cannot convert " + ipcAddressString + " to an IP address: " + e.getMessage(), e); } } final int ipcPort = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT); // Read the suggested client polling interval this.recommendedClientPollingInterval = GlobalConfiguration.getInteger( ConfigConstants.JOBCLIENT_POLLING_INTERVAL_KEY, ConfigConstants.DEFAULT_JOBCLIENT_POLLING_INTERVAL); // Load the job progress collector this.eventCollector = new EventCollector(this.recommendedClientPollingInterval); // Register simple job archive int archived_items = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_WEB_ARCHIVE_COUNT, ConfigConstants.DEFAULT_JOB_MANAGER_WEB_ARCHIVE_COUNT); if (archived_items > 0) { this.archive = new MemoryArchivist(archived_items); this.eventCollector.registerArchivist(archive); } else { this.archive = null; } // Create the accumulator manager, with same archiving limit as web // interface. We need to store the accumulators for at least one job. // Otherwise they might be deleted before the client requested the // accumulator results. this.accumulatorManager = new AccumulatorManager(Math.min(1, archived_items)); // Load the input split manager this.inputSplitManager = new InputSplitManager(); // Determine own RPC address final InetSocketAddress rpcServerAddress = new InetSocketAddress(ipcAddress, ipcPort); // Start job manager's IPC server try { final int handlerCount = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_HANDLERS_KEY, ConfigConstants.DEFAULT_JOB_MANAGER_IPC_HANDLERS); this.jobManagerServer = RPC.getServer(this, rpcServerAddress.getHostName(), rpcServerAddress.getPort(), handlerCount); this.jobManagerServer.start(); } catch (IOException e) { throw new Exception("Cannot start RPC server: " + e.getMessage(), e); } LOG.info("Starting job manager in " + executionMode + " mode"); // Try to load the instance manager for the given execution mode // Try to load the scheduler for the given execution mode if (executionMode == ExecutionMode.LOCAL) { try { this.instanceManager = new LocalInstanceManager(); } catch (Throwable t) { throw new Exception("Cannot instantiate local instance manager: " + t.getMessage(), t); } } else { final String instanceManagerClassName = JobManagerUtils.getInstanceManagerClassName(executionMode); LOG.info("Trying to load " + instanceManagerClassName + " as instance manager"); this.instanceManager = JobManagerUtils.loadInstanceManager(instanceManagerClassName); if (this.instanceManager == null) { throw new Exception("Unable to load instance manager " + instanceManagerClassName); } } // Try to load the scheduler for the given execution mode final String schedulerClassName = JobManagerUtils.getSchedulerClassName(executionMode); LOG.info("Trying to load " + schedulerClassName + " as scheduler"); // Try to get the instance manager class name this.scheduler = JobManagerUtils.loadScheduler(schedulerClassName, this, this.instanceManager); if (this.scheduler == null) { throw new Exception("Unable to load scheduler " + schedulerClassName); } // Load profiler if it should be used if (GlobalConfiguration.getBoolean(ProfilingUtils.ENABLE_PROFILING_KEY, false)) { final String profilerClassName = GlobalConfiguration.getString(ProfilingUtils.JOBMANAGER_CLASSNAME_KEY, "eu.stratosphere.nephele.profiling.impl.JobManagerProfilerImpl"); this.profiler = ProfilingUtils.loadJobManagerProfiler(profilerClassName, ipcAddress); if (this.profiler == null) { throw new Exception("Cannot load profiler"); } } else { this.profiler = null; LOG.debug("Profiler disabled"); } }
From source file:org.rifidi.edge.adapter.csl.util.CslRfidTagServer.java
void StartInventory() { String cmdString;// ww w . ja v a 2 s .c o m int OEMCountryCode, OEMModelCode; int ret_val = 0; while (true) { try { synchronized (inventoryStarted) { if (inventoryStarted) return; else inventoryStarted = true; } String IPAddress = this.IPAddress; // open cport (1516) TCPCtrlSocket = new Socket(IPAddress, 1516); TCPCtrlOut = new DataOutputStream(TCPCtrlSocket.getOutputStream()); TCPCtrlIn = new DataInputStream(new BufferedInputStream(TCPCtrlSocket.getInputStream())); // open iport (1515) TCPDataSocket = new Socket(IPAddress, 1515); TCPDataOut = new DataOutputStream(TCPDataSocket.getOutputStream()); TCPDataIn = new DataInputStream(new BufferedInputStream(TCPDataSocket.getInputStream())); // open uport (3041) clientSocket = new DatagramSocket(); String returnString = ""; // Power up RFID module logger.info("Power up RFID module with command 0x80000001"); returnString = CslRfid_SendCtrlCMD("80000001", 5, 2000); logger.info(String.format("Return: %s \n", returnString)); Thread.sleep(2000); ReaderMode mode = checkMode(); if (mode != ReaderMode.lowLevel) { // change to low-level setMode(ReaderMode.lowLevel); // System.out.println("Could not change reader to low-level mode. Operation abort"); // reconnect TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); Thread.sleep(2000); // open cport (1516) TCPCtrlSocket = new Socket(IPAddress, 1516); TCPCtrlOut = new DataOutputStream(TCPCtrlSocket.getOutputStream()); TCPCtrlIn = new DataInputStream(new BufferedInputStream(TCPCtrlSocket.getInputStream())); // open iport (1515) TCPDataSocket = new Socket(IPAddress, 1515); TCPDataOut = new DataOutputStream(TCPDataSocket.getOutputStream()); TCPDataIn = new DataInputStream(new BufferedInputStream(TCPDataSocket.getInputStream())); // open uport (3041) clientSocket = new DatagramSocket(); logger.info("Power up RFID module with command 0x80000001"); returnString = CslRfid_SendCtrlCMD("80000001", 5, 2000); logger.info(String.format("Return: %s \n", returnString)); mode = checkMode(); if (mode != ReaderMode.lowLevel) { TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); Thread.sleep(2000); inventoryStarted = false; return; } Thread.sleep(2000); } // Enable TCP Notifications logger.info("Enable TCP Notifications with command 0x8000011701"); returnString = CslRfid_SendCtrlCMD("8000011701", 5, 2000); logger.info(String.format("Return: %s \n", returnString)); Thread.sleep(500); // Send Abort command clearReadBuffer(TCPDataIn); logger.info("Send Abort command 0x4003000000000000"); returnString = CslRfid_SendDataCMD("4003000000000000", 8, 2000); logger.info(String.format("Return: %s \n", returnString)); this.state = ReaderState.CONNECTED; // Select Antenna port 0 ANT_PORT_SEL clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("7001010700000000")); logger.info("Send ANT_PORT_SEL command 0x7001010700000000"); Thread.sleep(5); // Select RF power Max up to 30dBm clearReadBuffer(TCPDataIn); if ((readerPower < 0) || (readerPower > 300)) ret_val = -11; else { // TCPDataOut.write(hexStringToByteArray("700106072C010000")); cmdString = String.format("70010607%02X%02X0000", readerPower & 0xFF, ((readerPower >> 8) & 0xFF)); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send RF Power command %s \n", cmdString)); } Thread.sleep(5); // Set Dwell Time clearReadBuffer(TCPDataIn); // dwellTime = 0 for CS203 reader cmdString = String.format("70010507%02X%02X%02X%02X", dwellTime & 0xff, (dwellTime >> 8) & 0xff, (dwellTime >> 16) & 0xff, (dwellTime >> 24) & 0xff); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send Dwell Time command %s \n", cmdString)); Thread.sleep(5); // Set Inventory Round (ANT_PORT_INV_CNT) clearReadBuffer(TCPDataIn); // inventoryRound = 0xffffffff for CS203 reader inventoryRound = 0xffffffff; cmdString = String.format("70010707%02X%02X%02X%02X", inventoryRound & 0xff, (inventoryRound >> 8) & 0xff, (inventoryRound >> 16) & 0xff, (inventoryRound >> 24) & 0xff); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send Inventory Round command %s \n", cmdString)); Thread.sleep(5); // Link Profile clearReadBuffer(TCPDataIn); if ((link_Profile < 0) || (link_Profile > 4)) ret_val = -12; else { // TCPDataOut.write(hexStringToByteArray("7001600b02000000")); // link_Profile = 2; // Link Profile cmdString = String.format("7001600b%02X000000", link_Profile & 0xff); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send Link Profile 2 command %s \n", cmdString)); } Thread.sleep(5); // HST Command clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("700100f019000000")); logger.info("HST_CMD command 700100f019000000"); Thread.sleep(5); // QUERY_CFG Command for continuous inventory clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("70010007ffff0000")); logger.info("QUERY_CFG (continuous mode) command 70010007ffff0000"); Thread.sleep(5); // Set DynamicQ algorithm (INV_SEL) clearReadBuffer(TCPDataIn); // TCPDataOut.write(hexStringToByteArray("70010309f7005003")); if ((algorithm_Q < 0) || (algorithm_Q > 3)) ret_val = -14; else { cmdString = String.format("70010209%02X000000", algorithm_Q & 0xff); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send Q Algorithm command %s \n", cmdString)); } Thread.sleep(5); // start Q clearReadBuffer(TCPDataIn); if ((startQ < 0) || (startQ > 15)) ret_val = -15; else { cmdString = String.format("70010309F%01X400000", startQ & 0xf); TCPDataOut.write(hexStringToByteArray(cmdString)); logger.info(String.format("Send Start Q command %s \n", cmdString)); } Thread.sleep(5); // Send INV_CFG clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("7001010901000000")); logger.info("Send INV_CFG command 7001010901000000"); Thread.sleep(5); //---------------------------------------- Read Country code clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("7001000502000000")); Thread.sleep(5); TCPDataOut.write(hexStringToByteArray("700100f003000000")); Thread.sleep(5); while (true) { if (TCPDataIn.available() != 0) { len = TCPDataIn.read(inData); break; } } OEMCountryCode = inData[28]; Thread.sleep(5); //---------------------------------------- Read Model code clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("70010005A4000000")); Thread.sleep(5); TCPDataOut.write(hexStringToByteArray("700100f003000000")); Thread.sleep(5); while (true) { if (TCPDataIn.available() != 0) { len = TCPDataIn.read(inData); break; } } OEMModelCode = inData[28]; Thread.sleep(5); switch (OEMModelCode) { case 0: cmdString = String.format("Reader Model: CS101-%d \n", OEMCountryCode); break; case 1: cmdString = String.format("Reader Model: CS203-%d \n", OEMCountryCode); break; case 3: cmdString = String.format("Reader Model: CS468-%d \n", OEMCountryCode); break; case 5: cmdString = String.format("Reader Model: CS468INT-%d \n", OEMCountryCode); break; case 7: cmdString = String.format("Reader Model: CS469-%d \n", OEMCountryCode); break; default: cmdString = String.format("Unidentified reader model \n"); ret_val = -17; break; } System.out.println(cmdString); // sel_Country = "G800"; int t_index = 0; // String cty = CslFreqTab.OEMCountryTable[1]; if (ret_val == 0) { //--------------------------------------------------- Set Frequency Table for the Country Select ret_val = VerifySelectCountry(sel_Country, OEMCountryCode); if (ret_val == 0) { t_index = Arrays.asList(CslFreqTab.OEMCountryTable).indexOf(sel_Country); int[] t_freqTable = CslFreqTab.countryFreqTable[t_index][0]; int t_numCh = CslFreqTab.countryFreqTable[t_index][1][0]; int t_freqVal; for (int i = 0; i < t_numCh; i++) { Thread.sleep(5); //---------------------------------------- Read Model code clearReadBuffer(TCPDataIn); cmdString = String.format("7001010C%02X000000", i); // Select Channel TCPDataOut.write(hexStringToByteArray(cmdString)); Thread.sleep(5); t_freqVal = swapMSBLSB32bit(t_freqTable[i]); cmdString = String.format("7001030C%08X", t_freqVal); // Set Freq TCPDataOut.write(hexStringToByteArray(cmdString)); Thread.sleep(5); TCPDataOut.write(hexStringToByteArray("7001020C01000000")); // Enable Channel Thread.sleep(5); } } else { cmdString = String.format("The reader -%d does not support selected country!! \n", OEMCountryCode); System.out.println(cmdString); } } //----------------------------------------- quit if error value returned boolean sentAbortCmd = false; if (ret_val < 0) { inventoryStarted = false; tcpClientStarted = false; TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); Thread.sleep(1000); sentAbortCmd = true; } else { // Start inventory - send (HST_CMD) long timer = System.currentTimeMillis(); clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("700100f00f000000")); logger.info("Start inventory - send (HST_CMD) 700100f00f000000"); while (true) { if (!inventoryStarted && !sentAbortCmd) { // Send Abort command clearReadBuffer(TCPDataIn); TCPDataOut.write(hexStringToByteArray("4003000000000000")); logger.info("Send Abort command 0x4003000000000000"); sentAbortCmd = true; } if (TCPDataIn.available() != 0) { timer = System.currentTimeMillis(); len = TCPDataIn.read(inData, 0, 8); if (len < 8) continue; if (byteArrayToHexString(inData, len).startsWith("9898989898989898")) { // clearReadBuffer(TCPDataIn); // date = new Date(); // System.out.println(dateFormat.format(date) + // " TCP Notification Received."); continue; } if (byteArrayToHexString(inData, len).startsWith("02000780")) { // clearReadBuffer(TCPDataIn); // /date = new Date(); // System.out.println(dateFormat.format(date) + // " Antenna Cycle End Notification Received"); continue; } if (byteArrayToHexString(inData, len).startsWith("4003BFFCBFFCBFFC")) { TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); date = new Date(); logger.info("Abort cmd response received " + byteArrayToHexString(inData, len)); Thread.sleep(2000); inventoryStarted = false; break; } // int pkt_ver = (int) inData[0]; // int flags = (int) inData[1]; int pkt_type = (int) (inData[2] & 0xFF) + ((int) (inData[3] & 0xFF) << 8); int pkt_len = (int) (inData[4] & 0xFF) + ((int) (inData[5] & 0xFF) << 8); int datalen = pkt_len * 4; // wait until the full packet data has come in while (TCPDataIn.available() < datalen) { } // finish reading TCPDataIn.read(inData, 8, datalen); if (pkt_type == 0x8001) { TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); this.state = ReaderState.NOT_CONNECTED; date = new Date(); logger.info("Command End Packet: " + byteArrayToHexString(inData, len + datalen)); Thread.sleep(2000); break; } if (pkt_type == 0x8000) { this.state = ReaderState.BUSY; date = new Date(); logger.info(dateFormat.format(date) + " Command Begin Packet: " + byteArrayToHexString(inData, len + datalen)); continue; } if (pkt_type == 0x8005) { date = new Date(); // System.out.println(dateFormat.format(date) + // " Inventory Packet: " + // byteArrayToHexString(inData,len+datalen)); // logger.info("pkt_type == 0x8005 : " + dateFormat.format(date)); // For Test Only byte[] EPC = new byte[1000]; TagInfo tag = new TagInfo(); tag.pc = byteArrayToHexString(Arrays.copyOfRange(inData, 20, 22), 2); tag.rssi = (float) (inData[13] * 0.8); tag.antennaPort = inData[18]; for (int cnt = 0; cnt < (datalen - 16); cnt++) { EPC[cnt] = inData[22 + cnt]; } tag.addr = this.IPAddress; tag.epc = byteArrayToHexString(EPC, datalen - 16); tag.timestamp = System.currentTimeMillis(); synchronized (TagBuffer) { if (TagBuffer.size() >= 10000) TagBuffer.remove(); TagBuffer.add(tag); } } } else { if (System.currentTimeMillis() - timer >= 8000) { this.state = ReaderState.NOT_CONNECTED; logger.error("Connection lost. To be reconnected"); logger.error("Close Connections"); TCPCtrlSocket.close(); TCPDataSocket.close(); clientSocket.close(); Thread.sleep(2000); inventoryStarted = false; break; } } } } if (sentAbortCmd) { // exit thread logger.info("Inventory Stopped"); this.state = ReaderState.NOT_CONNECTED; inventoryStarted = false; break; } } catch (UnknownHostException e) { System.err.println(e.getMessage()); inventoryStarted = false; } catch (IOException e) { System.err.println(e.getMessage()); inventoryStarted = false; } catch (java.lang.InterruptedException e) { System.err.println(e.getMessage()); inventoryStarted = false; } catch (java.lang.IndexOutOfBoundsException e) { System.err.println(e.getMessage()); inventoryStarted = false; } } }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient.java
/** * Retrieves the root URL for the Gerrit instance and attempts to parse the configuration from the JavaScript * portion of the page./*from w w w.j av a 2s. com*/ */ private GerritConfigX refreshGerritConfig(final IProgressMonitor monitor) throws GerritException { try { GerritConfigX gerritConfig = client.execute(new Request<GerritConfigX>() { @Override public HttpMethodBase createMethod() throws IOException { return new GetMethod(client.getUrl() + "/"); //$NON-NLS-1$ } @Override public GerritConfigX process(HttpMethodBase method) throws IOException { InputStream in = WebUtil.getResponseBodyAsStream(method, monitor); try { GerritHtmlProcessor processor = new GerritHtmlProcessor(); processor.parse(in, method.getResponseCharSet()); return processor.getConfig(); } finally { in.close(); } } }, monitor); if (gerritConfig == null) { throw new GerritException("Failed to obtain Gerrit configuration"); //$NON-NLS-1$ } return gerritConfig; } catch (UnknownHostException cause) { GerritException e = new GerritException("Unknown host: " + cause.getMessage()); //$NON-NLS-1$ e.initCause(cause); throw e; } catch (IOException cause) { GerritException e = new GerritException(cause.getMessage()); e.initCause(cause); throw e; } }
From source file:org.openmrs.api.impl.AdministrationServiceImpl.java
/** * @see org.openmrs.api.AdministrationService#getSystemInformation() *///from w ww . j av a 2 s .co m @Transactional(readOnly = true) public Map<String, Map<String, String>> getSystemInformation() throws APIException { Map<String, Map<String, String>> systemInfoMap = new LinkedHashMap<String, Map<String, String>>(); systemInfoMap.put("SystemInfo.title.openmrsInformation", new LinkedHashMap<String, String>() { private static final long serialVersionUID = 1L; { put("SystemInfo.OpenMRSInstallation.systemDate", new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime())); put("SystemInfo.OpenMRSInstallation.systemTime", new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())); put("SystemInfo.OpenMRSInstallation.openmrsVersion", OpenmrsConstants.OPENMRS_VERSION); try { put("SystemInfo.hostname", InetAddress.getLocalHost().getCanonicalHostName()); } catch (UnknownHostException e) { put("SystemInfo.hostname", "Unknown host: " + e.getMessage()); } } }); systemInfoMap.put("SystemInfo.title.javaRuntimeEnvironmentInformation", new LinkedHashMap<String, String>() { Properties properties = System.getProperties(); private static final long serialVersionUID = 1L; { put("SystemInfo.JavaRuntimeEnv.operatingSystem", properties.getProperty("os.name")); put("SystemInfo.JavaRuntimeEnv.operatingSystemArch", properties.getProperty("os.arch")); put("SystemInfo.JavaRuntimeEnv.operatingSystemVersion", properties.getProperty("os.version")); put("SystemInfo.JavaRuntimeEnv.javaVersion", properties.getProperty("java.version")); put("SystemInfo.JavaRuntimeEnv.javaVendor", properties.getProperty("java.vendor")); put("SystemInfo.JavaRuntimeEnv.jvmVersion", properties.getProperty("java.vm.version")); put("SystemInfo.JavaRuntimeEnv.jvmVendor", properties.getProperty("java.vm.vendor")); put("SystemInfo.JavaRuntimeEnv.javaRuntimeName", properties.getProperty("java.runtime.name")); put("SystemInfo.JavaRuntimeEnv.javaRuntimeVersion", properties.getProperty("java.runtime.version")); put("SystemInfo.JavaRuntimeEnv.userName", properties.getProperty("user.name")); put("SystemInfo.JavaRuntimeEnv.systemLanguage", properties.getProperty("user.language")); put("SystemInfo.JavaRuntimeEnv.systemTimezone", properties.getProperty("user.timezone")); put("SystemInfo.JavaRuntimeEnv.fileSystemEncoding", properties.getProperty("sun.jnu.encoding")); put("SystemInfo.JavaRuntimeEnv.userDirectory", properties.getProperty("user.dir")); put("SystemInfo.JavaRuntimeEnv.tempDirectory", properties.getProperty("java.io.tmpdir")); } }); systemInfoMap.put("SystemInfo.title.memoryInformation", new LinkedHashMap<String, String>() { private static final long serialVersionUID = 1L; Runtime runtime = Runtime.getRuntime(); { put("SystemInfo.Memory.totalMemory", convertToMegaBytes(runtime.totalMemory())); put("SystemInfo.Memory.freeMemory", convertToMegaBytes(runtime.freeMemory())); put("SystemInfo.Memory.maximumHeapSize", convertToMegaBytes(runtime.maxMemory())); } }); systemInfoMap.put("SystemInfo.title.dataBaseInformation", new LinkedHashMap<String, String>() { Properties properties = Context.getRuntimeProperties(); private static final long serialVersionUID = 1L; { put("SystemInfo.Database.name", OpenmrsConstants.DATABASE_NAME); put("SystemInfo.Database.connectionURL", properties.getProperty("connection.url")); put("SystemInfo.Database.userName", properties.getProperty("connection.username")); put("SystemInfo.Database.driver", properties.getProperty("hibernate.connection.driver_class")); put("SystemInfo.Database.dialect", properties.getProperty("hibernate.dialect")); } }); systemInfoMap.put("SystemInfo.title.moduleInformation", new LinkedHashMap<String, String>() { private static final long serialVersionUID = 1L; { put("SystemInfo.Module.repositoryPath", ModuleUtil.getModuleRepository().getAbsolutePath()); Collection<Module> loadedModules = ModuleFactory.getLoadedModules(); for (Module module : loadedModules) { String moduleInfo = module.getVersion() + " " + (module.isStarted() ? "" : Context.getMessageSourceService().getMessage("Module.notStarted")); put(module.getName(), moduleInfo); } } }); return systemInfoMap; }