List of usage examples for java.net SocketException getMessage
public String getMessage()
From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java
public void run() { try {//from www .j a va 2 s . c om logger.debug("Binding to UDP port " + listeningPort); socket = new DatagramSocket(listeningPort); } catch (SocketException e) { // Fix: Flag to control lock socket within application isSocketException = true; throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage()); } // Fix: Flag to control lock socket within application isSocketCreated = true; while (!workerThread.isInterrupted()) { byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE]; final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer, requestPacketBuffer.length); try { socket.receive(requestPacket); } catch (IOException e) { logger.error("Error processing SNMP request. Reason: " + e.getMessage()); continue; } final byte data[] = requestPacket.getData(); Thread procThread = new Thread(new Runnable() { public void run() { try { Message requestMsg; Message responseMsg; PDU requestPDU; // Fix: Added missed ')' character logger.debug("Received packet (length=" + data.length + " bytes)"); BerTlv tlv = new BerTlv(); tlv.decode(new ByteArrayInputStream(data)); requestMsg = new Message(tlv); responseMsg = null; requestPDU = (PDU) requestMsg.getPDU(); String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName() .stringValue(); if (!hasHandledPrefix(requestedOID)) { logger.info("No entry found for oid " + requestedOID); GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L, requestPDU.getVarBindList()); responseMsg = new Message(0, requestMsg.getComunity(), responsePDU); return; } if (!validateCommunity(requestMsg)) { logger.warn( "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request"); return; } GetResponsePDU responsePDU = null; if (requestPDU instanceof GetRequestPDU) responsePDU = handleGetRequest((GetRequestPDU) requestPDU); else if (requestPDU instanceof GetNextRequestPDU) responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU); else if (requestPDU instanceof SetRequestPDU) responsePDU = handleSetRequest((SetRequestPDU) requestPDU); else responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0, requestPDU.getVarBindList()); responseMsg = new Message(0, requestMsg.getComunity(), responsePDU); logger.info("Sending response to client\n" + responseMsg.toString()); byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes(); if (responsePacketBuffer.length > PACKET_MAX_SIZE) { responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L, requestPDU.getVarBindList()); responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU); responsePacketBuffer = responseMsg.toBerTlv().getBytes(); } DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer, responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort()); socket.send(responsePacket); } catch (Exception e) { logger.error("Error processing SNMP request. Reason: " + e.getMessage()); } } }); procThread.start(); } }
From source file:org.wso2.bam.integration.tests.archive.CassandraDataArchiveTestCase.java
@Test(groups = { "wso2.bam" }) public void publishData() { String host = null;//from ww w.ja va 2 s . com try { host = getLocalHostAddress().getHostAddress(); } catch (SocketException e) { host = "127.0.0.1"; } try { dataPublisher = new DataPublisher("tcp://" + host + ":7611", "admin", "admin"); defineEventStream(); //Publish yesterday's data publishEvent(-1); publishEvent(0); Thread.sleep(5000); runArchivalJob(); Thread.sleep(40000); runJDBCHandlerTest(); } catch (Exception e) { fail("Can't get data publisher: " + e.getMessage()); } }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * Binds this server to the SocketAddress supplied by DaapConfig * //ww w . j a va 2s .c o m * @throws IOException */ public void bind() throws IOException { SocketAddress bindAddr = config.getInetSocketAddress(); int backlog = config.getBacklog(); try { ssc = ServerSocketChannel.open(); ServerSocket socket = ssc.socket(); // BugID: 4546610 // On Win2k, Mac OS X, XYZ it is possible to bind // the same address without rising a SocketException // (the Documentation lies) socket.setReuseAddress(false); try { socket.bind(bindAddr, backlog); } catch (SocketException err) { throw new BindException(err.getMessage()); } ssc.configureBlocking(false); if (LOG.isInfoEnabled()) { LOG.info("DaapServerNIO bound to " + bindAddr); } streams = new HashSet(); connections = new HashSet(); sessionIds = new HashSet(); } catch (IOException err) { close(); throw err; } }
From source file:phex.download.DownloadEngine.java
/** * Connects a unconnected Download engine and prepares the DownloadEngine for use. * @param timeout//from w ww . ja va2s.c om * @throws IOException * @throws InterruptedException */ public void connect(int timeout) throws IOException { assert socket == null; DestAddress address = candidate.getHostAddress(); try { candidate.addToCandidateLog("Wait for connect slot " + address.getHostName() + ":" + address.getPort()); NLogger.debug(NLoggerNames.Download_Engine, "Wait for connect slot " + address.getHostName() + ":" + address.getPort()); Runnable acquireCallback = new Runnable() { public void run() { DestAddress address = candidate.getHostAddress(); candidate.addToCandidateLog("Connecting to " + address.getHostName() + ":" + address.getPort()); NLogger.debug(NLoggerNames.Download_Engine, "Connecting to " + address.getHostName() + ":" + address.getPort()); candidate.setStatus(SWDownloadConstants.STATUS_CANDIDATE_CONNECTING); } }; socket = OIOSocketFactory.connect(address, timeout, acquireCallback); } catch (SocketException exp) {// indicates a general communication error while connecting throw new ConnectionFailedException(exp.getMessage()); } prepareConnection(); }
From source file:org.wso2.carbon.siddhi.editor.core.internal.ServiceComponent.java
@Reference(name = "http-connector-provider", service = ServerConnector.class, cardinality = ReferenceCardinality.AT_LEAST_ONE, policy = ReferencePolicy.DYNAMIC, unbind = "unsetCarbonTransport") protected void setCarbonTransport(ServerConnector serverConnector) { if (serverConnector instanceof HTTPServerConnector) { HTTPServerConnector httpServerConnector = (HTTPServerConnector) serverConnector; ListenerConfiguration config = httpServerConnector.getListenerConfiguration(); if ("http".equals(config.getScheme())) { String hostname = null; try { hostname = HostAddressFinder.findAddress(config.getHost()); } catch (SocketException e) { log.error("Error in finding address for provided hostname " + config.getHost() + "." + e.getMessage(), e); hostname = config.getHost(); }/*from w w w .j a v a 2 s .c o m*/ startingURL += config.getScheme() + "://" + hostname + ":" + config.getPort() + "/editor"; } } }
From source file:org.gcaldaemon.core.http.HTTPListener.java
public final void run() { // Variables/*from www .ja v a 2 s . c o m*/ Socket socket = null; Request request = null; Response response = null; try { // Loop for (;;) { // Accept connection socket = serverSocket.accept(); socket.setSoTimeout(5000); // Access control try { checkAccess(socket); } catch (Exception securityError) { log.debug("Connection refused!", securityError); try { socket.close(); } catch (Exception igonre) { } socket = null; } // Parse request request = null; if (socket != null) { try { request = readRequest(socket); log.debug("Processing " + request.method + " method..."); } catch (Exception readError) { log.warn("Unable to read request!", readError); request = null; } } // Create response response = null; if (request != null) { if (request.url != null && request.url.endsWith(".ics")) { int i = request.url.indexOf('@'); if (i != -1) { request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1); } i = request.url.indexOf("googlemail.com"); if (i != -1) { request.url = request.url.substring(0, i) + "gmail.com" + request.url.substring(i + 14); } } try { if (GET_METHOD.equals(request.method)) { response = doGet(request); } else { if (PUT_METHOD.equals(request.method)) { response = doPut(request); } else { response = doUnsupportedMethod(request); } } } catch (Exception processingError) { log.warn("Unable to process request!", processingError); response = null; } } // Write response if (response != null) { log.trace("Response processed with status code " + response.status + "."); try { writeResponse(socket, request, response); } catch (Exception writeError) { log.warn("Unable to write response!", writeError); response = null; } } request = null; // Close socket if (socket != null) { try { socket.close(); } catch (Exception closeError) { log.warn("Unable to close socket!", closeError); socket = null; } } } } catch (SocketException socketException) { // Check message String msg = socketException.getMessage(); if (msg == null || msg.indexOf("close") == -1) { log.fatal("Fatal HTTP server error!", socketException); } } catch (Exception fatalError) { // Service stopped log.fatal("Fatal service error!", fatalError); } finally { // Close resources if (serverSocket != null && !serverSocket.isClosed()) { try { serverSocket.close(); } catch (Exception ignore) { } } if (socket != null) { try { socket.close(); } catch (Exception igonre) { } socket = null; } } log.info("HTTP server stopped."); }
From source file:edu.hawaii.soest.kilonalu.adam.AdamDispatcher.java
/** * A method used to connect to the UDP port of the host that will have the * UDP stream of data packets, and that will also connect each of the AdamSource * drivers to the DataTurbine.//from w ww . j a va 2s . c o m */ protected boolean connect() { if (isConnected()) { return true; } try { // bind to the UDP socket this.datagramSocket = new DatagramSocket(getHostPort()); // Create a list of sensors from the properties file, and iterate through // the list, creating an RBNB Source object for each sensor listed. Store // these objects in a HashMap for later referral. this.sourceMap = new HashMap<String, AdamSource>(); List sensorList = this.xmlConfiguration.getList("sensor.address"); // declare the properties that will be pulled from the // sensor.properties.xml file String address = ""; String sourceName = ""; String cacheSize = ""; String archiveSize = ""; String archiveChannel = ""; // evaluate each sensor listed in the sensor.properties.xml file for (Iterator sIterator = sensorList.iterator(); sIterator.hasNext();) { // get each property value of the sensor int index = sensorList.indexOf(sIterator.next()); address = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").address"); sourceName = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").name"); cacheSize = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").cacheSize"); archiveSize = (String) this.xmlConfiguration.getProperty("sensor(" + index + ").archiveSize"); // given the properties, create an RBNB Source object AdamSource adamSource = new AdamSource(this.serverName, (new Integer(this.serverPort)).toString(), this.archiveMode, (new Integer(archiveSize).intValue()), (new Integer(cacheSize).intValue()), sourceName); adamSource.startConnection(); sourceMap.put(address, adamSource); } connected = true; } catch (SocketException se) { System.err.println( "Failed to connect to the UDP data stream. " + "The error message was: " + se.getMessage()); } return connected; }
From source file:net.latin.server.GwtBaseAction.java
/***************************************************************/ public String execute() throws Exception { try {//from w w w . j a v a2s .c om // Store the request & response objects in thread-local storage. // // save globals in the user thread local // (antes del readContent porque si falla doUnexpectedFailure() // espera que el response este seteado en UserContext) UserContext userContext = UserContext.getInstance(); userContext.setRequest(request); userContext.setResponse(response); // Read the request fully. // String requestPayload = readContent(request); userContext.setRequestPayload(requestPayload); if (SpringUtils.useSpringPersistenceTemplates()) { /** * Execute the gwt method inside a spring transaction */ SpringUtils.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { try { // save the transactionStatus in the ThreadLocal UserContext.getInstance().setTransactionStatus(transactionStatus); /** * Process gwt method inside the transaction */ executeGwtMethod(); // check for declared LnwTransactionException in // session HttpSession session = UserContext.getInstance().getRequest().getSession(false); if (session != null) { LnwTransactionException trEx = (LnwTransactionException) session .getAttribute(GwtUseCase.LNW_TRANSACTION_EXCEPTION_KEY); // if it was loaded in session, rollback // transaction (see LnwTransactionException // class) if (trEx != null) { session.removeAttribute(GwtUseCase.LNW_TRANSACTION_EXCEPTION_KEY); rollbackTransaction(transactionStatus); } } // Catchs exceptions and rollback } catch (Exception e) { rollbackTransaction(transactionStatus); // throws another exception, with the originial // wrapped, to be catched by gwt throw new RuntimeException(e); } } }); } else { /** * Process gwt method (and let the subclass determines if a * transaction handling is needed) */ executeGwtMethod(); } } catch (SocketException se) { // Vemos si no es que el cliente cerro el browser y se perdio la // conexion // antes de que termine de enviar todo el response. // Es burda, pero es la unica manera que encontre de detectar estos // casos. if (!se.getMessage().toLowerCase().contains("connection reset")) { throw se; } } catch (Throwable e) { // Give a subclass a chance to either handle the exception or // rethrow it doUnexpectedFailure(e); } finally { // null the thread-locals to avoid holding request/response // // clear user context UserContext.getInstance().clear(); } // no forward requeried return null; }
From source file:com.ephesoft.gxt.batchinstance.server.BatchInfoDownloadServlet.java
/** * This method uploads the folder containing information related to a batch on a ftp server. * /*from w w w.j ava 2 s.c o m*/ * @param batchInstance {@link BatchInstance} * @param batchSchemaService {@link BatchSchemaService} * @param batchClass {@link BatchClass} * @param response {@link HttpServletResponse} * * @return {@link String} the path where file is uploaded */ private String uploadToFTPPath(final BatchInstance batchInstance, final BatchSchemaService batchSchemaService, final BatchClass batchClass, final HttpServletResponse response) { File zipFolder = null; String ftpFolderPath = null; String batchInstanceIdentifier = null; if (null != batchInstance) { batchInstanceIdentifier = batchInstance.getIdentifier(); } File tempFolder = new File(createDownloadFolderPathName(batchInstanceIdentifier, baseFolderPath)); tempFolder.mkdirs(); if (tempFolder.exists()) { FileOutputStream fout = null; ZipOutputStream zout = null; try { PrintWriter writer = response.getWriter(); response.setContentType(IUtilCommonConstants.CONTENT_TYPE_HTML); String zipFileName = createZipFileName(batchInstanceIdentifier); String zipFolderPath = EphesoftStringUtil.concatenate(baseFolderPath, File.separator, TROUBLESHOOT, File.separator, zipFileName); String zipFilePath = EphesoftStringUtil.concatenate(zipFolderPath, File.separator, zipFileName, ZIP_EXT); zipFolder = new File(zipFolderPath); zipFolder.mkdirs(); fout = new FileOutputStream(zipFilePath); zout = new ZipOutputStream(fout); Properties properties = getFTPProperties(); if (null != properties) { ftpFolderPath = EphesoftStringUtil.concatenate(TROUBLESHOOT, File.separator, zipFileName, ZIP_EXT); FTPInformation ftpInformation = new FTPInformation(ftpServerURL, username, password, properties.getProperty(UPLOAD_BASE_DIR), Integer.parseInt(properties.getProperty(NUM_OF_RETRIES)), properties.getProperty(DATA_TIMEOUT), zipFolderPath, TROUBLESHOOT, 2); try { FTPClient client = new FTPClient(); FTPUtil.createConnection(client, ftpServerURL, username, password, properties.getProperty(DATA_TIMEOUT)); client.disconnect(); copySelectedFolders(batchInstance, batchSchemaService, batchClass, tempFolder.getPath(), tempFolder); if (null != tempFolder.list()) { FileUtils.zipDirectoryWithFullName(tempFolder.getPath(), zout); FTPUtil.uploadDirectory(ftpInformation, false); } writer.write(copyTroubleshootingArtifacts.getFoldersNotCopied()); } catch (SocketException socketException) { LOGGER.error("Could not connect to the FTP client. Socket Exception", socketException.getMessage()); ftpFolderPath = null; // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results. } catch (final IOException ioException) { LOGGER.error(" Invalid Credentials. Could not connect to the FTP client.", ioException.getMessage()); ftpFolderPath = null; writer.write("INVALID_CREDENTIALS"); response.setStatus(HttpServletResponse.SC_OK); // Removed response.sendError code to fix JIRA bug id EPHESOFT-12355. Did not returned expected results. } } } catch (FTPDataUploadException e) { LOGGER.error(EphesoftStringUtil.concatenate("Error occured in uploading the file to path ", ftpFolderPath)); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e) { LOGGER.error(EphesoftStringUtil.concatenate("Error occured in getting writer from response.", e.getMessage())); } catch (NumberFormatException e) { LOGGER.error(EphesoftStringUtil.concatenate("Exception occured in parsing number of retries.", e.getMessage())); } finally { try { closeResources(null, zout, fout, null); if (tempFolder != null) { FileUtils.deleteDirectoryAndContentsRecursive(tempFolder); } if (zipFolder != null) { FileUtils.deleteDirectoryAndContentsRecursive(zipFolder); } } catch (IOException e) { LOGGER.error(EphesoftStringUtil.concatenate("Exception occured while closing outputstream.", e.getMessage())); } } } else { LOGGER.error("Could not create the folder for copying the required folders."); } return ftpFolderPath; }
From source file:org.wso2.carbon.bpel.b4p.extension.PeopleActivity.java
private String generateServiceURLUpToWebContext() throws B4PCoordinationException, FaultException { String baseURL = ""; if (CoordinationConfiguration.getInstance().isClusteredTaskEngines()) { baseURL = CoordinationConfiguration.getInstance().getLoadBalancerURL(); } else {//from ww w . j a v a 2s . c om ConfigurationContext serverConfigurationContext = getConfigurationContext(); String scheme = CarbonConstants.HTTPS_TRANSPORT; String host; try { host = NetworkUtils.getLocalHostname(); } catch (SocketException e) { log.error(e.getMessage(), e); throw new B4PCoordinationException(e.getLocalizedMessage(), e); } int port = 9443; port = CarbonUtils.getTransportProxyPort(serverConfigurationContext, scheme); if (port == -1) { port = CarbonUtils.getTransportPort(serverConfigurationContext, scheme); } baseURL = scheme + "://" + host + ":" + port; } String webContext = ServerConfiguration.getInstance().getFirstProperty("WebContextRoot"); if (webContext == null || webContext.equals("/")) { webContext = ""; } return baseURL + webContext; }