Example usage for java.lang Character isLetter

List of usage examples for java.lang Character isLetter

Introduction

In this page you can find the example usage for java.lang Character isLetter.

Prototype

public static boolean isLetter(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a letter.

Usage

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument.java

/**
 * Indicates if the content is a well formed HTML snippet that can already be parsed to be added to the DOM.
 *
 * @param content the HTML snippet//from  w  w w .  j  a v  a2  s .  c  o  m
 * @return {@code false} if it not well formed
 */
static boolean canAlreadyBeParsed(final String content) {
    // all <script> must have their </script> because the parser doesn't close automatically this tag
    // All tags must be complete, that is from '<' to '>'.
    ParsingStatus tagState = ParsingStatus.OUTSIDE;
    int tagNameBeginIndex = 0;
    int scriptTagCount = 0;
    boolean tagIsOpen = true;
    char stringBoundary = 0;
    boolean stringSkipNextChar = false;
    int index = 0;
    char openingQuote = 0;
    for (final char currentChar : content.toCharArray()) {
        switch (tagState) {
        case OUTSIDE:
            if (currentChar == '<') {
                tagState = ParsingStatus.START;
                tagIsOpen = true;
            } else if (scriptTagCount > 0 && (currentChar == '\'' || currentChar == '"')) {
                tagState = ParsingStatus.IN_STRING;
                stringBoundary = currentChar;
                stringSkipNextChar = false;
            }
            break;
        case START:
            if (currentChar == '/') {
                tagIsOpen = false;
                tagNameBeginIndex = index + 1;
            } else {
                tagNameBeginIndex = index;
            }
            tagState = ParsingStatus.IN_NAME;
            break;
        case IN_NAME:
            if (Character.isWhitespace(currentChar) || currentChar == '>') {
                final String tagName = content.substring(tagNameBeginIndex, index);
                if ("script".equalsIgnoreCase(tagName)) {
                    if (tagIsOpen) {
                        scriptTagCount++;
                    } else if (scriptTagCount > 0) {
                        // Ignore extra close tags for now. Let the parser deal with them.
                        scriptTagCount--;
                    }
                }
                if (currentChar == '>') {
                    tagState = ParsingStatus.OUTSIDE;
                } else {
                    tagState = ParsingStatus.INSIDE;
                }
            } else if (!Character.isLetter(currentChar)) {
                tagState = ParsingStatus.OUTSIDE;
            }
            break;
        case INSIDE:
            if (currentChar == openingQuote) {
                openingQuote = 0;
            } else if (openingQuote == 0) {
                if (currentChar == '\'' || currentChar == '"') {
                    openingQuote = currentChar;
                } else if (currentChar == '>' && openingQuote == 0) {
                    tagState = ParsingStatus.OUTSIDE;
                }
            }
            break;
        case IN_STRING:
            if (stringSkipNextChar) {
                stringSkipNextChar = false;
            } else {
                if (currentChar == stringBoundary) {
                    tagState = ParsingStatus.OUTSIDE;
                } else if (currentChar == '\\') {
                    stringSkipNextChar = true;
                }
            }
            break;
        default:
            // nothing
        }
        index++;
    }
    if (scriptTagCount > 0 || tagState != ParsingStatus.OUTSIDE) {
        if (LOG.isDebugEnabled()) {
            final StringBuilder message = new StringBuilder();
            message.append("canAlreadyBeParsed() retruns false for content: '");
            message.append(StringUtils.abbreviateMiddle(content, ".", 100));
            message.append("' (scriptTagCount: " + scriptTagCount);
            message.append(" tagState: " + tagState);
            message.append(")");
            LOG.debug(message.toString());
        }
        return false;
    }

    return true;
}

From source file:PmpEditor.java

/**
 * Called by StyledText to get styles for a line
 *//* w  w w.j  a v  a 2  s. com*/
public void lineGetStyle(LineStyleEvent event) {
    // Only do styles if syntax data has been loaded
    if (syntaxData != null) {
        // Create collection to hold the StyleRanges
        List styles = new ArrayList();

        int start = 0;
        int length = event.lineText.length();

        // Check if line begins inside a multiline comment
        int mlIndex = getBeginsInsideComment(event.lineOffset, event.lineText.length());
        if (mlIndex > -1) {
            // Line begins inside multiline comment; create the range
            styles.add(new StyleRange(event.lineOffset, mlIndex - event.lineOffset, COMMENT_COLOR,
                    COMMENT_BACKGROUND));
            start = mlIndex;
        }
        // Do punctuation, single-line comments, and keywords
        while (start < length) {
            // Check for multiline comments that begin inside this line
            if (event.lineText.indexOf(syntaxData.getMultiLineCommentStart(), start) == start) {
                // Determine where comment ends
                int endComment = event.lineText.indexOf(syntaxData.getMultiLineCommentEnd(), start);

                // If comment doesn't end on this line, extend range to end of line
                if (endComment == -1)
                    endComment = length;
                else
                    endComment += syntaxData.getMultiLineCommentEnd().length();
                styles.add(new StyleRange(event.lineOffset + start, endComment - start, COMMENT_COLOR,
                        COMMENT_BACKGROUND));

                // Move marker
                start = endComment;
            }
            // Check for single line comments
            else if (event.lineText.indexOf(syntaxData.getComment(), start) == start) {
                // Comment rest of line
                styles.add(new StyleRange(event.lineOffset + start, length - start, COMMENT_COLOR,
                        COMMENT_BACKGROUND));

                // Move marker
                start = length;
            }
            // Check for punctuation
            else if (syntaxData.getPunctuation().indexOf(event.lineText.charAt(start)) > -1) {
                // Add range for punctuation
                styles.add(new StyleRange(event.lineOffset + start, 1, PUNCTUATION_COLOR, null));
                ++start;
            } else if (Character.isLetter(event.lineText.charAt(start))) {
                // Get the next word
                StringBuffer buf = new StringBuffer();
                int i = start;
                // Call any consecutive letters a word
                for (; i < length && Character.isLetter(event.lineText.charAt(i)); i++) {
                    buf.append(event.lineText.charAt(i));
                }
                // See if the word is a keyword
                if (syntaxData.getKeywords().contains(buf.toString())) {
                    // It's a keyword; create the StyleRange
                    styles.add(
                            new StyleRange(event.lineOffset + start, i - start, KEYWORD_COLOR, null, SWT.BOLD));
                }
                // Move the marker to the last char (the one that wasn't a letter)
                // so it can be retested in the next iteration through the loop
                start = i;
            } else
                // It's nothing we're interested in; advance the marker
                ++start;
        }

        // Copy the StyleRanges back into the event
        event.styles = (StyleRange[]) styles.toArray(new StyleRange[0]);
    }
}

From source file:com.prowidesoftware.swift.model.field.Field.java

/**
 * Return the letter option of this field as given by it classname or <code>null</code> if this field has no letter option
 *//*w  w w  .  ja  v a  2  s.c  om*/
public Character letterOption() {
    final String cn = getClass().getName();
    final char c = cn.charAt(cn.length() - 1);
    if (Character.isLetter(c)) {
        return c;
    }
    return null;
}

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

/**
 * Process the CIFS server configuration
 *///from  w ww  . j  ava2 s . co m
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());
    }
}

From source file:xc.mst.manager.processingDirective.DefaultServicesService.java

public Collection<String> getServicesAvailableForInstall() {
    List<String> availableServices = new ArrayList<String>();
    File dir = getServiceDir();// www.  java  2 s  . c  o  m
    File[] fileList = dir.listFiles();

    Set<String> allServices = new HashSet<String>();
    try {
        List<Service> services = getAllServices();
        for (Service s : services) {
            allServices.add(s.getName());
        }
    } catch (Throwable t) {
        LOG.error("", t);
    }

    for (File file : fileList) {
        if (file.isDirectory() && !allServices.contains(file.getName())) {
            boolean nameIsAcceptable = true;
            for (byte b : file.getName().getBytes()) {
                if (!(Character.isDigit((char) b) || Character.isLetter((char) b))) {
                    nameIsAcceptable = false;
                }
            }
            if (nameIsAcceptable) {
                String serviceName = file.getName();
                availableServices.add(serviceName);
            }
        }
    }

    return availableServices;
}

From source file:org.botlibre.util.Utils.java

/**
 * Check if the text is all upper case.//from   w  ww . j av  a2  s  .co m
 */
public static boolean isCaps(String text) {
    boolean hasCaps = false;
    for (int index = 0; index < text.length(); index++) {
        char character = text.charAt(index);
        if (Character.isLetter(character)) {
            if (!Character.isUpperCase(character)) {
                return false;
            }
            hasCaps = true;
        }
    }
    return hasCaps;
}

From source file:org.gvnix.service.roo.addon.addon.util.WsdlParserUtils.java

/**
 * Map an XML name to a Java identifier per the mapping rules of JSR 101 (in
 * version 1.0 this is "Chapter 20: Appendix: Mapping of XML Names"
 * /* w w  w  .  j ava  2 s .  c  om*/
 * @param name is the xml name
 * @return the java name per JSR 101 specification
 */
public static String xmlNameToJava(String name) {

    // protect ourselves from garbage
    if (name == null || name.equals(""))
        return name;

    char[] nameArray = name.toCharArray();
    int nameLen = name.length();
    StringBuffer result = new StringBuffer(nameLen);
    boolean wordStart = false;

    // The mapping indicates to convert first character.
    int i = 0;
    while (i < nameLen && (isPunctuation(nameArray[i]) || !Character.isJavaIdentifierStart(nameArray[i]))) {
        i++;
    }
    if (i < nameLen) {
        // Decapitalization code used to be here, but we use the
        // Introspector function now after we filter out all bad chars.

        result.append(nameArray[i]);
        // wordStart = !Character.isLetter(nameArray[i]);
        wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0);
    } else {
        // The identifier cannot be mapped strictly according to
        // JSR 101
        if (Character.isJavaIdentifierPart(nameArray[0])) {
            result.append("_" + nameArray[0]);
        } else {
            // The XML identifier does not contain any characters
            // we can map to Java. Using the length of the string
            // will make it somewhat unique.
            result.append("_" + nameArray.length);
        }
    }

    // The mapping indicates to skip over
    // all characters that are not letters or
    // digits. The first letter/digit
    // following a skipped character is
    // upper-cased.
    for (++i; i < nameLen; ++i) {
        char c = nameArray[i];

        // if this is a bad char, skip it and remember to capitalize next
        // good character we encounter
        if (isPunctuation(c) || !Character.isJavaIdentifierPart(c)) {
            wordStart = true;
            continue;
        }
        if (wordStart && Character.isLowerCase(c)) {
            result.append(Character.toUpperCase(c));
        } else {
            result.append(c);
        }
        // If c is not a character, but is a legal Java
        // identifier character, capitalize the next character.
        // For example: "22hi" becomes "22Hi"
        // wordStart = !Character.isLetter(c);
        wordStart = !Character.isLetter(c) && c != "_".charAt(0);
    }

    // covert back to a String
    String newName = result.toString();

    // Follow JavaBean rules, but we need to check if the first
    // letter is uppercase first
    if (Character.isUpperCase(newName.charAt(0)))
        newName = Introspector.decapitalize(newName);

    // check for Java keywords
    if (isJavaKeyword(newName))
        newName = makeNonJavaKeyword(newName);

    return newName;
}

From source file:org.apache.openjpa.lib.conf.ConfigurationImpl.java

/**
 * Convert <code>propName</code> to a lowercase-with-hyphens-style string.
 * This algorithm is only designed for mixes of uppercase and lowercase 
 * letters and lone digits. A more sophisticated conversion should probably 
 * be handled by a proper parser generator or regular expressions.
 *//*  w w w . ja  v a 2 s. c  o  m*/
public static String toXMLName(String propName) {
    if (propName == null)
        return null;
    StringBuilder buf = new StringBuilder();
    char c;
    for (int i = 0; i < propName.length(); i++) {
        c = propName.charAt(i);

        // convert sequences of all-caps to downcase with dashes around 
        // them. put a trailing cap that is followed by downcase into the
        // downcase word.
        if (i != 0 && Character.isUpperCase(c)
                && (Character.isLowerCase(propName.charAt(i - 1))
                        || (i > 1 && i < propName.length() - 1 && Character.isUpperCase(propName.charAt(i - 1))
                                && Character.isLowerCase(propName.charAt(i + 1)))))
            buf.append('-');

        // surround sequences of digits with dashes.
        if (i != 0 && ((!Character.isLetter(c) && Character.isLetter(propName.charAt(i - 1)))
                || (Character.isLetter(c) && !Character.isLetter(propName.charAt(i - 1)))))
            buf.append('-');

        buf.append(Character.toLowerCase(c));
    }
    return buf.toString();
}

From source file:CharUtils.java

/**
 * Get case value for a string.//from w ww.ja  v  a 2s .c  o m
 * 
 * @param s
 *            The string.
 * 
 * @return Case value. 0 = all letters are lower case 1 = first letter
 *         (only) is upper case 2 = first letter is not upper case, but some
 *         letters after first are upper case 3 = all letters are upper case
 */

public static int getLetterCase(String s) {
    int result = 0;

    int capLetCount = 0;
    int letCount = 0;

    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);

        if (Character.isLetter(ch)) {
            letCount++;

            if (Character.isUpperCase(ch)) {
                if (letCount == 1)
                    result = 1;
                capLetCount++;
            }
        }
    }

    if (letCount == capLetCount) {
        result = 3;
    } else if ((result == 0) && (capLetCount > 0)) {
        result = 2;
    }

    return result;
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Capitalises the first word in the supplied text (which may contain RTF
 * markup) the first letter of the word is preceded by a '|'.
 * //from  w  w w. j av a 2s. co m
 * @param text
 *            the text to capitalise.
 * @return the text with the first word capitalised.
 */
public static String capitaliseFirstWord(String text) {
    if (StringUtils.isEmpty(text)) {
        return text;
    }

    StringBuilder tmp = new StringBuilder();
    tmp.append(text);
    int index = 0;
    while (index >= 0 && index < text.length() && !Character.isLetterOrDigit(tmp.charAt(index))) {
        if (tmp.charAt(index) == '\\') {
            index = RTFUtils.skipKeyword(text, index);

            if (index < 0 || index >= tmp.length() || Character.isLetterOrDigit(tmp.charAt(index))) {
                break;
            }
        }
        index++;
    }

    if (index >= 0 && index < text.length() && Character.isLetter(tmp.charAt(index))) {
        if ((index == 0) || (tmp.charAt(index - 1) != '|')) {
            tmp.setCharAt(index, Character.toUpperCase(tmp.charAt(index)));
        } else if (tmp.charAt(index - 1) == '|') {
            tmp.deleteCharAt(index - 1);
        }
    }
    return tmp.toString();
}