Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

In this page you can find the example usage for java.net UnknownHostException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.dragonflow.StandardMonitor.URLOriginalMonitor.java

/**
 * // w w w  .  jav a2s .c o m
 */
private static long[] checkInternalURL(SocketSession socketsession, String s, String s1, String s2, String s3,
        String s4, String s5, String s6, String s7, Array array, String s8, String s9, String s10,
        StringBuffer stringbuffer, long l, String s11, int i, long l1, StringBuffer stringbuffer1,
        StringBuffer stringbuffer2) {
    String s12 = "";
    if (s.lastIndexOf('#') != -1) {
        s = s.substring(0, s.lastIndexOf('#'));
    }
    if ((debugURL & kDebugRequest) != 0) {
        LogManager.log("RunMonitor", "checking URL... " + s);
    }
    int j = 0;
    if (socketsession.context.getSetting("_keepTryingForGoodStatus").length() > 0) {
        j = TextUtils.toInt(socketsession.context.getSetting("_keepTryingForGoodStatus"));
    }
    long l2 = kURLNoStatusError;
    long l3 = 0L;
    long l4 = System.currentTimeMillis();
    long l6 = 0L;
    long l7 = 0L;
    long l8 = 0L;
    long l9 = 0L;
    long l10 = 0L;
    long l11 = 0L;
    long l12 = 0L;
    boolean flag = false;
    URLInfo urlinfo = new URLInfo(s);
    String s16 = urlinfo.getProtocol();
    String s17 = urlinfo.getHost();
    int k = urlinfo.getConnectPort();
    boolean flag1 = false;
    boolean flag2 = false;
    if (SocketStream.getSSLFactory() != null) {
        flag1 = true;
        if (socketsession.context.getSetting("_sslJavaEnabled").length() > 0) {
            flag1 = true;
        } else if (socketsession.context.getSetting("_sslJavaDisabled").length() > 0) {
            flag1 = false;
        }
    }
    boolean flag3 = false;
    if (s8.startsWith(NT_CHALLENGE_RESPONSE_TAG)) {
        s8 = s8.substring(NT_CHALLENGE_RESPONSE_TAG.length());
        flag3 = true;
    }
    boolean flag4 = false;
    if (socketsession.context.getSetting("_urlMonitorUseApacheHttpClient").length() > 0) {
        flag4 = true;
    }
    SocketStream socketstream = null;
    String s18 = getUserAgent(array);
    if (s18.length() == 0) {
        s18 = socketsession.context.getSetting("_URLUserAgent");
    }
    String s19 = getSslgetOptions(array);
    if (s19.length() == 0) {
        s19 = socketsession.context.getSetting("_sslgetOptions");
    }
    String s20 = socketsession.context.getSetting("_URLMonitorProxyExceptions");
    String s21 = null;
    String s22 = "";
    String s23 = "";
    String s25 = "";
    String s26 = getContentType(array);
    String s27 = encodeParameters(array, s26);
    socketsession.addCookieParameters(array, s);
    if (stringbuffer == null) {
        stringbuffer = new StringBuffer(kURLBufferSize);
    }
    boolean flag5 = socketsession.context.getSetting("_concatURLRedirects").length() != 0;
    if (flag5 && concatBuffer == null) {
        concatBuffer = new StringBuffer(kURLBufferSize);
    }
    if (s8.length() > 0) {
        Base64Encoder base64encoder = new Base64Encoder(s8 + ":" + s9);
        s22 = "Authorization: Basic " + base64encoder.processString() + CRLF;
    }
    if (s6.length() > 0) {
        Base64Encoder base64encoder1 = new Base64Encoder(s6 + ":" + s7);
        String s24 = base64encoder1.processString();
        s25 = "Proxy-Authorization: Basic " + s24 + CRLF;
    }
    long l13 = l1 - System.currentTimeMillis();
    long l14 = l13 / 1000L;
    long l15 = -1L;
    CounterLock counterlock;

    // 617
    try {
        if (s10.length() != 0) {
            String s28 = "";
            if (s27.length() > 0) {
                s28 = HTTPRequest.encodeString(s27);
            }
            String s32;
            if (s10.indexOf("get.exe") != -1) {
                String s36 = socketsession.context.getSetting("_URLRemoteOptions");
                if (s36.length() == 0) {
                    s36 = "-ignoreErrors+-ignoreUnknownCA+-x";
                }
                if (flag3 && !s8.startsWith(NT_CHALLENGE_RESPONSE_TAG)) {
                    s8 = NT_CHALLENGE_RESPONSE_TAG + s8;
                }
                if (s18.length() > 0) {
                    if (s28.length() > 0) {
                        s28 = s28 + URLEncoder.encode("&");
                    }
                    s28 = s28 + URLEncoder.encode("User-Agent: " + s18);
                }
                if (s19.length() > 0) {
                    if (s28.length() > 0) {
                        s28 = s28 + URLEncoder.encode("&");
                    }
                    s28 = s28 + URLEncoder.encode("sslgetOptions: " + s19);
                }
                if (s11.length() > 0) {
                    String as[] = TextUtils.split(s11, CRLF);
                    for (int k1 = 0; k1 < as.length; k1++) {
                        if (s28.length() > 0) {
                            s28 = s28 + URLEncoder.encode("&");
                        }
                        if (getHeaderType(as[k1]) < 0) {
                            s28 = s28 + URLEncoder.encode("Custom-Header: ");
                        }
                        String s46 = as[k1];
                        int i3 = s46.indexOf("&");
                        if (i3 >= 0 && !s46.startsWith(URLSequenceMonitor.refererStartToken)) {
                            s46 = s46.substring(0, i3);
                        }
                        s28 = s28 + URLEncoder.encode(s46);
                    }

                }
                String s13 = socketsession.getCookieHeader(s, true);
                if (s13.length() > 0) {
                    String s40 = "";
                    if (s36.endsWith("-x")) {
                        s40 = "-x";
                        s36 = s36.substring(0, s36.length() - 2);
                    }
                    String as2[] = TextUtils.split(s13, CRLF);
                    for (int j2 = 0; j2 < as2.length; j2++) {
                        s36 = s36 + "-c+%22" + URLEncoder.encode(as2[j2]) + "%22+";
                    }

                    s36 = s36 + s40;
                }
                s32 = s10 + "?" + s36 + "+%22" + URLEncoder.encode(s) + "%22" + "+%22" + l14 + "%22" + "+%22"
                        + URLEncoder.encode(s8) + "%22" + "+%22" + URLEncoder.encode(s9) + "%22" + "+%22" + s28
                        + "%22" + "+%22" + URLEncoder.encode(s5) + "%22" + "+%22" + URLEncoder.encode(s6)
                        + "%22" + "+%22" + URLEncoder.encode(s7) + "%22";
            } else if (s10.indexOf("port.exe") != -1) {
                s32 = s10 + "&host=" + s;
            } else {
                s32 = s10 + "?host=" + s;
            }
            Array array2 = null;
            String s41 = "";
            String s43 = "";
            String s47 = "";
            String s49 = "";
            String s51 = "";
            String s54 = "";
            String s56 = "";
            if (Platform.isPortal()) {
                String s59 = HTTPUtils.getLocationIDByURL(s10);
                if (Portal.isPortalID(s59)) {
                    PortalSiteView portalsiteview = (PortalSiteView) Portal.getSiteViewForID(s59);
                    if (portalsiteview != null) {
                        s41 = portalsiteview.getProperty(PortalSiteView.pUserName);
                        s43 = portalsiteview.getProperty(PortalSiteView.pPassword);
                        s49 = portalsiteview.getProperty(PortalSiteView.pProxy);
                        s51 = portalsiteview.getProperty(PortalSiteView.pProxyUserName);
                        s54 = portalsiteview.getProperty(PortalSiteView.pProxyPassword);
                    }
                }
            }
            int k3 = i;
            if (socketsession.context == null)
                ;
            CounterLock counterlock1 = null;
            if (!socketsession.inRemoteRequest) {
                counterlock1 = getLocationLock(socketsession.context, s10, s);
            }
            try {
                long l18 = System.currentTimeMillis() + (l14 + 30L) * 1000L;
                socketsession.inRemoteRequest = true;
                long al2[] = check1URL(socketsession, s32, s1, s2, s3, s4, s49, s51, s54, array2, s41, s43, s47,
                        stringbuffer, l, s56, k3, l18, stringbuffer1, stringbuffer2);
                l2 = al2[0];
                if (j > 0) {
                    l2 = getURLStatus_ForBackupToRegularMeansOnly(socketsession, l2, s32, 0, j);
                }
                if (debugURL != 0) {
                    System.out.println("Status1: " + l2);
                }
                l3 = al2[1];
            } finally {
                socketsession.inRemoteRequest = false;
                if (counterlock1 != null) {
                    releaseLocationLock(counterlock1);
                }
            }

            String s65 = stringbuffer.toString();
            int i4 = s65.length();
            stringbuffer.setLength(0);
            int j4 = 0;
            while (j4 < i4) {
                int k4 = s65.indexOf("\r\r\n", j4);
                if (k4 < 0) {
                    stringbuffer.append(s65.substring(j4));
                    break;
                }
                stringbuffer.append(s65.substring(j4, k4) + "\r\n");
                j4 = k4 + 3;
            }

            String s68 = stringbuffer.toString();
            if (s10.indexOf("get.exe") != -1) {
                String s70 = "URLMonitorDuration: ";
                int k5 = s68.lastIndexOf(s70);
                if (k5 != -1) {
                    l3 = TextUtils.toLong(s68.substring(k5 + s70.length(), k5 + s70.length() + 10));
                }
                s70 = "URLMonitorStatus: ";
                k5 = s68.lastIndexOf(s70);
                long l21 = l2;
                if (k5 != -1) {
                    l21 = TextUtils.toLong(s68.substring(k5 + s70.length(), k5 + s70.length() + 10));
                }
                if (l21 != 200L || l2 != (long) kURLContentMatchError && l2 != (long) kURLContentErrorFound) {
                    if (k5 != -1) {
                        l2 = l21;
                        if (debugURL != 0) {
                            System.out.println("Status2 ssl: " + l2);
                        }
                    } else {
                        int j6 = s68.length();
                        if (j6 > 500) {
                            j6 = 500;
                        }
                        String s78 = s68.substring(0, j6);
                        if (j > 0) {
                            l21 = getURLStatus_ForBackupToRegularMeansOnly(socketsession, l21, s32, 0, j);
                        }
                        LogManager.log("Error", "Remote URL error, [" + HTTPUtils.getLocationIDByURL(s10) + "] "
                                + lookupStatus(l2) + ", " + s10 + ", " + s + ", detail: " + s78);
                        l2 = kURLRemoteMonitoringError;
                        if (debugURL != 0) {
                            System.out.println("Status3 kURLRemoteMonitoringError: " + l2);
                        }
                    }
                }
            }
            s68 = getHTTPContent(s68);
            int i5 = s68.lastIndexOf("\r\nURLMonitorStatus: ");
            if (i5 >= 0) {
                s68 = s68.substring(0, i5);
            }
            stringbuffer.setLength(0);
            stringbuffer.append(s68);
            l12 = stringbuffer.length();
        } else {

            if (flag3 || s16.equals("https") && !flag1 || flag4) {
                flag2 = true;
                counterlock = null;
                try {
                    if (s16.equals("https")) {
                        counterlock = getSSLGroupLock(socketsession.context);
                    }
                    if (flag4) {
                        Vector vector = new Vector();
                        if (socketsession.context.getSetting("_sslKeepAlive").length() > 0) {
                            if (s5.length() > 0) {
                                vector.add(new Header("Proxy-Connection", "Keep-Alive"));
                            } else {
                                vector.add(new Header("Connection", "Keep-Alive"));
                            }
                        }
                        vector.add(new Header("User-Agent", s18));
                        Header header = socketsession.getCookieHeader(s);
                        if (header != null) {
                            vector.add(header);
                        }
                        if (s27.length() > 0) {
                            vector.add(new Header("Content-Type", s26));
                        }
                        String s42 = "";
                        HTTPRequestSettings httprequestsettings = new HTTPRequestSettings(s, s8, s9, s42, null,
                                s5, s6, s7, vector, 1, (int) l13, (int) l13);
                        StringBuffer stringbuffer3 = new StringBuffer();
                        ApacheHttpMethod apachehttpmethod = null;
                        long l17 = System.currentTimeMillis();
                        apachehttpmethod = ApacheHttpUtils.getRequest(httprequestsettings, stringbuffer3);
                        l3 = System.currentTimeMillis() - l17;
                        l2 = apachehttpmethod.getStatusCode();
                        if (apachehttpmethod.getResponseBodyAsString() != null) {
                            stringbuffer2.append(apachehttpmethod.getResponseBodyAsString());
                        }
                        if (apachehttpmethod.getResponseBody() != null) {
                            l12 = apachehttpmethod.getResponseBody().length;
                        }
                    } else {
                        if (s5 == null) {
                            s5 = "";
                        }
                        Array array1 = new Array();
                        array1.add(Platform.getRoot() + "/tools/sslget");
                        if (s19.length() > 0) {
                            Array array3 = Platform.split(' ', s19);
                            Enumeration enumeration = array3.elements();
                            while (enumeration.hasMoreElements()) {
                                array1.add(enumeration.nextElement());
                            }
                        }
                        if (socketsession.context.getSetting("_sslKeepAlive").length() > 0) {
                            array1.add("-keepAlive");
                        }
                        boolean flag6 = socketsession.context.getSetting("_urlUnixSSL").length() == 0;
                        array1.add("-agent");
                        array1.add("\"" + s18 + "\"");
                        String s14 = s11;
                        s14 = socketsession.getCookieHeader(s, flag6) + s14;
                        if (s14.length() > 0) {
                            String as1[] = TextUtils.split(s14, CRLF);
                            for (int i2 = 0; i2 < as1.length; i2++) {
                                array1.add("-c");
                                array1.add("\"" + as1[i2] + "\"");
                            }

                        }
                        if (s27.length() > 0) {
                            array1.add("-c");
                            array1.add("\"" + CONTENT_TYPE_HEADER + s26 + "\"");
                        }
                        if (array != null) {
                            Enumeration enumeration1 = array.elements();
                            while (enumeration1.hasMoreElements()) {
                                String s44 = (String) enumeration1.nextElement();
                                if (TextUtils.startsWithIgnoreCase(s44, CUSTOM_HEADER)) {
                                    array1.add("-c");
                                    array1.add("\"" + s44.substring(CUSTOM_HEADER.length()) + "\"");
                                }
                            }
                        }
                        array1.add("-x");
                        array1.add(s);
                        array1.add("" + l14);
                        array1.add("\"" + s8 + "\"");
                        array1.add("\"" + s9 + "\"");
                        array1.add("\"" + s27 + "\"");
                        if (!hostIsProxyException(s20, s)) {
                            array1.add("\"" + s5 + "\"");
                        } else {
                            array1.add("\"\"");
                        }
                        array1.add("\"" + s6 + "\"");
                        array1.add("\"" + s7 + "\"");
                        SSLCounter++;
                        if (sslLock.current() == 0) {
                            LogManager.log("RunMonitor",
                                    "ssl block, " + ((sslLock.max - sslLock.current()) + 1) + ", " + s);
                        } else {
                            LogManager.log("RunMonitor", "ssl start, " + SSLCounter + ", " + s);
                        }
                        Array array4 = new Array();
                        l2 = sendSSLRequest(urlinfo.getHost(), socketsession, array1, sslLock, array4);
                        if (debugURL != 0) {
                            System.out.println("Status4 sendSSLRequest: " + l2);
                        }
                        SSLCounter--;
                        Enumeration enumeration2 = array4.elements();
                        int k2 = 0;
                        boolean flag7 = false;
                        l12 = -1L;
                        String s52 = "URLMonitorStatus:";
                        String s55 = "URLMonitorDuration:";
                        String s57 = "URLMonitorDNSDuration:";
                        String s60 = "URLMonitorConnectDuration:";
                        String s62 = "URLMonitorResponseDuration:";
                        String s66 = "URLMonitorDownloadDuration:";
                        boolean flag8 = true;
                        while (enumeration2.hasMoreElements()) {
                            String s69 = (String) enumeration2.nextElement();
                            if (stringbuffer2 != null) {
                                stringbuffer2.append(s69 + "\n");
                            }
                            if (++k2 > 2) {
                                int j5 = s69.indexOf(s52);
                                if (j5 >= 0) {
                                    String s71 = s69.substring(s69.length() - 10);
                                    l2 = TextUtils.toLong(s71);
                                    if (debugURL != 0) {
                                        System.out.println("Status5 statusString: " + l2);
                                    }
                                    flag8 = false;
                                }
                                int i6 = s69.indexOf(s55);
                                if (i6 >= 0) {
                                    String s72 = s69.substring(s69.length() - 10);
                                    l3 = TextUtils.toLong(s72);
                                }
                                i6 = s69.indexOf(s57);
                                if (i6 >= 0) {
                                    String s73 = s69.substring(s69.length() - 10);
                                    l6 = TextUtils.toLong(s73);
                                }
                                i6 = s69.indexOf(s60);
                                if (i6 >= 0) {
                                    String s74 = s69.substring(s69.length() - 10);
                                    l7 = TextUtils.toLong(s74);
                                }
                                i6 = s69.indexOf(s62);
                                if (i6 >= 0) {
                                    String s75 = s69.substring(s69.length() - 10);
                                    l8 = TextUtils.toLong(s75);
                                }
                                i6 = s69.indexOf(s66);
                                if (i6 >= 0) {
                                    String s76 = s69.substring(s69.length() - 10);
                                    l9 = TextUtils.toLong(s76);
                                }
                                if (k2 == 4 && s69.length() == 0) {
                                    flag7 = true;
                                }
                                if ((!flag7 || k2 % 2 != 0 || s69.length() != 0) && flag8) {
                                    stringbuffer.append(s69);
                                    stringbuffer.append('\n');
                                }
                            }
                        }
                        LogManager.log("RunMonitor", "SSL END, " + SSLCounter + ", " + l3 + "   " + s);
                        l12 = stringbuffer.length();
                    }
                    if (counterlock != null) {
                        releaseSSLGroupLock(counterlock);
                    }
                } catch (Exception exception1) {
                    if (counterlock != null) {
                        releaseSSLGroupLock(counterlock);
                    }
                    throw exception1;
                }
            } else {
                String s29 = urlinfo.getFile();
                String s33 = getHostHeader(array, s17, k, s16);
                String s37 = null;
                int j1 = -1;
                if (s5.length() != 0 && !isProxyException(s20, s17)) {
                    if (!s5.startsWith("http://")) {
                        s5 = "http://" + s5;
                    }
                    j1 = k;
                    s37 = s17;
                    URLInfo urlinfo1 = new URLInfo(s5);
                    s17 = urlinfo1.getHost();
                    k = urlinfo1.getConnectPort();
                    if (!s16.equals("https")) {
                        if (s29.equals("/") && !s.endsWith("/")) {
                            s29 = s + "/";
                        } else {
                            s29 = s;
                        }
                    }
                }
                String s45 = socketsession.getCookieHeader(s, false);
                String s48 = getRequestCommand(array);
                String s50 = socketsession.getVersion();
                String s53 = getRequestProtocol(array);
                if (s53.endsWith("/")) {
                    s53 = s53 + s50;
                }
                String s15 = s11;
                int j3 = -1;
                String s58 = s15;
                if ((j3 = s15.indexOf("&" + URLSequenceMonitor.refererEndToken)) != -1) {
                    s15 = s58.substring(0, j3);
                    s15 = s15 + s58.substring(j3 + ("&" + URLSequenceMonitor.refererEndToken).length());
                }
                if (s15.length() > 0 && !s15.endsWith(CRLF)) {
                    s15 = s15 + CRLF;
                }
                if (array != null) {
                    Enumeration enumeration3 = array.elements();
                    while (enumeration3.hasMoreElements()) {
                        String s63 = (String) enumeration3.nextElement();
                        if (TextUtils.startsWithIgnoreCase(s63, CUSTOM_HEADER)) {
                            s15 = s15 + s63.substring(CUSTOM_HEADER.length()) + CRLF;
                        }
                    }
                }
                String s61 = socketsession.getStreamEncoding();
                String s64 = "";
                if (s61.length() > 0) {
                    s64 = "Accept-charset: " + s61 + CRLF;
                }
                String s67 = s48 + " " + s29 + " " + s53 + CRLF + "User-Agent: " + s18 + CRLF + s64
                        + "Accept: */*" + CRLF + "Host: " + s33 + CRLF + s22 + s25 + s45 + s15;
                if (s27.length() == 0) {
                    s67 = s67 + CRLF;
                } else {
                    if (s61.length() > 0) {
                        s64 = "; charset=" + s61;
                    }
                    s67 = s67 + CONTENT_TYPE_HEADER + s26 + s64 + CRLF + "Content-length: " + s27.length()
                            + CRLF + CRLF + s27;
                }
                long l5 = System.currentTimeMillis();
                long l19 = l5;
                InetAddress inetaddress = InetAddress.getByName(s17);
                long l20 = System.currentTimeMillis();
                l6 = l20 - l19;
                String s77 = Platform.dottedIPString(inetaddress.getAddress()) + ":" + k;
                l19 = l20;
                socketstream = socketsession.connect(s77, inetaddress, k, s16, s37, j1, s6, s7, l1);
                l20 = System.currentTimeMillis();
                l7 = l20 - l19;
                Socket socket = socketstream.socket;
                int k6 = (int) (l1 - System.currentTimeMillis());
                if ((long) k6 <= kTimedOutValue) {
                    throw new InterruptedIOException();
                }
                if (s16.equals("https") && socketsession.context.getSetting("_urlCertDays").length() > 0) {
                    try {
                        SSLSession sslsession = ((SSLSocket) socketstream.socket).getSession();
                        X509Certificate ax509certificate[] = sslsession.getPeerCertificateChain();
                        int j7 = 0;
                        for (int k7 = 0; k7 < ax509certificate.length; k7++) {
                            X509Certificate x509certificate = ax509certificate[k7];
                            long l22 = System.currentTimeMillis();
                            long l23 = l22 + 0x5265c00L;
                            int i8 = 0;
                            while (true) {
                                Date date = new Date(l23);
                                try {
                                    x509certificate.checkValidity(date);
                                } catch (CertificateExpiredException certificateexpiredexception) {
                                    if (i8 == 0) {
                                        i8++;
                                    }
                                    break;
                                } catch (CertificateNotYetValidException certificatenotyetvalidexception) {
                                    break;
                                }
                                i8++;
                                l23 += 0x5265c00L;
                            }

                            if (i8 <= 0) {
                                continue;
                            }
                            if (j7 == 0) {
                                j7 = i8;
                                continue;
                            }
                            if (j7 > i8) {
                                j7 = i8;
                            }
                        }

                        if (j7 > 1) {
                            l15 = j7;
                        }
                        if (j7 == 1) {
                            l15 = 0L;
                        }
                    } catch (SSLPeerUnverifiedException sslpeerunverifiedexception) {
                        /* empty */
                    }
                }
                Platform.setSocketTimeout(socket, k6);
                if ((debugURL & kDebugRequest) != 0) {
                    LogManager.log("RunMonitor", "sending request... " + s67);
                }
                l19 = System.currentTimeMillis();
                socketstream.transmit(s67);
                if (stringbuffer2 != null) {
                    stringbuffer2.append(s67);
                }
                if ((debugURL & kDebugRequest) != 0) {
                    LogManager.log("RunMonitor", "request sent");
                }
                long al3[];
                if (s50.equals("1.0")) {
                    al3 = fillBuffer(socketsession, socketstream, l1, stringbuffer, l, l19);
                } else {
                    al3 = fillBufferParse(s48, socketsession, socketstream, socket, l1, stringbuffer, l, l19);
                }
                if (stringbuffer2 != null) {
                    stringbuffer2.append(stringbuffer.toString());
                }
                if (!socketstream.receivedReply || al3.length > 2 && al3[2] == -1L) {
                    socketstream.receivedEndOfStreamOnFirst = false;
                    LogManager.log("RunMonitor", "reopening connection to " + inetaddress);
                    socketstream.reconnect();
                    l19 = l20;
                    socketstream = socketsession.connect(s77, inetaddress, k, s16, s37, j1, s6, s7, l1);
                    l20 = System.currentTimeMillis();
                    l7 += l20 - l19;
                    Socket socket1 = socketstream.socket;
                    int i7 = (int) (l1 - System.currentTimeMillis());
                    if ((long) i7 <= kTimedOutValue) {
                        throw new InterruptedIOException();
                    }
                    Platform.setSocketTimeout(socket1, i7);
                    if (debugURL != 0) {
                        LogManager.log("RunMonitor", "sending request2..." + s67);
                        System.out.println("URLOriginalMonitor : sending request2..." + s67);
                    }
                    l19 = System.currentTimeMillis();
                    socketstream.transmit(s67);
                    if (stringbuffer2 != null) {
                        stringbuffer2.append(s67);
                    }
                    if (debugURL != 0) {
                        LogManager.log("RunMonitor", "request2 sent");
                        System.out.println("URLOriginalMonitor : request2 sent");
                    }
                    if (s50.equals("1.0")) {
                        al3 = fillBuffer(socketsession, socketstream, l1, stringbuffer, l, l19);
                    } else {
                        al3 = fillBufferParse(s48, socketsession, socketstream, socket1, l1, stringbuffer, l,
                                l19);
                    }
                    if (stringbuffer2 != null) {
                        stringbuffer2.append(stringbuffer.toString());
                    }
                }
                l12 = al3[0];
                l8 = al3[1];
                l20 = System.currentTimeMillis();
                l9 = l20 - l19 - l8;
                l3 = l20 - l5;
                if ((debugURL & kDebugIO) != 0) {
                    LogManager.log("RunMonitor",
                            "total, duration: " + l3 + ", clock: " + System.currentTimeMillis());
                }
            }
        }
        // 5637

        if ((debugURL & kDebugData) != 0) {
            LogManager.log("RunMonitor", "content=" + stringbuffer);
        }
        URLScannerInputStream urlscannerinputstream = new URLScannerInputStream(stringbuffer, l2);
        urlscannerinputstream.parse();
        if (urlscannerinputstream.contentLength != -1L) {
            l12 = urlscannerinputstream.contentLength;
        }
        l10 = urlscannerinputstream.lastModified;
        l11 = urlscannerinputstream.date;
        s21 = urlscannerinputstream.location;
        l2 = urlscannerinputstream.status;
        if (j > 0) {
            l2 = getURLStatus_ForBackupToRegularMeansOnly(socketsession, l2, s, 0, j);
        }
        if (debugURL != 0) {
            System.out.println("Status6 scanner.status: " + l2);
        }
        if ((debugURL & kDebugReply) != 0) {
            if (l2 != 200L) {
                LogManager.log("RunMonitor", "status=" + l2 + ", reply=" + stringbuffer);
            } else {
                LogManager.log("RunMonitor", "status=" + l2);
            }
        }
        if (socketstream != null) {
            socketstream.keepAlive = urlscannerinputstream.isKeepAlive();
        }
        if (!socketsession.inRemoteRequest) {
            flag = urlscannerinputstream.refreshRedirect;
        }
        // 5905
    } catch (UnknownHostException e) {
        l2 = kURLBadHostNameError;
        if (debugURL != 0) {
            System.out.println("Status7 kURLBadHostNameError: " + l2 + " exception: " + e.toString());
        }
    } catch (InterruptedIOException e) {
        l2 = kURLTimeoutError;
        if (debugURL != 0) {
            System.out.println("Status8 kURLTimeoutError: " + l2 + " exception: " + e.toString());
        }
    } catch (SocketException e) {
        if (debugURL != 0) {
            e.printStackTrace();
            LogManager.log("RunMonitor", "socket exception, " + e);
        }
        if (Platform.noRoute(e)) {
            l2 = kURLNoRouteToHostError;
            if (debugURL != 0) {
                System.out.println("Status9 kURLNoRouteToHostError: " + l2 + " exception: " + e.toString());
            }
        } else {
            l2 = kURLNoConnectionError;
            if (debugURL != 0) {
                System.out.println("Status10 kURLNoConnectionError: " + l2 + " exception: " + e.toString());
            }
            if (Platform.isWindows()) {
                l2 = kSSL2NotFoundError;
                if (debugURL != 0) {
                    System.out.println("Status11 kSSL2NotFoundError: " + l2 + " exception: " + e.toString());
                }
            }
        }
    } catch (Exception e) {
        String s34 = e.getClass() + ", " + e.getMessage();
        if (s34.indexOf("SSLException") != -1 && Platform.isWindows()) {
            String s38 = s17 + ":" + k;
            addSSL2Only(s38, s + ", " + s34);
            l2 = kSSL2NotFoundError;
            if (debugURL != 0) {
                System.out.println("Status12 kSSL2NotFoundError: " + l2 + " exception: " + e.toString());
            }
        } else {
            e.printStackTrace();
            l2 = kSSL2NotFoundError;
            if (debugURL != 0) {
                System.out.println("Status13 kSSL2NotFoundError: " + l2 + " exception: " + e.toString());
            }
        }
    } finally {
        if (j > 0) {
            l2 = getURLStatus_ForBackupToRegularMeansOnly(socketsession, l2, s, 0, j);
        }
        if (socketstream != null) {
            if (socketstream.receivedEndOfStreamOnFirst) {
                String s79 = s17 + ":" + k;
                addSSL2Only(s79, s + ", " + " first line null");
                l2 = kSSL2NotFoundError;
                if (debugURL != 0) {
                    System.out.println("Status14 kSSL2NotFoundError: " + l2);
                }
                socketstream.receivedEndOfStreamOnFirst = false;
            }
            socketsession.release(socketstream);
        }
    }

    // 6637

    if (200L < l2 && l2 < 300L && socketsession.context.getSetting("_urlEnable2xxStatus").length() == 0) {
        l2 = 200L;
    }
    if (debugURL != 0) {
        System.out.println("Status15 200: " + l2);
    }
    if (l2 == 301L || l2 == 302L || l2 == 303L || l2 == 307L || flag) {
        if (s21 != null) {
            s21 = TextUtils.unescapeHTML(s21);
            s21 = resolveURL(s21, new URLInfo(s1), "");
            socketsession.refererURL = s21;
            long l16 = socketsession.context.getSettingAsLong("_urlRedirectMax", DEFAULT_MAX_REDIRECTS);
            if ((long) i <= l16) {
                if ((debugURL & kDebugRequest) != 0) {
                    LogManager.log("RunMonitor", "redirect=" + s21);
                }
                socketsession.updateCookies(stringbuffer.toString(), s);
                if (stringbuffer1 != null) {
                    stringbuffer1.setLength(0);
                    stringbuffer1.append(s21);
                }
                if (flag5 && concatBuffer != null) {
                    concatBuffer.append(stringbuffer.toString());
                }
                stringbuffer.setLength(0);
                s8 = socketsession.originalUserName;
                s9 = socketsession.originalPassword;
                long al1[] = check1URL(socketsession, s21, s21, s2, s3, s4, s5, s6, s7, null, s8, s9, s2,
                        stringbuffer, l, s11, i + 1, l1, stringbuffer1, stringbuffer2);
                l2 = al1[0];
                if (j > 0) {
                    l2 = getURLStatus_ForBackupToRegularMeansOnly(socketsession, l2, s21, 0, j);
                }
                if (debugURL != 0) {
                    System.out.println("Status16 redirectResult: " + l2);
                }
                l10 = al1[3];
                l11 = al1[4];
                l3 += al1[1];
                l12 += al1[2];
                l6 += al1[5];
                l7 += al1[6];
                l8 += al1[7];
                l9 += al1[8];
            }
        }
    } else {
        if (l2 == (long) kURLNoStatusError) {
            if (socketsession.context.getSetting("_urlAllowNoStatus").length() > 0) {
                l2 = kURLok;
                if (debugURL != 0) {
                    System.out.println("Status17 kURLok: " + l2);
                }
            } else {
                LogManager.log("Error", "URL missing status: " + s);
            }
        }
        if (flag5 && concatBuffer != null) {
            concatBuffer.append(stringbuffer.toString());
            stringbuffer.setLength(0);
            stringbuffer.append(concatBuffer.toString());
            concatBuffer = null;
        }
        String s30 = I18N.UnicodeToString(stringbuffer.toString(), I18N.nullEncoding());
        if (l2 == 200L && s4.length() != 0) {
            int i1 = TextUtils.matchExpression(s30, s4);
            if (i1 != Monitor.kURLok && I18N.hasUnicode(s4)) {
                String s39 = getHTMLEncoding(s30);
                i1 = TextUtils.matchExpression(s30, I18N.UnicodeToString(s4, s39));
            }
            if (i1 == 200) {
                l2 = kURLContentErrorFound;
            }
            if (debugURL != 0) {
                System.out.println("Status18 kURLContentErrorFound: " + l2);
            }
        }
        if (l2 == 200L && s3.length() != 0) {
            l2 = TextUtils.matchExpression(s30, s3);
            if (debugURL != 0) {
                System.out.println("Status19 TextUtils.matchExpression(contents,match): " + l2);
            }
            if (l2 != (long) Monitor.kURLok && I18N.hasUnicode(s3)) {
                String s35 = getHTMLEncoding(s30);
                l2 = TextUtils.matchExpression(s30, I18N.UnicodeToString(s3, s35));
                if (debugURL != 0) {
                    System.out.println(
                            "Status20 TextUtils.matchExpression(contents, I18N.UnicodeToString(match,encoding): "
                                    + l2);
                }
            }
        }
    }
    if (socketsession.context.getSetting("_urlDetailLogEnabled").length() > 0 && s.indexOf("get.exe") == -1) {
        String s31 = "";
        if (s10.length() > 0) {
            s31 = "[" + HTTPUtils.getLocationIDByURL(s10) + "]";
        }
        LogManager.log(socketsession.context.getSetting(pURLLogName),
                s31 + s + "\t" + l2 + "\t" + l3 + "\t" + l12 + "\t" + l10 + "\t" + l11 + "\t" + l6 + "\t" + l7
                        + "\t" + l8 + "\t" + l9 + "\t" + socketsession.context.getProperty(pName) + "\t"
                        + socketsession.context.getProperty(pGroupID) + "\t"
                        + socketsession.context.getProperty(pID));
    }
    if (!socketsession.inRemoteRequest) {
        internalURLs++;
        internalURLBytes += l12;
        internalURLDuration += l3;
        if (l2 != 200L) {
            internalURLErrors++;
        }
    }
    if (s10.length() > 0) {
        internalRemoteURLs++;
        internalRemoteBytes += l12;
        internalRemoteDuration += l3;
        if (l2 != 200L) {
            internalRemoteErrors++;
        }
    } else if (s16.equals("https")) {
        if (flag2) {
            internalSecureURLs++;
            internalSecureBytes += l12;
            internalSecureDuration += l3;
            if (l2 != 200L) {
                internalSecureErrors++;
            }
        } else {
            internalSecureJavaURLs++;
            internalSecureJavaBytes += l12;
            internalSecureJavaDuration += l3;
            if (l2 != 200L) {
                internalSecureJavaErrors++;
            }
        }
    } else if (!socketsession.inRemoteRequest) {
        internalJavaURLs++;
        internalJavaBytes += l12;
        internalJavaDuration += l3;
        if (l2 != 200L) {
            internalJavaErrors++;
        }
    }
    long al[] = new long[10];
    al[0] = l2;
    if (debugURL != 0) {
        System.out.println("Status21 #############################results[0]: " + l2);
    }
    al[1] = l3;
    al[2] = l12;
    al[3] = l10;
    al[4] = l11;
    al[5] = l6;
    al[6] = l7;
    al[7] = l8;
    al[8] = l9;
    al[9] = l15;
    return al;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*from   www.j  ava  2 s .  c o m*/
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:com.clustercontrol.poller.impl.WbemPollerImpl.java

/**
 * ?//w ww  .ja  v  a 2  s  . co m
 * IP?DataTable????
 * ????DataTable??
 * 
 * @param ipAddress IP
 * @param port ??
 * @param protocol 
 * @param user 
 * @param password 
 * @param nameSpace ???
 * @param retries ????
 * @param timeout ??
 * @param cimList CIM??
 * @param indexCheckFlg ???????????
 */
@SuppressWarnings("unchecked")
public DataTable polling(String ipAddress, int port, String protocol, String user, String password,
        String nameSpace, int retries, int timeout, Set<String> cimList // cim????
) {
    // ?
    init();

    if (port < 0) {
        m_log.debug("set Port. " + port + " to " + DEFAULT_PORT);
        port = DEFAULT_PORT;
    }

    // ?
    if (retries < 0) {
        m_log.debug("set Retries. " + retries + " to " + DEFAULT_RETRIES);
        retries = DEFAULT_RETRIES;
    }

    if (timeout < 0) {
        m_log.debug("set Timeout. " + timeout + " to " + DEFAULT_TIMEOUT);
        timeout = DEFAULT_TIMEOUT;
    }

    // ????
    DataTable dataTable = new DataTable();

    m_ipAddress = ipAddress;
    try {
        InetAddress address = InetAddress.getByName(ipAddress);
        if (address instanceof Inet6Address) {
            m_ipAddress = "[" + m_ipAddress + "]";
        }
    } catch (UnknownHostException e) {
        m_log.warn("polling() ipAddress = " + ipAddress, e);
    }
    m_cimAgentAddress = protocol + "://" + m_ipAddress + ":" + port;

    if (nameSpace != null) {
        m_nameSpace = nameSpace;
    }

    // ?
    if (m_log.isDebugEnabled()) {
        m_log.debug("polling() start : " + m_ipAddress.toString());
        m_log.debug("Port            : " + port);
        m_log.debug("Protocol        : " + protocol);
        m_log.debug("User            : " + user);
        m_log.debug("Password        : " + password);
        m_log.debug("Retries         : " + retries);
        m_log.debug("Timeout         : " + timeout);
        m_log.debug("URL             : " + m_cimAgentAddress);
    }

    long enumerationStart = HinemosTime.currentTimeMillis();

    CIMClient cimClient = null;

    try {

        // *****************************
        // 1. Create user credentials
        // *****************************
        UserPrincipal userPr = new UserPrincipal(user);
        PasswordCredential pwCred = new PasswordCredential(password.toCharArray());

        // *****************************
        // 2. Set NameSpace
        // - URL is set like: http(s)://<IP>:Port
        // - Namespace does not need to be specified in COPs if set in this constuctor
        // - There is no server authentication being done. Thus: No need for a truststore
        // *****************************
        CIMNameSpace ns = new CIMNameSpace(m_cimAgentAddress, m_nameSpace);

        // *****************************
        // 3. Create CIM Client
        // *****************************
        cimClient = new CIMClient(ns, userPr, pwCred);

        // *****************************
        // 4. Create Session Properties
        // *****************************
        SessionProperties properties = cimClient.getSessionProperties();
        if (properties == null) {
            properties = new SessionProperties();
            cimClient.setSessionProperties(properties);
        }
        properties.setHttpTimeOut(timeout);

        m_cimText = new String[cimList.size()];

        // ??????HashMap?
        HashMap<String, ArrayList<String>> requestMap = new HashMap<String, ArrayList<String>>();
        String cimClass = "";
        String cimProperty = "";
        ArrayList<String> propertyList = null;

        int i = 0;
        for (String cimText : cimList) {

            m_cimText[i] = cimText;

            String[] targetValue = m_cimText[i].split("\\.");
            cimClass = targetValue[0];
            cimProperty = targetValue[1];

            propertyList = requestMap.get(cimClass);

            // ????????
            if (propertyList != null && propertyList.size() != 0) {
                propertyList.add(cimProperty);
            }
            // ???????????
            else {
                propertyList = new ArrayList<String>();
                propertyList.add(cimProperty);
                requestMap.put(cimClass, propertyList);
            }

            i++;
        }

        CIMObjectPath cop = null;
        CIMInstance ci = null;
        CIMValue value = null;
        Enumeration<CIMInstance> enm = null;

        // ???
        for (int j = 0; j < retries; j++) {
            boolean errorFlg = false;
            m_retMap = new HashMap<String, CIMValue>();
            try {
                for (Map.Entry<String, ArrayList<String>> cimClassEntry : requestMap.entrySet()) {
                    cimClass = cimClassEntry.getKey();
                    propertyList = cimClassEntry.getValue();

                    m_log.debug("CIMClass : " + cimClassEntry.getKey());

                    cop = new CIMObjectPath(cimClassEntry.getKey());
                    enm = cimClient.enumInstances(cop, true);

                    i = 0;
                    while (enm.hasMoreElements()) {

                        ci = enm.nextElement();

                        for (String property : propertyList) {
                            cimProperty = property;

                            if (ci.getProperty(cimProperty) != null) {

                                value = ci.getProperty(cimProperty).getValue();

                                // ????5?1???
                                // CIM??????????????
                                // 
                                // ?????Array index out of range: 0??
                                // test code
                                /*
                                if(value.getType().getType() == CIMDataType.STRING_ARRAY){
                                   testCounter ++;
                                   if (testCounter > 10) {
                                      value = new CIMValue(new Vector<String>(),
                                            new CIMDataType(CIMDataType.STRING_ARRAY));
                                      testCounter = 0;
                                   }
                                }
                                 */
                                // test code

                                if (!checkCIMData(value)) {
                                    errorFlg = true;
                                    continue;
                                    /*
                                     * ??????????
                                     * (???????????????)
                                     */
                                }
                                m_retMap.put(cimClass + "." + cimProperty + "." + i, value);

                            }
                        }
                        if (errorFlg) {
                            break;
                        }
                        i++;
                    }
                    if (errorFlg) {
                        break;
                    }
                }
            } catch (CIMException e) {
                errorFlg = true;
                for (String property : propertyList) {
                    dataTable.putValue(new TableEntry(getEntryKey(cimClass + "." + property + ".0"),
                            HinemosTime.currentTimeMillis(), ErrorType.IO_ERROR, e));
                }
                m_log.warn("polling() warning :" + m_ipAddress.toString() + ", cimClass=" + cimClass + ", ID="
                        + e.getID() + ", message=" + e.getMessage());
            } catch (Exception e) {
                errorFlg = true;
                for (String property : propertyList) {
                    dataTable.putValue(new TableEntry(getEntryKey(cimClass + "." + property + ".0"),
                            HinemosTime.currentTimeMillis(), ErrorType.IO_ERROR, e));
                }
                m_log.warn("polling() warning :" + m_ipAddress.toString() + ", " + cimClass
                        + " unforeseen error. " + e.getMessage(), e);
            } finally {
                if (errorFlg) {
                    // m_retMap = new HashMap<String, CIMValue>();
                    /*
                     * ???????????m_retMap?
                     * ???
                     */
                } else {
                    break;
                }
            }
        }
    } catch (RuntimeException e) {
        m_log.warn("polling() warning :" + m_ipAddress.toString() + " unforeseen error. " + e.getMessage(), e);
    } finally {
        if (cimClient != null) {
            try {
                cimClient.close();
            } catch (Exception e) {
                m_log.warn("polling():" + m_ipAddress.toString() + " Session close failed", e);
            }
        }
    }

    long enumerationStop = HinemosTime.currentTimeMillis();

    // ?
    if (m_log.isDebugEnabled()) {
        m_log.debug("polling() end : time : " + (enumerationStop - enumerationStart));
    }

    // ***************
    // ?? (?)
    // ***************
    try {
        // ?????????????
        if (m_retMap == null || m_retMap.size() == 0) {
            m_log.debug("wbemReceived() : " + m_ipAddress.toString() + " result is empty");
            return dataTable;
        }

        long time = HinemosTime.currentTimeMillis(); // ?

        for (Map.Entry<String, CIMValue> entry : m_retMap.entrySet()) {
            String cimString = entry.getKey();
            CIMValue value = entry.getValue();

            if (value.getType().getType() == CIMDataType.UINT8) {
                long ret = ((UnsignedInt8) value.getValue()).longValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);
            } else if (value.getType().getType() == CIMDataType.UINT16) {
                long ret = ((UnsignedInt16) value.getValue()).longValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);
            } else if (value.getType().getType() == CIMDataType.UINT32) {
                long ret = ((UnsignedInt32) value.getValue()).longValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);
            } else if (value.getType().getType() == CIMDataType.UINT64) {
                BigInteger bigInt = ((UnsignedInt64) value.getValue()).bigIntValue();
                long ret = bigInt.longValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);
            } else if (value.getType().getType() == CIMDataType.STRING) {
                String ret = (String) value.getValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);

            } else if (value.getType().getType() == CIMDataType.STRING_ARRAY) {

                Vector<String> ret = (Vector<String>) value.getValue();
                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);
            } else if (value.getType().getType() == CIMDataType.DATETIME) {

                CIMDateTime sdt = (CIMDateTime) value.getValue();

                // CIMDateTime?Calendar?
                Calendar cal = sdt.getCalendar();

                // Calendar??????????
                long ret = cal.getTimeInMillis() / 1000;

                dataTable.putValue(getEntryKey(cimString), time, ret);

                m_log.debug("polling() dataTable put : " + "entryKey : " + getEntryKey(cimString) + ", time : "
                        + time + ", value : " + ret);

            } else {
                m_log.debug("polling() data type is nothing");
            }

        }
    } catch (Exception e) { // ?????????
        m_log.warn("polling() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);

        // ?????
        dataTable.clear();
        for (Map.Entry<String, CIMValue> entry : m_retMap.entrySet()) {
            final String entryKey = getEntryKey(entry.getKey());
            dataTable
                    .putValue(new TableEntry(entryKey, HinemosTime.currentTimeMillis(), ErrorType.IO_ERROR, e));
        }
    }
    return dataTable;
}

From source file:net.wastl.webmail.server.WebMailServlet.java

/**
 * Handle a request to the WebMail servlet. This is the central method of
 * the WebMailServlet. It first gathers all of the necessary information
 * from the client, then either creates or gets a Session and executes the
 * URL handler for the given path./*  ww  w .j  av  a2s . c o m*/
 */
public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest) req1;
    final HttpServletResponse res = (HttpServletResponse) res1;
    final HTTPRequestHeader http_header = new HTTPRequestHeader();

    if (req.getServletPath().equals("/admin"))
        try {
            log.debug("Forwarding /admin request back to self");
            req.getRequestDispatcher("WebMail/admin").forward(req1, res1);
            return;
        } catch (IOException ioe) {
            log.fatal("Forward from '/admin' failed", ioe);
            throw new ServletException(ioe.getMessage());
        }

    final Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        final String s = (String) en.nextElement();
        http_header.setHeader(s, req.getHeader(s));
    }

    http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo());

    InetAddress addr;
    try {
        addr = InetAddress.getByName(req.getRemoteHost());
    } catch (final UnknownHostException e) {
        try {
            addr = InetAddress.getByName(req.getRemoteAddr());
        } catch (final Exception ex) {
            throw new ServletException("Remote host must identify!");
        }
    }

    HTMLDocument content = null;
    final int err_code = 400;
    HTTPSession sess = null;

    /*
     * Here we try to parse the MIME content that the Client sent in his
     * POST since the JServ doesn't do that for us:-( At least we can use
     * the functionality provided by the standalone server where we need to
     * parse the content ourself anyway.
     */
    try {
        final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());

        /*
         * First we try to use the Servlet API's methods to parse the
         * parameters. Unfortunately, it doesn't know how to handle MIME
         * multipart POSTs, so we will have to handle that ourselves
         */

        /*
         * First get all the parameters and set their values into
         * http_header
         */
        Enumeration enum2 = req.getParameterNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setContent(s, req.getParameter(s));
            // log.info("Parameter "+s);
        }

        /* Then we set all the headers in http_header */
        enum2 = req.getHeaderNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setHeader(s, req.getHeader(s));
        }

        /*
         * In Servlet API 2.2 we might want to fetch the attributes also,
         * but this doesn't work in API 2.0, so we leave it commented out
         */
        // enum2=req.getAttributeNames();
        // while(enum2.hasMoreElements()) {
        // String s=(String)enum2.nextElement();
        // log.info("Attribute "+s);
        // }

        /* Now let's try to handle multipart/form-data posts */

        if (req.getContentType() != null
                && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) {
            final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size"));
            final MultipartParser mparser = new MultipartParser(req, size);
            Part p;
            while ((p = mparser.readNextPart()) != null) {
                if (p.isFile()) {
                    final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size);
                    bs.setName(((FilePart) p).getFileName());
                    bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName()));
                    http_header.setContent(p.getName(), bs);
                    log.info("File name " + bs.getName());
                    log.info("Type      " + bs.getContentType());

                } else if (p.isParam()) {
                    http_header.setContent(p.getName(), ((ParamPart) p).getStringValue());
                }

                // log.info("Parameter "+p.getName());
            }
        }

        try {
            final String url = http_header.getPath();

            try {
                /* Find out about the session id */
                sess = req.getSession(false) == null ? null
                        : (HTTPSession) req.getSession(false).getAttribute("webmail.session");

                /*
                 * If the user was logging on, he doesn't have a session id,
                 * so generate one. If he already had one, all the better,
                 * we will take the old one
                 */
                if (sess == null && url.startsWith("/login")) {
                    sess = newSession(req, http_header);
                } else if (sess == null && url.startsWith("/admin/login")) {
                    http_header.setHeader("LOGIN", "Administrator");
                    sess = newAdminSession(req, http_header);
                }
                if (sess == null && !url.equals("/") && !url.startsWith("/passthrough")
                        && !url.startsWith("/admin")) {
                    content = getURLHandler().handleURL("/logout", sess, http_header);
                } else {
                    /* Ensure that the session state is up-to-date */
                    if (sess != null) {
                        sess.setEnv();
                    }

                    /* Let the URLHandler determine the result of the query */
                    content = getURLHandler().handleURL(url, sess, http_header);
                }
            } catch (final InvalidPasswordException e) {
                log.error("Connection to " + addr.toString() + ": Authentication failed!");
                if (url.startsWith("/admin/login")) {
                    content = getURLHandler().handleURL("/admin", null, http_header);
                } else if (url.startsWith("/login")) {
                    content = getURLHandler().handleURL("/", null, http_header);
                } else
                    // content=new
                    // HTMLErrorMessage(getStorage(),e.getMessage());
                    throw new ServletException("Invalid URL called!");
            } catch (final Exception ex) {
                content = getURLHandler().handleException(ex, sess, http_header);
                log.debug("Some strange error while handling request", ex);
            }

            /*
             * Set some HTTP headers: Date is now, the document should
             * expire in 5 minutes, proxies and clients shouldn't cache it
             * and all WebMail documents must be revalidated when they think
             * they don't have to follow the "no-cache".
             */
            res.setDateHeader("Date:", System.currentTimeMillis());
            res.setDateHeader("Expires", System.currentTimeMillis() + 300000);
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Cache-Control", "must-revalidate");

            synchronized (out) {
                res.setStatus(content.getReturnCode());

                if (content.hasHTTPHeader()) {
                    final Enumeration enumVar = content.getHTTPHeaderKeys();
                    while (enumVar.hasMoreElements()) {
                        final String s = (String) enumVar.nextElement();
                        res.setHeader(s, content.getHTTPHeader(s));
                    }
                }

                /*
                 * What we will send is an image or some other sort of
                 * binary
                 */
                if (content instanceof HTMLImage) {
                    final HTMLImage img = (HTMLImage) content;
                    /*
                     * the HTMLImage class provides us with most of the
                     * necessary information that we want to send
                     */
                    res.setHeader("Content-Type", img.getContentType());
                    res.setHeader("Content-Transfer-Encoding", img.getContentEncoding());
                    res.setHeader("Content-Length", "" + img.size());
                    res.setHeader("Connection", "Keep-Alive");

                    /* Send 8k junks */
                    int offset = 0;
                    while (offset + chunk_size < img.size()) {
                        out.write(img.toBinary(), offset, chunk_size);
                        offset += chunk_size;
                    }
                    out.write(img.toBinary(), offset, img.size() - offset);
                    out.flush();

                    out.close();
                } else {
                    final byte[] encoded_content = content.toString().getBytes("UTF-8");

                    /*
                     * We are sending HTML text. Set the encoding to UTF-8
                     * for Unicode messages
                     */
                    res.setHeader("Content-Length", "" + (encoded_content.length + 2));
                    res.setHeader("Connection", "Keep-Alive");
                    res.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

                    out.write(encoded_content);
                    out.write("\r\n".getBytes());

                    out.flush();

                    out.close();
                }
            }
        } catch (final DocumentNotFoundException e) {
            log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code
                    + ") (Reason: " + e.getMessage() + ")");
            throw new ServletException("Error: " + e.getMessage(), e);
            // res.setStatus(err_code);
            // res.setHeader("Content-type","text/html");
            // res.setHeader("Connection","close");

            // content=new HTMLErrorMessage(getStorage(),e.getMessage());
            // out.write((content+"\r\n").getBytes("UTF-8"));
            // out.write("</HTML>\r\n".getBytes());
            // out.flush();
            // out.close();
        }
    } catch (final Exception e) {
        log.info("Connection to " + addr.toString() + " closed unexpectedly", e);
        throw new ServletException(e.getMessage());
    }
}

From source file:org.alfresco.filesys.config.ServerConfigurationBean.java

/**
 * Process the FTP server configuration/*from   w  ww  .  j a  v a 2  s  .  c  o  m*/
 */
protected void processFTPServerConfig() {
    // If the configuration section is not valid then FTP is disabled

    if (ftpConfigBean == null) {
        removeConfigSection(FTPConfigSection.SectionName);
        return;
    }

    // Check if the server has been disabled

    if (!ftpConfigBean.getServerEnabled()) {
        removeConfigSection(FTPConfigSection.SectionName);
        return;
    }

    // Create the FTP configuration section

    FTPConfigSection ftpConfig = new FTPConfigSection(this);

    try {
        // Check for a bind address

        String bindText = ftpConfigBean.getBindTo();
        if (bindText != null && bindText.length() > 0 && !bindText.equals(BIND_TO_IGNORE)) {

            // Validate the bind address

            try {

                // Check the bind address

                InetAddress bindAddr = InetAddress.getByName(bindText);

                // Set the bind address for the FTP server

                ftpConfig.setFTPBindAddress(bindAddr);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("Unable to find FTP bindto address, " + bindText, ex);
            }
        }

        // Check for an FTP server port

        Integer port = ftpConfigBean.getPort();
        if (port != null) {
            ftpConfig.setFTPPort(port);
            if (ftpConfig.getFTPPort() <= 0 || ftpConfig.getFTPPort() >= 65535)
                throw new AlfrescoRuntimeException("FTP server port out of valid range");
        } else {

            // Use the default FTP port

            ftpConfig.setFTPPort(DefaultFTPServerPort);
        }

        // Check for an FTP server timeout for connection to client
        Integer sessionTimeout = ftpConfigBean.getSessionTimeout();
        if (sessionTimeout != null) {
            ftpConfig.setFTPSrvSessionTimeout(sessionTimeout);
            if (ftpConfig.getFTPSrvSessionTimeout() < 0)
                throw new AlfrescoRuntimeException(
                        "FTP server session timeout must have positive value or zero");
        } else {

            // Use the default timeout

            ftpConfig.setFTPSrvSessionTimeout(DefaultFTPSrvSessionTimeout);
        }

        // Check if anonymous login is allowed

        if (ftpConfigBean.getAllowAnonymous()) {

            // Enable anonymous login to the FTP server

            ftpConfig.setAllowAnonymousFTP(true);

            // Check if an anonymous account has been specified

            String anonAcc = ftpConfigBean.getAnonymousAccount();
            if (anonAcc != null && anonAcc.length() > 0) {

                // Set the anonymous account name

                ftpConfig.setAnonymousFTPAccount(anonAcc);

                // Check if the anonymous account name is valid

                if (ftpConfig.getAnonymousFTPAccount() == null
                        || ftpConfig.getAnonymousFTPAccount().length() == 0) {
                    throw new AlfrescoRuntimeException("Anonymous FTP account invalid");
                }
            } else {

                // Use the default anonymous account name

                ftpConfig.setAnonymousFTPAccount(DefaultFTPAnonymousAccount);
            }
        } else {

            // Disable anonymous logins

            ftpConfig.setAllowAnonymousFTP(false);
        }

        // Check if a root path has been specified

        String rootPath = ftpConfigBean.getRootDirectory();
        if (rootPath != null && rootPath.length() > 0) {
            try {

                // Parse the path

                new FTPPath(rootPath);

                // Set the root path

                ftpConfig.setFTPRootPath(rootPath);
            } catch (InvalidPathException ex) {
                throw new AlfrescoRuntimeException("Invalid FTP root directory, " + rootPath);
            }
        }

        // Check for FTP debug flags

        String flags = ftpConfigBean.getDebugFlags();
        int ftpDbg = 0;

        if (flags != null) {

            // Parse the flags

            flags = flags.toUpperCase();
            StringTokenizer token = new StringTokenizer(flags, ",");

            while (token.hasMoreTokens()) {

                // Get the current debug flag token

                String dbg = token.nextToken().trim();

                // Find the debug flag name

                int idx = 0;

                while (idx < m_ftpDebugStr.length && m_ftpDebugStr[idx].equalsIgnoreCase(dbg) == false)
                    idx++;

                if (idx >= m_ftpDebugStr.length)
                    throw new AlfrescoRuntimeException("Invalid FTP debug flag, " + dbg);

                // Set the debug flag

                ftpDbg += 1 << idx;
            }

            // Set the FTP debug flags

            ftpConfig.setFTPDebug(ftpDbg);
        }

        // Check if a character set has been specified

        String charSet = ftpConfigBean.getCharSet();
        if (charSet != null && charSet.length() > 0) {

            try {

                // Validate the character set name

                Charset.forName(charSet);

                // Set the FTP character set

                ftpConfig.setFTPCharacterSet(charSet);
            } catch (IllegalCharsetNameException ex) {
                throw new AlfrescoRuntimeException("FTP Illegal character set name, " + charSet);
            } catch (UnsupportedCharsetException ex) {
                throw new AlfrescoRuntimeException("FTP Unsupported character set name, " + charSet);
            }
        }

        // Check if an authenticator has been specified

        FTPAuthenticator auth = ftpConfigBean.getAuthenticator();
        if (auth != null) {

            // Initialize and set the authenticator class

            ftpConfig.setAuthenticator(auth);
        } else
            throw new AlfrescoRuntimeException("FTP authenticator not specified");

        // Check if a data port range has been specified

        if (ftpConfigBean.getDataPortFrom() != 0 && ftpConfigBean.getDataPortTo() != 0) {

            // Range check the data port values

            int rangeFrom = ftpConfigBean.getDataPortFrom();
            int rangeTo = ftpConfigBean.getDataPortTo();

            if (rangeFrom != 0 && rangeTo != 0) {

                // Validate the FTP data port range

                if (rangeFrom < 1024 || rangeFrom > 65535)
                    throw new InvalidConfigurationException(
                            "Invalid FTP data port range from value, " + rangeFrom);

                if (rangeTo < 1024 || rangeTo > 65535)
                    throw new InvalidConfigurationException("Invalid FTP data port range to value, " + rangeTo);

                if (rangeFrom >= rangeTo)
                    throw new InvalidConfigurationException(
                            "Invalid FTP data port range, " + rangeFrom + "-" + rangeTo);

                // Set the FTP data port range

                ftpConfig.setFTPDataPortLow(rangeFrom);
                ftpConfig.setFTPDataPortHigh(rangeTo);

                // Log the data port range

                logger.info("FTP server data ports restricted to range " + rangeFrom + ":" + rangeTo);
            }
        }

        // FTPS parameter parsing
        //
        // Check if a key store path has been specified

        if (ftpConfigBean.getKeyStorePath() != null && ftpConfigBean.getKeyStorePath().length() > 0) {

            // Get the path to the key store, check that the file exists

            String keyStorePath = ftpConfigBean.getKeyStorePath();
            File keyStoreFile = new File(keyStorePath);

            if (keyStoreFile.exists() == false)
                throw new InvalidConfigurationException("FTPS key store file does not exist, " + keyStorePath);
            else if (keyStoreFile.isDirectory())
                throw new InvalidConfigurationException("FTPS key store path is a directory, " + keyStorePath);

            // Set the key store path

            ftpConfig.setKeyStorePath(keyStorePath);

            // Check if the key store type has been specified

            if (ftpConfigBean.getKeyStoreType() != null && ftpConfigBean.getKeyStoreType().length() > 0) {

                // Get the key store type, and validate

                String keyStoreType = ftpConfigBean.getKeyStoreType();

                if (keyStoreType == null || keyStoreType.length() == 0)
                    throw new InvalidConfigurationException("FTPS key store type is invalid");

                try {
                    KeyStore.getInstance(keyStoreType);
                } catch (KeyStoreException ex) {
                    throw new InvalidConfigurationException("FTPS key store type is invalid, " + keyStoreType,
                            ex);
                }

                // Set the key store type

                ftpConfig.setKeyStoreType(keyStoreType);
            }

            // Check if the key store passphrase has been specified

            if (ftpConfigBean.getKeyStorePassphrase() != null
                    && ftpConfigBean.getKeyStorePassphrase().length() > 0) {

                // Set the key store passphrase

                ftpConfig.setKeyStorePassphrase(ftpConfigBean.getKeyStorePassphrase());
            }
        }

        // Check if the trust store path has been specified

        if (ftpConfigBean.getTrustStorePath() != null && ftpConfigBean.getTrustStorePath().length() > 0) {

            // Get the path to the trust store, check that the file exists

            String trustStorePath = ftpConfigBean.getTrustStorePath();
            File trustStoreFile = new File(trustStorePath);

            if (trustStoreFile.exists() == false)
                throw new InvalidConfigurationException(
                        "FTPS trust store file does not exist, " + trustStorePath);
            else if (trustStoreFile.isDirectory())
                throw new InvalidConfigurationException(
                        "FTPS trust store path is a directory, " + trustStorePath);

            // Set the trust store path

            ftpConfig.setTrustStorePath(trustStorePath);

            // Check if the trust store type has been specified

            if (ftpConfigBean.getTrustStoreType() != null && ftpConfigBean.getTrustStoreType().length() > 0) {

                // Get the trust store type, and validate

                String trustStoreType = ftpConfigBean.getTrustStoreType();

                if (trustStoreType == null || trustStoreType.length() == 0)
                    throw new InvalidConfigurationException("FTPS trust store type is invalid");

                try {
                    KeyStore.getInstance(trustStoreType);
                } catch (KeyStoreException ex) {
                    throw new InvalidConfigurationException(
                            "FTPS trust store type is invalid, " + trustStoreType, ex);
                }

                // Set the trust store type

                ftpConfig.setTrustStoreType(trustStoreType);
            }

            // Check if the trust store passphrase has been specified

            if (ftpConfigBean.getTrustStorePassphrase() != null
                    && ftpConfigBean.getTrustStorePassphrase().length() > 0) {

                // Set the trust store passphrase

                ftpConfig.setTrustStorePassphrase(ftpConfigBean.getTrustStorePassphrase());
            }
        }

        // Check if only secure sessions should be allowed to logon

        if (ftpConfigBean.hasRequireSecureSession()) {

            // Only allow secure sessions to logon to the FTP server

            ftpConfig.setRequireSecureSession(true);
        }

        // Check that all the required FTPS parameters have been set
        // MNT-7301 FTPS server requires unnecessarly to have a trustStore while a keyStore should be sufficient
        if (ftpConfig.getKeyStorePath() != null) {

            // Make sure all parameters are set

            if (ftpConfig.getKeyStorePath() == null)
                throw new InvalidConfigurationException("FTPS configuration requires keyStore to be set");
        }

        // Check if SSLEngine debug output should be enabled

        if (ftpConfigBean.hasSslEngineDebug()) {

            // Enable SSLEngine debug output

            System.setProperty("javax.net.debug", "ssl,handshake");
        }
    } catch (InvalidConfigurationException ex) {
        throw new AlfrescoRuntimeException(ex.getMessage());
    }
}

From source file:org.alfresco.filesys.config.ServerConfigurationBean.java

/**
 * Process the CIFS server configuration
 *///from  w w w.  j  a v  a 2s . com
protected void processCIFSServerConfig() {
    // If the configuration section is not valid then CIFS is disabled

    if (cifsConfigBean == null) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Check if the server has been disabled
    if (!cifsConfigBean.getServerEnabled()) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Before we go any further, let's make sure there's a compatible authenticator in the authentication chain.
    ICifsAuthenticator authenticator = cifsConfigBean.getAuthenticator();
    if (authenticator == null
            || authenticator instanceof ActivateableBean && !((ActivateableBean) authenticator).isActive()) {
        logger.error("No enabled CIFS authenticator found in authentication chain. CIFS Server disabled");
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Create the CIFS server configuration section

    CIFSConfigSection cifsConfig = new CIFSConfigSection(this);

    try {
        // Check if native code calls should be disabled on Windows
        if (cifsConfigBean.getDisableNativeCode()) {
            // Disable native code calls so that the JNI DLL is not required

            cifsConfig.setNativeCodeDisabled(true);
            m_disableNativeCode = true;

            // Warning

            logger.warn("CIFS server native calls disabled, JNI code will not be used");
        }

        // Get the network broadcast address
        //
        // Note: We need to set this first as the call to getLocalDomainName() may use a NetBIOS
        // name lookup, so the broadcast mask must be set before then.

        String broadcastAddess = cifsConfigBean.getBroadcastAddress();
        if (broadcastAddess != null && broadcastAddess.length() > 0) {

            // Check if the broadcast mask is a valid numeric IP address

            if (IPAddress.isNumericAddress(broadcastAddess) == false) {
                throw new AlfrescoRuntimeException("CIFS Invalid broadcast mask, must be n.n.n.n format");
            }

            // Set the network broadcast mask

            cifsConfig.setBroadcastMask(broadcastAddess);
        }

        // Get the terminal server address

        List<String> terminalServerList = cifsConfigBean.getTerminalServerList();
        if (terminalServerList != null && terminalServerList.size() > 0) {
            // Check if the terminal server address is a valid numeric IP address
            for (String terminalServerAddress : terminalServerList) {
                if (IPAddress.isNumericAddress(terminalServerAddress) == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid terminal server address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setTerminalServerList(terminalServerList);
        }

        // Get the load balancer address

        List<String> loadBalancerList = cifsConfigBean.getLoadBalancerList();
        if (loadBalancerList != null && loadBalancerList.size() > 0) {
            // Check if the load balancer address is a valid numeric IP address
            for (String loadBalancerAddress : loadBalancerList) {
                if (IPAddress.isNumericAddress(loadBalancerAddress) == false)
                    throw new AlfrescoRuntimeException("Invalid load balancer address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setLoadBalancerList(loadBalancerList);
        }

        // Get the host configuration

        String hostName = cifsConfigBean.getServerName();
        if (hostName == null || hostName.length() == 0) {
            throw new AlfrescoRuntimeException("CIFS Host name not specified or invalid");
        }

        // Get the local server name

        String srvName = getLocalServerName(true);

        // Check if the host name contains the local name token

        int pos = hostName.indexOf(TokenLocalName);
        if (pos != -1) {
            // Rebuild the host name substituting the token with the local server name

            StringBuilder hostStr = new StringBuilder();

            hostStr.append(hostName.substring(0, pos));
            hostStr.append(srvName);

            pos += TokenLocalName.length();
            if (pos < hostName.length()) {
                hostStr.append(hostName.substring(pos));
            }

            hostName = hostStr.toString();
        }

        // Make sure the CIFS server name does not match the local server name

        if (hostName.toUpperCase().equals(srvName.toUpperCase())
                && getPlatformType() == Platform.Type.WINDOWS) {
            throw new AlfrescoRuntimeException("CIFS server name must be unique");
        }

        // Check if the host name is longer than 15 characters. NetBIOS only allows a maximum of 16 characters in
        // the
        // server name with the last character reserved for the service type.

        if (hostName.length() > 15) {
            // Truncate the CIFS server name

            hostName = hostName.substring(0, 15);

            // Output a warning

            logger.warn("CIFS server name is longer than 15 characters, truncated to " + hostName);
        }

        // Set the CIFS server name

        cifsConfig.setServerName(hostName.toUpperCase());
        setServerName(hostName.toUpperCase());

        // Get the domain/workgroup name

        String domain = cifsConfigBean.getDomainName();
        if (domain != null && domain.length() > 0) {
            // Set the domain/workgroup name

            cifsConfig.setDomainName(domain.toUpperCase());
        } else {
            // Get the local domain/workgroup name

            String localDomain = getLocalDomainName();

            if (localDomain == null && (getPlatformType() != Platform.Type.WINDOWS || isNativeCodeDisabled())) {
                // Use a default domain/workgroup name

                localDomain = "WORKGROUP";

                // Output a warning
                logger.warn("CIFS, Unable to get local domain/workgroup name, using default of " + localDomain
                        + ". This may be due to firewall settings or incorrect <broadcast> setting)");
            }

            // Set the local domain/workgroup that the CIFS server belongs to

            cifsConfig.setDomainName(localDomain);
        }

        // Check for a server comment

        String comment = cifsConfigBean.getServerComment();
        if (comment != null && comment.length() > 0) {
            cifsConfig.setComment(comment);
        }

        // Set the maximum virtual circuits per session

        if (cifsConfigBean.getMaximumVirtualCircuits() < VirtualCircuitList.MinCircuits
                || cifsConfigBean.getMaximumVirtualCircuits() > VirtualCircuitList.MaxCircuits)
            throw new AlfrescoRuntimeException("Invalid virtual circuits value, valid range is "
                    + VirtualCircuitList.MinCircuits + " - " + VirtualCircuitList.MaxCircuits);
        else
            cifsConfig.setMaximumVirtualCircuits(cifsConfigBean.getMaximumVirtualCircuits());

        // Check for a bind address

        // Check if the network adapter name has been specified
        String bindToAdapter = cifsConfigBean.getBindToAdapter();
        String bindTo;

        if (bindToAdapter != null && bindToAdapter.length() > 0) {

            // Get the IP address for the adapter

            InetAddress bindAddr = parseAdapterName(bindToAdapter);

            // Set the bind address for the server

            cifsConfig.setSMBBindAddress(bindAddr);
        } else if ((bindTo = cifsConfigBean.getBindToAddress()) != null && bindTo.length() > 0
                && !bindTo.equals(BIND_TO_IGNORE)) {

            // Validate the bind address
            try {
                // Check the bind address

                InetAddress bindAddr = InetAddress.getByName(bindTo);

                // Set the bind address for the server

                cifsConfig.setSMBBindAddress(bindAddr);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("CIFS Unable to bind to address :" + bindTo, ex);
            }
        }

        // Get the authenticator

        if (authenticator != null) {
            cifsConfig.setAuthenticator(authenticator);
        } else {
            throw new AlfrescoRuntimeException("CIFS authenticator not specified");
        }

        // Check if the host announcer has been disabled

        if (!cifsConfigBean.getHostAccouncerEnabled()) {
            // Switch off the host announcer

            cifsConfig.setHostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("CIFS Host announcements not enabled");
        } else {
            // Check for an announcement interval

            Integer interval = cifsConfigBean.getHostAccounceInterval();
            if (interval != null) {
                cifsConfig.setHostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null) {
                throw new AlfrescoRuntimeException(
                        "CIFS Domain name must be specified if host announcement is enabled");
            }

            // Enable host announcement

            cifsConfig.setHostAnnouncer(true);
        }

        // Check if NetBIOS SMB is enabled
        NetBIOSSMBConfigBean netBIOSSMBConfigBean = cifsConfigBean.getNetBIOSSMB();
        if (netBIOSSMBConfigBean != null) {
            // Check if NetBIOS over TCP/IP is enabled for the current platform

            String platformsStr = netBIOSSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null && platformsStr.length() > 0) {
                // Parse the list of platforms that NetBIOS over TCP/IP is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the NetBIOS SMB support, if enabled for this platform

            cifsConfig.setNetBIOSSMB(platformOK);

            // Parse/check NetBIOS settings, if enabled

            if (cifsConfig.hasNetBIOSSMB()) {
                // Check if the broadcast mask has been specified

                if (cifsConfig.getBroadcastMask() == null) {
                    throw new AlfrescoRuntimeException("CIFS Network broadcast mask not specified");
                }

                // Check for a bind address

                String bindto = netBIOSSMBConfigBean.getBindTo();
                if (bindto != null && bindto.length() > 0 && !bindto.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(bindto);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new AlfrescoRuntimeException("CIFS Invalid NetBIOS bind address:" + bindto, ex);
                    }
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                } else {
                    // Get a list of all the local addresses

                    InetAddress[] addrs = null;

                    try {
                        // Get the local server IP address list

                        addrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
                    } catch (UnknownHostException ex) {
                        logger.error("CIFS Failed to get local address list", ex);
                    }

                    // Check the address list for one or more valid local addresses filtering out the loopback
                    // address

                    int addrCnt = 0;

                    if (addrs != null) {
                        for (int i = 0; i < addrs.length; i++) {

                            // Check for a valid address, filter out '127.0.0.1' and '0.0.0.0' addresses

                            if (addrs[i].getHostAddress().equals("127.0.0.1") == false
                                    && addrs[i].getHostAddress().equals("0.0.0.0") == false)
                                addrCnt++;
                        }
                    }

                    // Check if any addresses were found

                    if (addrCnt == 0) {
                        // Enumerate the network adapter list

                        Enumeration<NetworkInterface> niEnum = null;

                        try {
                            niEnum = NetworkInterface.getNetworkInterfaces();
                        } catch (SocketException ex) {
                        }

                        if (niEnum != null) {
                            while (niEnum.hasMoreElements()) {
                                // Get the current network interface

                                NetworkInterface ni = niEnum.nextElement();

                                // Enumerate the addresses for the network adapter

                                Enumeration<InetAddress> niAddrs = ni.getInetAddresses();
                                if (niAddrs != null) {
                                    // Check for any valid addresses

                                    while (niAddrs.hasMoreElements()) {
                                        InetAddress curAddr = niAddrs.nextElement();

                                        if (curAddr.getHostAddress().equals("127.0.0.1") == false
                                                && curAddr.getHostAddress().equals("0.0.0.0") == false)
                                            addrCnt++;
                                    }
                                }
                            }

                            // DEBUG

                            if (addrCnt > 0 && logger.isDebugEnabled())
                                logger.debug("Found valid IP address from interface list");
                        }

                        // Check if we found any valid network addresses

                        if (addrCnt == 0) {
                            // Log the available IP addresses

                            if (logger.isDebugEnabled()) {
                                logger.debug("Local address list dump :-");
                                if (addrs != null) {
                                    for (int i = 0; i < addrs.length; i++)
                                        logger.debug("  Address: " + addrs[i]);
                                } else {
                                    logger.debug("  No addresses");
                                }
                            }

                            // Throw an exception to stop the CIFS/NetBIOS name server from starting

                            throw new AlfrescoRuntimeException(
                                    "Failed to get IP address(es) for the local server, check hosts file and/or DNS setup");
                        }
                    }
                }

                // Check if the session port has been specified

                Integer portNum = netBIOSSMBConfigBean.getSessionPort();
                if (portNum != null) {
                    cifsConfig.setSessionPort(portNum);
                    if (cifsConfig.getSessionPort() <= 0 || cifsConfig.getSessionPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS session port out of valid range");
                }

                // Check if the name port has been specified

                portNum = netBIOSSMBConfigBean.getNamePort();
                if (portNum != null) {
                    cifsConfig.setNameServerPort(portNum);
                    if (cifsConfig.getNameServerPort() <= 0 || cifsConfig.getNameServerPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS name port out of valid range");
                }

                // Check if the datagram port has been specified

                portNum = netBIOSSMBConfigBean.getDatagramPort();
                if (portNum != null) {
                    cifsConfig.setDatagramPort(portNum);
                    if (cifsConfig.getDatagramPort() <= 0 || cifsConfig.getDatagramPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS datagram port out of valid range");
                }

                // Check for a bind address

                String attr = netBIOSSMBConfigBean.getBindTo();
                if (attr != null && attr.length() > 0 && !attr.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(attr);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new InvalidConfigurationException(ex.toString());
                    }
                }

                // Check for a bind address using the adapter name

                else if ((attr = netBIOSSMBConfigBean.getAdapter()) != null && attr.length() > 0) {

                    // Get the bind address via the network adapter name

                    InetAddress bindAddr = parseAdapterName(attr);
                    cifsConfig.setNetBIOSBindAddress(bindAddr);
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                }

            }
        } else {

            // Disable NetBIOS SMB support

            cifsConfig.setNetBIOSSMB(false);
        }

        // Check if TCP/IP SMB is enabled

        TcpipSMBConfigBean tcpipSMBConfigBean = cifsConfigBean.getTcpipSMB();
        if (tcpipSMBConfigBean != null) {

            // Check if native SMB is enabled for the current platform

            String platformsStr = tcpipSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null) {
                // Parse the list of platforms that native SMB is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the TCP/IP SMB support, if enabled for this platform

            cifsConfig.setTcpipSMB(platformOK);

            // Check if the port has been specified

            Integer portNum = tcpipSMBConfigBean.getPort();
            if (portNum != null) {
                cifsConfig.setTcpipSMBPort(portNum);
                if (cifsConfig.getTcpipSMBPort() <= 0 || cifsConfig.getTcpipSMBPort() >= 65535)
                    throw new AlfrescoRuntimeException("TCP/IP SMB port out of valid range");
            }

            // Check if IPv6 support should be enabled

            if (tcpipSMBConfigBean.getIpv6Enabled()) {
                try {
                    // Use the IPv6 bind all address

                    cifsConfig.setSMBBindAddress(InetAddress.getByName("::"));

                    // DEBUG

                    if (logger.isInfoEnabled()) {
                        logger.info("Enabled CIFS IPv6 bind address for native SMB");

                    }
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException(
                            "CIFS Failed to enable IPv6 bind address, " + ex.getMessage());
                }
            }

        } else {

            // Disable TCP/IP SMB support

            cifsConfig.setTcpipSMB(false);
        }

        // Check if Win32 NetBIOS is enabled

        Win32NetBIOSConfigBean win32NetBIOSConfigBean = cifsConfigBean.getWin32NetBIOS();
        if (win32NetBIOSConfigBean != null) {

            // Check if the Win32 NetBIOS server name has been specified

            String win32Name = win32NetBIOSConfigBean.getName();
            if (win32Name != null && win32Name.length() > 0) {

                // Validate the name

                if (win32Name.length() > 16)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS name, " + win32Name);

                // Set the Win32 NetBIOS file server name

                cifsConfig.setWin32NetBIOSName(win32Name);
            }

            // Check if the Win32 NetBIOS LANA has been specified

            String lanaStr = win32NetBIOSConfigBean.getLana();
            if (lanaStr != null && lanaStr.length() > 0) {
                // Check if the LANA has been specified as an IP address or adapter name

                int lana = -1;

                if (IPAddress.isNumericAddress(lanaStr)) {

                    // Convert the IP address to a LANA id

                    lana = Win32NetBIOS.getLANAForIPAddress(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert IP address " + lanaStr + " to a LANA");
                } else if (lanaStr.length() > 1 && Character.isLetter(lanaStr.charAt(0))) {

                    // Convert the network adapter to a LANA id

                    lana = Win32NetBIOS.getLANAForAdapterName(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert network adapter " + lanaStr + " to a LANA");
                } else {

                    try {
                        lana = Integer.parseInt(lanaStr);
                    } catch (NumberFormatException ex) {
                        throw new AlfrescoRuntimeException("Invalid win32 NetBIOS LANA specified");
                    }
                }

                // LANA should be in the range 0-255

                if (lana < 0 || lana > 255)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS LANA number, " + lana);

                // Set the LANA number

                cifsConfig.setWin32LANA(lana);
            }

            // Check if the native NetBIOS interface has been specified, either 'winsock' or 'netbios'

            String nativeAPI = win32NetBIOSConfigBean.getApi();
            if (nativeAPI != null && nativeAPI.length() > 0) {
                // Validate the API type

                boolean useWinsock = true;

                if (nativeAPI.equalsIgnoreCase("netbios"))
                    useWinsock = false;
                else if (nativeAPI.equalsIgnoreCase("winsock") == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid NetBIOS API type, spefify 'winsock' or 'netbios'");

                // Set the NetBIOS API to use

                cifsConfig.setWin32WinsockNetBIOS(useWinsock);
            }

            // Force the older NetBIOS API code to be used on 64Bit Windows

            if (cifsConfig.useWinsockNetBIOS() == true && X64.isWindows64()) {
                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Using older Netbios() API code");

                // Use the older NetBIOS API code

                cifsConfig.setWin32WinsockNetBIOS(false);
            }

            // Check if the current operating system is supported by the Win32
            // NetBIOS handler

            String osName = System.getProperty("os.name");
            if (osName.startsWith("Windows") && (osName.endsWith("95") == false
                    && osName.endsWith("98") == false && osName.endsWith("ME") == false)
                    && isNativeCodeDisabled() == false) {

                // Call the Win32NetBIOS native code to make sure it is initialized

                if (Win32NetBIOS.LanaEnumerate() != null) {
                    // Enable Win32 NetBIOS

                    cifsConfig.setWin32NetBIOS(true);
                } else {
                    logger.warn("No NetBIOS LANAs available");
                }
            } else {

                // Win32 NetBIOS not supported on the current operating system

                cifsConfig.setWin32NetBIOS(false);
            }
        } else {

            // Disable Win32 NetBIOS

            cifsConfig.setWin32NetBIOS(false);
        }

        // Check if the Win32 host announcer has been disabled

        if (!cifsConfigBean.getWin32HostAnnouncerEnabled()) {
            // Switch off the Win32 host announcer

            cifsConfig.setWin32HostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("Win32 host announcements not enabled");
        } else {
            // Check for an announcement interval
            Integer interval = cifsConfigBean.getWin32HostAnnounceInterval();
            if (interval != null) {
                cifsConfig.setWin32HostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null)
                throw new AlfrescoRuntimeException(
                        "Domain name must be specified if host announcement is enabled");

            // Enable Win32 NetBIOS host announcement

            cifsConfig.setWin32HostAnnouncer(true);
        }

        // Check if NetBIOS and/or TCP/IP SMB have been enabled

        if (cifsConfig.hasNetBIOSSMB() == false && cifsConfig.hasTcpipSMB() == false
                && cifsConfig.hasWin32NetBIOS() == false)
            throw new AlfrescoRuntimeException("NetBIOS SMB, TCP/IP SMB or Win32 NetBIOS must be enabled");

        // Check if WINS servers are configured

        WINSConfigBean winsConfigBean = cifsConfigBean.getWINSConfig();

        if (winsConfigBean != null && !winsConfigBean.isAutoDetectEnabled()) {

            // Get the primary WINS server

            String priWins = winsConfigBean.getPrimary();

            if (priWins == null || priWins.length() == 0)
                throw new AlfrescoRuntimeException("No primary WINS server configured");

            // Validate the WINS server address

            InetAddress primaryWINS = null;

            try {
                primaryWINS = InetAddress.getByName(priWins);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("Invalid primary WINS server address, " + priWins);
            }

            // Check if a secondary WINS server has been specified

            String secWins = winsConfigBean.getSecondary();
            InetAddress secondaryWINS = null;

            if (secWins != null && secWins.length() > 0) {

                // Validate the secondary WINS server address

                try {
                    secondaryWINS = InetAddress.getByName(secWins);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid secondary WINS server address, " + secWins);
                }
            }

            // Set the WINS server address(es)

            cifsConfig.setPrimaryWINSServer(primaryWINS);
            if (secondaryWINS != null)
                cifsConfig.setSecondaryWINSServer(secondaryWINS);

            // Pass the setting to the NetBIOS session class

            NetBIOSSession.setDefaultWINSServer(primaryWINS);
        }

        // Check if WINS is configured, if we are running on Windows and socket based NetBIOS is enabled

        else if (cifsConfig.hasNetBIOSSMB() && getPlatformType() == Platform.Type.WINDOWS
                && !isNativeCodeDisabled()) {
            // Get the WINS server list

            String winsServers = Win32NetBIOS.getWINSServerList();

            if (winsServers != null) {
                // Use the first WINS server address for now

                StringTokenizer tokens = new StringTokenizer(winsServers, ",");
                String addr = tokens.nextToken();

                try {
                    // Convert to a network address and check if the WINS server is accessible

                    InetAddress winsAddr = InetAddress.getByName(addr);

                    Socket winsSocket = new Socket();
                    InetSocketAddress sockAddr = new InetSocketAddress(winsAddr, RFCNetBIOSProtocol.NAME_PORT);

                    winsSocket.connect(sockAddr, 3000);
                    winsSocket.close();

                    // Set the primary WINS server address

                    cifsConfig.setPrimaryWINSServer(winsAddr);

                    // Debug

                    if (logger.isDebugEnabled())
                        logger.debug("Configuring to use WINS server " + addr);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid auto WINS server address, " + addr);
                } catch (IOException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Failed to connect to auto WINS server " + addr);
                }
            }
        }

        // Check for session debug flags

        String flags = cifsConfigBean.getSessionDebugFlags();

        int sessDbg = 0;

        if (flags != null && flags.length() > 0) {

            // Parse the flags

            flags = flags.toUpperCase();
            StringTokenizer token = new StringTokenizer(flags, ",");

            while (token.hasMoreTokens()) {
                // Get the current debug flag token

                String dbg = token.nextToken().trim();

                // Find the debug flag name

                int idx = 0;

                while (idx < m_sessDbgStr.length && m_sessDbgStr[idx].equalsIgnoreCase(dbg) == false)
                    idx++;

                if (idx > m_sessDbgStr.length)
                    throw new AlfrescoRuntimeException("Invalid session debug flag, " + dbg);

                // Set the debug flag

                sessDbg += 1 << idx;
            }
        }

        // Set the session debug flags

        cifsConfig.setSessionDebugFlags(sessDbg);

        // Check if NIO based socket code should be disabled

        if (cifsConfigBean.getDisableNIO()) {

            // Disable NIO based code

            cifsConfig.setDisableNIOCode(true);

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("NIO based code disabled for CIFS server");
        }

        // Check if a session timeout is configured

        Integer tmo = cifsConfigBean.getSessionTimeout();
        if (tmo != null) {

            // Validate the session timeout value

            cifsConfigBean.validateSessionTimeout(tmo);

            // Convert the session timeout to milliseconds

            cifsConfig.setSocketTimeout(tmo * 1000);
        }
    } catch (InvalidConfigurationException ex) {
        throw new AlfrescoRuntimeException(ex.getMessage());
    }
}