Example usage for java.net SocketException getLocalizedMessage

List of usage examples for java.net SocketException getLocalizedMessage

Introduction

In this page you can find the example usage for java.net SocketException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.wso2.carbon.attachment.mgt.util.URLGeneratorUtil.java

/**
 * Generate the permanent link for the given attachment uri based on current system configurations like host, port
 * eg - if {@code uniqueID} is abc123, then the resultant permanent link would {@code https://127.0.0.1:9443/context/abc123}
 * So this url can be used to download the attachment
 *
 * @param uniqueID uri for the attachment
 * @return downloadable url of the attachment
 * @throws AttachmentMgtException//ww w .  java  2 s.c  o  m
 */
public static URL getPermanentLink(URI uniqueID) throws AttachmentMgtException {
    String scheme = CarbonConstants.HTTPS_TRANSPORT;
    String host;
    try {
        host = NetworkUtils.getLocalHostname();
    } catch (SocketException e) {
        log.error(e.getMessage(), e);
        throw new AttachmentMgtException(e.getLocalizedMessage(), e);
    }

    int port = 9443;

    try {
        ConfigurationContext serverConfigContext = AttachmentServerHolder.getInstance()
                .getConfigurationContextService().getServerConfigContext();
        port = CarbonUtils.getTransportProxyPort(serverConfigContext, scheme);
        if (port == -1) {
            port = CarbonUtils.getTransportPort(serverConfigContext, scheme);
        }
    } catch (Exception ex) {
        log.warn("Using default port settings");
    }

    String webContext = ServerConfiguration.getInstance().getFirstProperty("WebContextRoot");
    if (webContext == null || webContext.equals("/")) {
        webContext = "";
    }

    String tenantDomain = String.valueOf(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    try {
        tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    } catch (Throwable e) {
        tenantDomain = null;
    }

    String url = null;
    try {
        String link = scheme + "://" + host + ":" + port + webContext
                + ((tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain))
                        ? "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain
                        : "")
                + AttachmentMgtConfigurationConstants.ATTACHMENT_DOWNLOAD_SERVELET_URL_PATTERN + "/"
                + uniqueID.toString();

        return new URL(link);
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        throw new AttachmentMgtException(e.getLocalizedMessage(), e);
    }
}

From source file:org.wso2.carbon.humantask.coordination.module.utils.ServiceUtils.java

/**
 * Returns URL of the of the Task engine's Protocol Handler Admin service.
 * eg: https://localhost:9443/services/HumanTaskProtocolHandler/
 *
 * @return HumanTask protocol handler admin service's url
 *///  w w w.  j av a2  s. c o  m
public static String getTaskProtocolHandlerURL(ConfigurationContext serverConfigurationContext)
        throws HumanTaskCoordinationException {
    HumanTaskServerConfiguration serverConfig = HTCoordinationModuleContentHolder.getInstance().getHtServer()
            .getServerConfig();
    String baseURL;
    if (serverConfig.isClusteredTaskEngines()) {
        baseURL = serverConfig.getLoadBalancerURL();
    } else {
        String scheme = CarbonConstants.HTTPS_TRANSPORT;
        String host;
        try {
            host = NetworkUtils.getLocalHostname();
        } catch (SocketException e) {
            log.error(e.getMessage(), e);
            throw new HumanTaskCoordinationException(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 = "";
    }

    String tenantDomain = "";
    try {
        tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
    } catch (Throwable e) {
        tenantDomain = null;
    }

    String protocolHandlerURL = baseURL + webContext
            + ((tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain))
                    ? "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain
                    : "")
            + Constants.CARBON_ADMIN_SERVICE_CONTEXT_ROOT + "/"
            + Constants.HUMANTASK_ENGINE_COORDINATION_PROTOCOL_HANDLER_SERVICE;
    return protocolHandlerURL;
}

From source file:node.Mailbox.java

/**
 * main loop//from ww w  . j av a  2  s  .  co m
 */
@Override
public void run() {
    Socket socket = null;
    // set up server socket
    try {
        if (backlog == 0) {
            serverSocket = new ServerSocket(port);
        } else {
            serverSocket = new ServerSocket(port, backlog);
        }
        serverSocket.setSoTimeout(100);
        println("Opened up server socket on port " + port);
    } catch (SocketException e) {
        Control.logOneTime(e.getLocalizedMessage(), Level.SEVERE);
        println(e.getLocalizedMessage());
        System.exit(-1);
    } catch (IOException e) {
        Control.logOneTime(
                "Mailbox error: could not listen on port " + port + ". stacktrace: " + e.getLocalizedMessage(),
                Level.SEVERE);
        e.printStackTrace();
        log.severe(ExceptionUtils.getStackTrace(e));
        System.exit(-1);
    }
    // enter main loop
    while (!shutdown) {
        if (REPORT)
            reportSend.add(report());
        println(report().toJSONString());

        // block until a connection is accepted
        println("Waiting for a connection");
        try {
            socket = serverSocket.accept();
            InetAddress inetaddr = socket.getInetAddress();

            println("Received connection from " + inetaddr);
            // get the message id, then call the appropriate message handler
            acceptMessage(socket);
            // close the socket
            socket.close();
        } catch (SocketTimeoutException e) {
            println("No connection: socket timed out", true);
        } catch (ConnectException e) {
            println("Caught ConnectException", true);
        } catch (SocketException e) {
            println("Caught SocketException", true);
        } catch (IOException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }

        // See if we have any messages to send
        if (msgsSend.size() > 0)
            println("Have " + msgsSend.size() + " messages to send");
        while (msgsSend.size() > 0) {
            MessageWrapper<AbstractMessage> currentMsg = msgsSend.remove();
            println("Current message: " + currentMsg.toString());
            NodeListEntry nle_dest = currentMsg.nle;
            String destID = currentMsg.destID;
            printMessageSize(currentMsg);
            currentMsg.msg.scheduleSend(nodeList, destID, nle_dest);
            println("Mailbox: Message of type " + currentMsg.msg.msgType + " with id# " + currentMsg.msg.msgID
                    + " scheduled for sending to " + nle_dest.toString());
        }
        // check if it's time to shut down (signaled from Control)
        if (shutdown) {
            // write a log message, then exit
            // serverSocket.close()
            println("Mailbox exited");
            return;
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.severe(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.openhab.binding.network.internal.PresenceDetection.java

/**
 * Enables/Disables listing for dhcp packets to figure out if devices have entered the network. This does not work
 * for iOS devices. The hostname of this network service object will be registered to the dhcp request packet
 * listener if enabled and unregistered otherwise.
 *
 * @param enabled Enable/Disable the dhcp listen service for this hostname.
 *//*from  ww w.jav  a 2s .  c o  m*/
private void enableDHCPListen(boolean enabled) {
    if (enabled) {
        try {
            if (DHCPListenService.register(destination.getHostAddress(), this).isUseUnprevilegedPort()) {
                dhcpState = "No access right for port 67. Bound to port 6767 instead. Port forwarding necessary!";
            } else {
                dhcpState = "Running normally";
            }
        } catch (SocketException e) {
            logger.warn("Cannot use DHCP sniffing.", e);
            useDHCPsniffing = false;
            dhcpState = "Cannot use DHCP sniffing: " + e.getLocalizedMessage();
        }
    } else {
        DHCPListenService.unregister(destination.getHostAddress());
        dhcpState = "off";
    }
}

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  www  .j a va  2  s . 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;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.workers.CheckinWorker.java

/**
 * Upload the given source file to the Team Foundation Server. If a socket
 * exception is encountered uploading the file, the upload is retried one
 * time.// w ww.j a v a  2s.c o m
 * <p>
 * If another exception is thrown, no clean-up of the source file is
 * performed (the caller must handle this condition).
 *
 * @param uncompressedSourceFile
 *        the uncompressed local file that will be sent to the server, which
 *        must exist (must not be <code>null</code> or empty)
 * @param md5Hash
 *        the pre-computed MD5 hash of the uncompressed source file. If
 *        null, the hash is computed automatically. This parameter exists
 *        for performance reasons (so callers can compute the hash only
 *        once).
 * @throws CoreCancelException
 *         if the upload was cancelled by the user via the
 *         {@link TaskMonitor}.
 */
private void upload(final String uncompressedSourceFile, final byte[] md5Hash) throws CoreCancelException {
    Check.notNullOrEmpty(uncompressedSourceFile, "uncompressedSourceFile"); //$NON-NLS-1$
    Check.notNull(md5Hash, "md5Hash"); //$NON-NLS-1$

    File compressedFile = null;

    try {
        /*
         * Define the multi part message permanent parts.
         */
        final Part[] parts = new Part[7];
        parts[0] = new StringPart(VersionControlConstants.SERVER_ITEM_FIELD, change.getServerItem(),
                partCharSet);
        parts[1] = new StringPart(VersionControlConstants.WORKSPACE_NAME_FIELD, workspace.getName(),
                partCharSet);
        parts[2] = new StringPart(VersionControlConstants.WORKSPACE_OWNER_FIELD, workspace.getOwnerName(),
                partCharSet);

        final long uncompressedFileLength = new File(uncompressedSourceFile).length();
        parts[3] = new StringPart(VersionControlConstants.LENGTH_FIELD, Long.toString(uncompressedFileLength),
                partCharSet);

        /*
         * Force ASCII encoding for the hash string (because we declare
         * UTF-8 and ASCII is a strict subset).
         */
        final String hashString = new String(Base64.encodeBase64(md5Hash), "US-ASCII"); //$NON-NLS-1$

        parts[4] = new StringPart(VersionControlConstants.HASH_FIELD, hashString, partCharSet);
        // part 5 is the chunk byte range.
        // part 6 is the chunk content.

        /*
         * Compress the file to a temporary file if possible.
         */
        if (0 < uncompressedFileLength && uncompressedFileLength < MAX_GZIP_INPUT_SIZE) {
            compressedFile = compressToTempFile(uncompressedSourceFile);
        }

        /*
         * Use the uncompressed file if compression increases the file size.
         */
        final File uploadFile;
        final String contentType;
        if (compressedFile == null || compressedFile.length() > uncompressedFileLength) {
            uploadFile = new File(uncompressedSourceFile);
            contentType = UNCOMPRESSED;
        } else {
            uploadFile = compressedFile;
            contentType = COMPRESSED;
        }

        int attempt = 0;
        do {
            attempt++;

            try {
                if (userCancellationMonitor.isCanceled()) {
                    throw new CoreCancelException();
                }

                retryableUpload(uploadFile, parts, contentType);

                /*
                 * Upload succeeded.
                 */
                return;
            } catch (final SocketException e) {
                log.warn(MessageFormat.format("SocketException during {0} attempt to upload the file {1}", //$NON-NLS-1$
                        attempt, uncompressedSourceFile), e);

                if (attempt < MAX_FILE_RETRY_ATTEMPTS) {
                    log.info("Retrying"); //$NON-NLS-1$
                } else {
                    final String message = MessageFormat.format(
                            Messages.getString(
                                    "CheckinEngineUploadWorker.SocketExceptionDuringUploadRetryFormat"), //$NON-NLS-1$
                            e.getLocalizedMessage());

                    throw new VersionControlException(message, e);
                }
            }
        } while (true);
    } catch (final IOException e) {
        throw new VersionControlException(e);
    } finally {
        if (compressedFile != null && compressedFile.exists()) {
            try {
                compressedFile.delete();
            } catch (final Exception e) {
                // do nothing
            }
        }
    }
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

static String getNetAddressInfo() {
    try {//  w ww. j  av a2 s  .com
        StringBuffer sb = new StringBuffer();

        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String addr = inetAddress.getHostAddress();

                    if (!TextUtils.isEmpty(addr)) {
                        if (sb.length() == 0) {
                            sb.append(addr);
                        } else {
                            sb.append(", ").append(addr); //$NON-NLS-1$
                        }
                    }
                }
            }
        }

        String netAddress = sb.toString();

        if (!TextUtils.isEmpty(netAddress)) {
            return netAddress;
        }
    } catch (SocketException e) {
        Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
    }

    return null;
}