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:edu.umich.robot.GuiApplication.java

public void createSuperdroidRobotDialog() {
    final Pose pose = new Pose();

    FormLayout layout = new FormLayout("right:pref, 4dlu, 30dlu, 4dlu, right:pref, 4dlu, 30dlu",
            "pref, 2dlu, pref, 2dlu, pref");

    layout.setRowGroups(new int[][] { { 1, 3 } });

    final JDialog dialog = new JDialog(frame, "Create Superdroid Robot", true);
    dialog.setLayout(layout);/*from   ww w. ja  v a  2  s .  co  m*/
    final JTextField name = new JTextField();
    final JTextField x = new JTextField(Double.toString((pose.getX())));
    final JTextField y = new JTextField(Double.toString((pose.getY())));
    final JButton cancel = new JButton("Cancel");
    final JButton ok = new JButton("OK");

    CellConstraints cc = new CellConstraints();
    dialog.add(new JLabel("Name"), cc.xy(1, 1));
    dialog.add(name, cc.xyw(3, 1, 5));
    dialog.add(new JLabel("x"), cc.xy(1, 3));
    dialog.add(x, cc.xy(3, 3));
    dialog.add(new JLabel("y"), cc.xy(5, 3));
    dialog.add(y, cc.xy(7, 3));
    dialog.add(cancel, cc.xyw(1, 5, 3));
    dialog.add(ok, cc.xyw(5, 5, 3));

    x.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            try {
                pose.setX(Double.parseDouble(x.getText()));
            } catch (NumberFormatException ex) {
                x.setText(Double.toString(pose.getX()));
            }
        }
    });

    y.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            try {
                pose.setY(Double.parseDouble(y.getText()));
            } catch (NumberFormatException ex) {
                y.setText(Double.toString(pose.getX()));
            }
        }
    });

    final ActionListener okListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String robotName = name.getText().trim();
            if (robotName.isEmpty()) {
                logger.error("Create Superdroid: robot name empty");
                return;
            }
            for (char c : robotName.toCharArray())
                if (!Character.isDigit(c) && !Character.isLetter(c)) {
                    logger.error("Create Superdroid: illegal robot name");
                    return;
                }

            controller.createSuperdroidRobot(robotName, pose, true);
            controller.createSimSuperdroid(robotName);
            dialog.dispose();
        }
    };
    name.addActionListener(okListener);
    x.addActionListener(okListener);
    y.addActionListener(okListener);
    ok.addActionListener(okListener);

    ActionListener cancelAction = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    };
    cancel.addActionListener(cancelAction);
    dialog.getRootPane().registerKeyboardAction(cancelAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            JComponent.WHEN_IN_FOCUSED_WINDOW);

    dialog.setLocationRelativeTo(frame);
    dialog.pack();
    dialog.setVisible(true);
}

From source file:org.commoncrawl.util.ArcFileWriter.java

private String escapeURI(String uri, String charsetEncoding) throws IOException {

    boolean needToChange = false;

    StringBuffer out = new StringBuffer(uri.length());

    Charset charset;/*from  w ww. j  a  va 2 s .co m*/

    CharArrayWriter charArrayWriter = new CharArrayWriter();

    if (charsetEncoding == null)
        throw new NullPointerException("charsetName");

    try {
        charset = Charset.forName(charsetEncoding);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(charsetEncoding);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(charsetEncoding);
    }

    for (int i = 0; i < uri.length();) {
        int c = (int) uri.charAt(i);
        // System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                 * If this character represents the start of a Unicode surrogate pair,
                 * then pass in two characters. It's not clear what should be done if
                 * a bytes reserved in the surrogate pairs range occurs outside of a
                 * legal surrogate pair. For now, just treat it as if it were any
                 * other character.
                 */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                     * System.out.println(Integer.toHexString(c) +
                     * " is high surrogate");
                     */
                    if ((i + 1) < uri.length()) {
                        int d = (int) uri.charAt(i + 1);
                        /*
                         * System.out.println("\tExamining " + Integer.toHexString(d));
                         */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                             * System.out.println("\t" + Integer.toHexString(d) +
                             * " is low surrogate");
                             */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < uri.length() && !dontNeedEncoding.get((c = (int) uri.charAt(i))));

            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charsetEncoding);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // converting to use uppercase letter as part of
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }

    return (needToChange ? out.toString() : uri);
}

From source file:org.nmrfx.processor.gui.PropertyManager.java

void setupItems() {
    ArrayList pyDocs = processorController.chartProcessor.getDocs();
    for (int i = 0; i < pyDocs.size(); i += 3) {
        String op = (String) pyDocs.get(i);
        ArrayList parList = (ArrayList) pyDocs.get(i + 1);
        String description = (String) pyDocs.get(i + 2);

        for (Object parObj : parList) {
            HashMap parMap = (HashMap) parObj;
            String name = (String) parMap.get("name");
            String parDesc = (String) parMap.get("desc");
            Boolean optional = (Boolean) parMap.get("optional");
            ArrayList types = (ArrayList) parMap.get("type");

            if (types.size() == 1) {
                String type = (String) types.get(0);
                switch (type) {
                case "string": {
                    String defaultString;
                    Object defObj = parMap.get("default");
                    if (defObj instanceof String) {
                        defaultString = (String) defObj;
                    } else if (defObj == null) {
                        defaultString = ""; // fixme  what to do when no default
                    } else {
                        defaultString = defObj.toString();
                    }//from   w  w w.j  av a 2s.c  om
                    propItems.add(new TextOperationItem(stringListener, defaultString, op, name, parDesc));

                    break;
                }
                case "wstring": {
                    String defaultString;
                    Object defObj = parMap.get("default");
                    if (defObj instanceof String) {
                        defaultString = (String) defObj;
                    } else if (defObj == null) {
                        defaultString = ""; // fixme  what to do when no default
                    } else {
                        defaultString = defObj.toString();
                    }
                    propItems.add(new TextWaitingOperationItem(null, this::updateOp, defaultString, op, name,
                            parDesc));
                    break;
                }
                case "file":
                    String defaultString;
                    Object defObj = parMap.get("default");
                    if (defObj instanceof String) {
                        defaultString = (String) defObj;
                    } else if (defObj == null) {
                        defaultString = ""; // fixme  what to do when no default
                    } else {
                        defaultString = defObj.toString();
                    }
                    propItems.add(new FileOperationItem(stringListener, defaultString, op, name, parDesc));
                    break;
                case "bool":
                    boolean defaultBool;
                    defObj = parMap.get("default");
                    if (defObj instanceof Boolean) {
                        defaultBool = ((Boolean) defObj);
                    } else if (defObj == null) {
                        defaultBool = false; // fixme  what to do when no default
                    } else {
                        String defStr = (String) defObj;
                        defaultBool = Boolean.parseBoolean(defStr);
                    }
                    propItems.add(new BooleanOperationItem(boolListener, defaultBool, op, name, parDesc));
                    break;
                case "int":
                    int minInt = -16384;
                    int maxInt = 16384;
                    if (parMap.containsKey("min")) {
                        Object minObj = parMap.get("min");
                        if (minObj instanceof Integer) {
                            minInt = ((Integer) minObj).intValue();
                        } else {
                            String minStr = (String) minObj;
                            if (minStr.startsWith("size")) {
                                minInt = 0;
                            } else {
                                minInt = Integer.parseInt(minStr);
                            }
                        }
                    }
                    if (parMap.containsKey("max")) {
                        Object maxObj = parMap.get("max");
                        if (maxObj instanceof Integer) {
                            maxInt = ((Integer) maxObj).intValue();
                        } else {

                            String maxStr = (String) maxObj;
                            if (maxStr.startsWith("size")) {
                                maxInt = 16384;
                            } else {
                                maxInt = Integer.parseInt(maxStr);
                            }
                        }
                    }
                    int defaultInt;
                    defObj = parMap.get("default");
                    if (defObj instanceof Integer) {
                        defaultInt = ((Integer) defObj).intValue();
                    } else if (defObj == null) {
                        defaultInt = 0; // fixme  what to do when no default
                    } else {
                        String defStr = (String) defObj;
                        defaultInt = Integer.parseInt(defStr);
                    }
                    if ((maxInt - minInt) < 2048) {
                        propItems.add(new IntRangeOperationItem(intListener, defaultInt, minInt, maxInt, op,
                                name, parDesc));
                    } else {
                        propItems.add(new IntOperationItem(intListener, defaultInt, minInt, maxInt, op, name,
                                parDesc));

                    }

                    break;
                case "complex":
                    Object defComplexObj = parMap.get("default");
                    if (defComplexObj instanceof PyComplex) {
                        PyComplex defPyComplex = (PyComplex) defComplexObj;
                        Complex defComplex = new Complex(defPyComplex.real, defPyComplex.imag);
                        ComplexOperationItem crItem = new ComplexOperationItem(complexListener, defComplex, op,
                                name, parDesc);
                        propItems.add(crItem);
                    } else if (defComplexObj instanceof Number) {
                        PyComplex defPyComplex = (PyComplex) defComplexObj;
                        Complex defComplex = new Complex(defPyComplex.real, defPyComplex.imag);
                        ComplexOperationItem crItem = new ComplexOperationItem(complexListener, defComplex, op,
                                name, parDesc);
                        propItems.add(crItem);
                    }
                    break;

                case "real":
                case "double":
                case "position":
                    double minDouble = -100000.0;
                    double maxDouble = 100000.0;
                    if (parMap.containsKey("min")) {
                        Object minObj = parMap.get("min");
                        if (minObj instanceof Double) {
                            minDouble = ((Double) minObj).doubleValue();
                        } else {
                            String minStr = (String) minObj;
                            if (minStr.startsWith("size")) {
                                minDouble = 0;
                            } else if (minStr.startsWith("Double.MIN")) {
                                minDouble = Double.MIN_VALUE;
                            } else {
                                minDouble = Double.parseDouble(minStr);
                            }
                        }
                    }
                    if (parMap.containsKey("max")) {
                        Object maxObj = parMap.get("max");
                        if (maxObj instanceof Double) {
                            maxDouble = ((Double) maxObj).doubleValue();
                        } else {

                            String maxStr = (String) maxObj;
                            if (maxStr.startsWith("size")) {
                                maxDouble = 1;
                            } else if (maxStr.startsWith("Double.MAX")) {
                                maxDouble = 100000.0;
                            } else {
                                maxDouble = Double.parseDouble(maxStr);
                            }
                        }
                    }
                    double aminDouble = Double.NEGATIVE_INFINITY;
                    double amaxDouble = Double.MAX_VALUE;
                    if (parMap.containsKey("amin")) {
                        Object minObj = parMap.get("amin");
                        if (minObj instanceof Double) {
                            aminDouble = ((Double) minObj).doubleValue();
                        } else {
                            String minStr = (String) minObj;
                            if (minStr.startsWith("size")) {
                                aminDouble = 0;
                            } else if (minStr.startsWith("Double.MIN")) {
                                aminDouble = Double.MIN_VALUE;
                            } else {
                                aminDouble = Double.parseDouble(minStr);
                            }
                        }

                    }
                    if (parMap.containsKey("amax")) {
                        Object maxObj = parMap.get("amax");
                        if (maxObj instanceof Double) {
                            amaxDouble = ((Double) maxObj).doubleValue();
                        } else {

                            String maxStr = (String) maxObj;
                            if (maxStr.startsWith("size")) {
                                amaxDouble = 1;
                            } else if (maxStr.startsWith("Double.MAX")) {
                                amaxDouble = 100000.0;
                            } else {
                                amaxDouble = Double.parseDouble(maxStr);
                            }
                        }

                    }
                    double defaultDouble;
                    char lastChar = (char) -1;
                    Object defDoubleObj = parMap.get("default");
                    if (defDoubleObj instanceof Double) {
                        defaultDouble = ((Double) defDoubleObj).doubleValue();
                    } else if (defDoubleObj instanceof Integer) {
                        defaultDouble = ((Integer) defDoubleObj).doubleValue();
                    } else if (defDoubleObj == null) {
                        defaultDouble = 0.0; // fixme  what to do when no default
                    } else {
                        String defStr = (String) defDoubleObj;
                        if (type.equals("position")) {
                            lastChar = defStr.charAt(defStr.length() - 1);
                            if (!Character.isLetter(lastChar)) {
                                lastChar = (char) -1;
                            }
                        }
                        defaultDouble = Double.parseDouble(defStr);
                    }

                    DoubleRangeOperationItem drItem = new DoubleRangeOperationItem(doubleListener,
                            defaultDouble, minDouble, maxDouble, aminDouble, amaxDouble, op, name, parDesc);
                    drItem.setLastChar(lastChar);
                    propItems.add(drItem);

                    break;
                case "list":
                    ArrayList listTypes = (ArrayList) parMap.get("listTypes");
                    ListOperationItem lstItem;
                    ArrayList defaultList = (ArrayList) parMap.get("default");
                    //ListOperationItemTypeSelector typeSelector = new ListOperationItemTypeSelector(stringListener, (String) listTypes.get(0), listTypes, op, "listType", parDesc);
                    ListOperationItemTypeSelector typeSelector = null;

                    if (listTypes == null || listTypes.isEmpty()) { // just a default list, so treat them as real values.
                        lstItem = new ListOperationItem(listListener, defaultList, listTypes, op, name, parDesc,
                                typeSelector);
                    } else {
                        lstItem = new ListOperationItem(listListener, defaultList, listTypes, op, name, parDesc,
                                typeSelector);
                    }

                    propItems.add(lstItem);
                    //propItems.add(typeSelector);
                    //propItems.add(listItemTypeSelector(listType));

                    //                            ListOperationItem lstItem = new ListOperationItem(listListener, defaultList, listType, op, name, parDesc)
                    break;
                default:
                    break;
                }
            } else {
                boolean isInt = true;
                for (Object type : types) {
                    if (!(type instanceof Integer)) {
                        isInt = false;
                        break;

                    }
                }
                if (isInt) {
                    propItems.add(new IntChoiceOperationItem(intListener, (Integer) types.get(0), types, op,
                            name, parDesc));
                } else {
                    propItems.add(new ChoiceOperationItem(stringListener, (String) types.get(0), types, op,
                            name, parDesc));

                }
            }
            // propItems.add(new DoubleRangeOperationItem(doubleListener, 1.0, 0.5, 1.0, "SB", "c", "First point multiplier"));

        }
        propItems.add(new BooleanOperationItem(boolListener, false, op, "disabled", "Disable this operation"));
    }

    //propItems.add(new DoubleRangeOperationItem(doubleListener, 1.0, 0.5, 1.0, "SB", "c", "First point multiplier"));
}

From source file:org.exoplatform.wcm.webui.formgenerator.UIFormGeneratorTabPane.java

private String formatInputName(String name) {
    name = cleanString(StringEscapeUtils.unescapeHtml(Text.unescape(name)));

    char firstChar = name.substring(0, 1).toCharArray()[0];
    if (!Character.isLetter(firstChar))
        return String.format("%s%s", INPUT_NAME_PREFIX, name);
    else//  w  w  w  .j a va2  s .co m
        return name;
}

From source file:org.imsglobal.lti.BasicLTIUtil.java

/**
 * The parameter name is mapped to lower case and any character that is
 * neither a number or letter is replaced with an "underscore". So if a
 * custom entry was as follows://from w  ww .  j  av a 2 s .  co  m
 *
 * {@code <parameter name="Vendor:Chapter">1.2.56</parameter>}
 *
 * Would map to: custom_vendor_chapter=1.2.56
 */
public static String mapKeyName(String keyname) {
    StringBuffer sb = new StringBuffer();
    if (keyname == null) {
        return null;
    }
    keyname = keyname.trim();
    if (keyname.length() < 1) {
        return null;
    }
    for (int i = 0; i < keyname.length(); i++) {
        Character ch = Character.toLowerCase(keyname.charAt(i));
        if (Character.isLetter(ch) || Character.isDigit(ch)) {
            sb.append(ch);
        } else {
            sb.append('_');
        }
    }
    return sb.toString();
}

From source file:org.apache.axis.utils.JavaUtils.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 a  va  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:com.gargoylesoftware.htmlunit.util.EncodingSniffer.java

/**
 * Attempts to sniff an encoding from an HTML <tt>meta</tt> tag in the specified byte array.
 *
 * @param bytes the bytes to check for an HTML <tt>meta</tt> tag
 * @return the encoding sniffed from the specified bytes, or {@code null} if the encoding
 *         could not be determined/*  w  w  w . ja  va  2 s .  com*/
 */
static String sniffEncodingFromMetaTag(final byte[] bytes) {
    for (int i = 0; i < bytes.length; i++) {
        if (matches(bytes, i, COMMENT_START)) {
            i = indexOfSubArray(bytes, new byte[] { '-', '-', '>' }, i);
            if (i == -1) {
                break;
            }
            i += 2;
        } else if (matches(bytes, i, META_START)) {
            i += META_START.length;
            for (Attribute att = getAttribute(bytes, i); att != null; att = getAttribute(bytes, i)) {
                i = att.getUpdatedIndex();
                final String name = att.getName();
                final String value = att.getValue();
                if ("charset".equals(name) || "content".equals(name)) {
                    String charset = null;
                    if ("charset".equals(name)) {
                        charset = value;
                    } else if ("content".equals(name)) {
                        charset = extractEncodingFromContentType(value);
                        if (charset == null) {
                            continue;
                        }
                    }
                    if (UTF16_BE.equalsIgnoreCase(charset) || UTF16_LE.equalsIgnoreCase(charset)) {
                        charset = UTF8;
                    }
                    if (isSupportedCharset(charset)) {
                        charset = charset.toUpperCase(Locale.ROOT);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Encoding found in meta tag: '" + charset + "'.");
                        }
                        return charset;
                    }
                }
            }
        } else if (i + 1 < bytes.length && bytes[i] == '<' && Character.isLetter(bytes[i + 1])) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E });
            if (i == -1) {
                break;
            }
            Attribute att;
            while ((att = getAttribute(bytes, i)) != null) {
                i = att.getUpdatedIndex();
            }
        } else if (i + 2 < bytes.length && bytes[i] == '<' && bytes[i + 1] == '/'
                && Character.isLetter(bytes[i + 2])) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E });
            if (i == -1) {
                break;
            }
            Attribute attribute;
            while ((attribute = getAttribute(bytes, i)) != null) {
                i = attribute.getUpdatedIndex();
            }
        } else if (matches(bytes, i, OTHER_START)) {
            i = skipToAnyOf(bytes, i, new byte[] { 0x3E });
            if (i == -1) {
                break;
            }
        }
    }
    return null;
}

From source file:CharUtils.java

/**
 * Capitalize first letter in string./*w  w  w . j av a  2  s  .com*/
 * 
 * @param s
 *            String to capitalize.
 * 
 * @return "s" with first letter (not first character) capitalized.
 *         Remaining characters are set to lower case.
 */

public static String capitalizeFirstLetter(String s) {
    char[] chars = s.toLowerCase().toCharArray();

    for (int i = 0; i < chars.length; i++) {
        char ch = chars[i];

        if (Character.isLetter(ch)) {
            chars[i] = Character.toUpperCase(ch);
            break;
        }
    }

    return new String(chars);
}

From source file:org.bibalex.wamcp.storage.WAMCPIndexedStorage.java

    /**
    * this method is used to make some processing on text so as to improve the searching results
    * @return/*from  ww  w  .  j ava  2  s. com*/
    * @throws XSAException
    * @throws DomBuildChangesException
    * @throws WFSVNException
    * @throws SugtnException
    * @throws JDOMException
    */
   @SuppressWarnings("deprecation")
   protected SolrInputDocument constructDocFromXSA() throws XSAException,
         DomBuildChangesException,
         WFSVNException, SugtnException, JDOMException {
// if (!this.initialized) {
// this.init();
// }
      SolrInputDocument result = new SolrInputDocument();
      
      boolean iniatlizedSdxe = false;
      
      if (!this.sdxeMediator.getDomTreeController().getIsInitialized()) {
         try {
            this.sdxeMediator.open(this.getWorkingFile().getCanonicalPath(),
                  this.schemaFilePath);
            XSALocator siteLoc = this.xsaDoc.getSiteLocator();
            this.sdxeMediator.moveToSugtnPath(siteLoc.asString());
         } catch (SDXEException e) {
            throw new WFSVNException(e);
         } catch (IOException e) {
            throw new WFSVNException(e);
         }
         
         iniatlizedSdxe = true;
      }
      
      try {
         List<XSAInstance> indexedInsts = this.xsaDoc.getIndexedInsts();
         
         for (XSAInstance xsaInst : indexedInsts) {
            
            String fieldName = this.ixedFieldsNames.get(xsaInst);
            String solrFieldType = this.ixedFieldsTypes.get(fieldName);
            
            String advFieldName = this.advSearchFieldsNames.get(xsaInst);
            // FIXME uncomment this, and index advanced search according to its type not the normal search type!
// String advFieldType = (advFieldName != null ? this.advSearchFieldsTypes
// .get(advFieldName) : null);
            
            String extraFacetFName = this.extraFacetFieldsNames.get(xsaInst);
            String extraFacetFType = (extraFacetFName != null ? this.extraFacetFieldsTypes
                  .get(extraFacetFName) : null);
            
            // Now find the nodes that must be indexed
            // YA 20110221 Index all occurences in all base shifts
// String allBrosStr = xsaInst.getXPathToAllOccsInAllConts();
            String allBrosStr = xsaInst.getXPathToAllOccsInAllBaseShifts();
            // END YA 20110221
            
            XPath allBrosXp = this.sdxeMediator.getDomTreeController()
                  .createXPathWithNS(allBrosStr);
            
            // this is part of the commit procedure so there can't be unsaved changes
            List allBros = allBrosXp.selectNodes(this.sdxeMediator.getDomTreeController()
                  .getDomTotal());
            
            for (Object bro : allBros) {
               
               String value = null;
               
               if (bro instanceof Element) {
// try {
                  value = ((Element) bro).getValue();
// Why would we index XML tags?
// JDOMUtils.getElementContentAsString((Element) bro, Format
// .getCompactFormat());
// value = value.replaceAll("<", "&lt;");
// value = value.replaceAll(">", "&gt;");
// } catch (IOException e) {
// throw new XSAException(e);
// }
                  
                  // And there is this Folio reference in many values.. let's strip it out
                  // And those stupid white spaces.. nuke 'em
                  value = value.replaceAll("[Ff]ol\\.\\ ?\\d+[ab]\\.?\\ ?\\d*", "").trim()
                        .replaceAll("\\s+", " ");
                  
               } else if (bro instanceof Attribute) {
                  value = ((Attribute) bro).getValue();
               } else {
                  throw new WFSVNException("Bad object type returned from: " + allBrosStr);
               }
               
               if ((extraFacetFType != null) && !extraFacetFType.isEmpty()
                     && !extraFacetFType.equals(solrFieldType)) {
                  if ("string".equals(extraFacetFType)) {
                     String facetVal = value.length() == 0 ? value : ArabicNormalizer
                           .normalize(value);
// facetVal = "\""+facetVal+"";
                     if ("Tahmid".equals(xsaInst.getIxFieldName())) {
                        facetVal = facetVal.replaceAll("[???]", "");
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim();
                        }
                        
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim();
                        }
// All diacretics are now removed
// // sometimes a shaddah is explicitly inserted
// if (facetVal.startsWith("")) {
// facetVal = facetVal.replaceFirst("", "").trim();
// }
                        
                        // other times they want to avoid the automatic shaddah
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim(); // to avoid the Shaddah they
// add a legator
                        }
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim(); // to avoid the Shaddah they
// add a legator
                        }
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim(); // to avoid the Shaddah they
// add a legator
                        }
                        
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim();
                        }
                        if (facetVal.startsWith("")) {
                           facetVal = facetVal.replaceFirst("", "").trim();
                        }
                        
                     }
                     StringTokenizer tahmidTokenz = new StringTokenizer(facetVal, " ",
                           false);
                     StringBuilder facetValBuilder = new StringBuilder();
                     int i = 0;
                     while (tahmidTokenz.hasMoreTokens() && (i < 20)) { // get max 25 words of the string
                        String token = tahmidTokenz.nextToken();
                        
                        facetValBuilder.append(token + " ");
                        
                        if (token.length() >= 3) {
                           ++i;
                        }
                        
                     }
                     
                     facetVal = facetValBuilder.toString();
// else if ("Provenance.Owners.Readers".equals(xsaInst.getIxFieldName())) {
                     
// if (facetVal.startsWith("Note of ownership:")) {
// facetVal = facetVal.replaceFirst("Note of ownership\\:", "")
// .trim();
// }
// }
                     this.addFieldValueToDoc(result, extraFacetFName, facetVal,
                           extraFacetFType);
                  } // TODO rest of types for extra facet
               }
               
               // The case of the date
               if (xsaInst.getIxFieldName().endsWith("Year") && (value != null)
                     && !value.isEmpty()) {
                  value = value.trim();
                  int lastSpace = value.lastIndexOf(' ');
                  if (lastSpace != -1) {
                     value = value.substring(lastSpace + 1); // the last part
                  }
                  try {
                     long normalizedValue = Long.valueOf(value);
                     
                     String calendar = xsaInst.getDomRep().getAttributeValue("calendar");
                     
                     normalizedValue += COMMONERA_CALENDARS_OFFSET.get(calendar);
                     
                     value = "" + normalizedValue;
                  } catch (NumberFormatException e) {
                     LOG.debug("Skipping the indexing of year from the value: " + value);
                     continue;
                  }
               }
               
               if ("boolean".equals(solrFieldType)) {
                  if ((value != null)
                        && !value.isEmpty()
                        && !("none".equalsIgnoreCase(value) || "no".equalsIgnoreCase(value)
                              || "false".equalsIgnoreCase(value) || "0"
                              .equalsIgnoreCase(value))) {
                     value = "true";
                  } else {
                     value = "false";
                  }
               }
               
               // The case of the shelfmark for sorting quasi-numerically
               if (fieldName.startsWith("Shelfmark")) {
                  String sortableShelfmark = value.replace(' ', '_');
                  int lastUnderscore = sortableShelfmark.lastIndexOf('_');
                  if (lastUnderscore > -1) {
                     sortableShelfmark = sortableShelfmark.substring(0, lastUnderscore);
                  }
                  
                  String actualShelfmark = value.substring(lastUnderscore + 1);
                  char lastChar = actualShelfmark.charAt(actualShelfmark.length() - 1);
                  boolean endWithALetter = Character.isLetter(lastChar);
                  if (endWithALetter) {
                     actualShelfmark = actualShelfmark
                           .substring(0, actualShelfmark.length() - 1);
                  }
                  while (actualShelfmark.length() < 4) {
                     actualShelfmark = '0' + actualShelfmark;
                  }
                  if (endWithALetter) {
                     actualShelfmark += lastChar;
                  }
                  sortableShelfmark += '_' + actualShelfmark;
                  
                  this.addFieldValueToDoc(result, "Sortable.Shelfmark", sortableShelfmark,
                        "string");
               }
               // all fields are now multivalues.. very few were not
// if (fieldName.endsWith("_M") && !solrFieldType.startsWith("text")) {
               if ((!xsaInst.isSingleton()
                     // || sugtnType.isListType() ||
// ((declNode instanceof SugtnElementNode)
// && ((SugtnElementNode) declNode).isMultivalued())
                     )
                     && !solrFieldType.startsWith("text")) {
                  // Field is multivalued but its content is not text, i.e. will not
                  // be analyzed or even tokenized on whitespace or anything..
                  // TOKENIZE IT HERE
                  
                  StringTokenizer tokens = new StringTokenizer(value, " ", false);
                  
                  while (tokens.hasMoreTokens()) {
                     String token = tokens.nextToken();
                     
                     this.addFieldValueToDoc(result, fieldName, token, null);
                     if (advFieldName != null) {
                        this.addFieldValueToDoc(result, advFieldName, token,
                              this.advSearchFieldsTypes.get(advFieldName));
                     }
                  }
                  
               } else {
                  this.addFieldValueToDoc(result, fieldName, value, null);
                  if (advFieldName != null) {
                     this.addFieldValueToDoc(result, advFieldName, value,
                           this.advSearchFieldsTypes.get(advFieldName));
                  }
                  
               }
            }
         }
      } finally {
         if (iniatlizedSdxe) {
            
            try {
               
               this.sdxeMediator.close();
               
            } catch (DomBuildException e) {
               throw new WFSVNException(e);
            }
            
         }
      }
      return result;
      
   }

From source file:net.spfbl.whois.Domain.java

/**
 * Atualiza os campos do registro com resultado do WHOIS.
 * @param result o resultado do WHOIS.//from  w w w.jav  a  2 s.c om
 * @return o domnio real apresentado no resultado do WHOIS.
 * @throws QueryException se houver alguma falha da atualizao do registro.
 */
private String refresh(String result) throws ProcessException {
    try {
        String ownerNew = null;
        String owneridNew = null;
        String responsibleNew = null;
        String countryNew = null;
        String owner_cNew = null;
        String admin_cNew = null;
        String tech_cNew = null;
        String billing_cNew = null;
        Date createdNew = null;
        Date expiresNew = null;
        Date changedNew = null;
        String providerNew = null;
        String statusNew = null;
        String dsrecordNew = null;
        String dsstatusNew = null;
        String dslastokNew = null;
        String saciNew = null;
        String web_whoisNew = null;
        ArrayList<String> nameServerListNew = new ArrayList<String>();
        boolean reducedNew = false;
        String domainResult = null;
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
        BufferedReader reader = new BufferedReader(new StringReader(result));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                try {
                    line = line.trim();
                    if (line.startsWith("domain:")) {
                        int index = line.indexOf(':') + 1;
                        domainResult = line.substring(index).trim();
                        // Remove a verso de domnios com acentuao.
                        index = domainResult.lastIndexOf(' ') + 1;
                        domainResult = domainResult.substring(index);
                        // Descobre o TLD do domnio e adiciona no conjunto.
                        index = domainResult.indexOf('.');
                        String tld = domainResult.substring(index);
                        addTLD(tld);
                    } else if (line.startsWith("owner:")) {
                        int index = line.indexOf(':') + 1;
                        ownerNew = line.substring(index).trim();
                    } else if (line.startsWith("ownerid:")) {
                        int index = line.indexOf(':') + 1;
                        owneridNew = line.substring(index).trim();
                    } else if (line.startsWith("p.a. to:")) {
                        // Este cammpo "p.a. to" (power of attorney to) 
                        //  equivalente ao ownerid. A diferena  que 
                        // neste caso  o ownerid do procurador invs 
                        // do prprio dono extrangeiro representado.
                        // https://registro.br/dominio/reg-estrangeiros.html
                        int index = line.indexOf(':') + 1;
                        owneridNew = line.substring(index).trim();
                    } else if (line.startsWith("responsible:")) {
                        int index = line.indexOf(':') + 1;
                        responsibleNew = line.substring(index).trim();
                    } else if (line.startsWith("country:")) {
                        int index = line.indexOf(':') + 1;
                        countryNew = line.substring(index).trim();
                    } else if (line.startsWith("owner-c:")) {
                        int index = line.indexOf(':') + 1;
                        owner_cNew = line.substring(index).trim();
                    } else if (line.startsWith("admin-c:")) {
                        int index = line.indexOf(':') + 1;
                        admin_cNew = line.substring(index).trim();
                    } else if (line.startsWith("tech-c:")) {
                        int index = line.indexOf(':') + 1;
                        tech_cNew = line.substring(index).trim();
                    } else if (line.startsWith("billing-c:")) {
                        int index = line.indexOf(':') + 1;
                        billing_cNew = line.substring(index).trim();
                    } else if (line.startsWith("nserver:")) {
                        int index = line.indexOf(':') + 1;
                        String nserver = line.substring(index).trim();
                        line = reader.readLine().trim();
                        index = line.indexOf(':') + 1;
                        String nsstat = line.substring(index).trim();
                        line = reader.readLine().trim();
                        index = line.indexOf(':') + 1;
                        String nslastaa = line.substring(index).trim();
                        NameServer ns = NameServer.getNameServer(nserver);
                        ns.setStat(nsstat);
                        ns.setLastAA(nslastaa);
                        nameServerListNew.add(nserver);
                    } else if (line.startsWith("created:")) {
                        int index = line.indexOf(':') + 1;
                        String valor = line.substring(index).trim();
                        if (valor.equals("multiple points")) {
                            valor = null;
                        } else if (valor.startsWith("before ")) {
                            index = line.indexOf(' ') - 1;
                            valor = valor.substring(index).trim();
                        }
                        if (valor != null && valor.length() > 7) {
                            valor = valor.substring(0, 8);
                            createdNew = dateFormatter.parse(valor);
                        }
                    } else if (line.startsWith("changed:")) {
                        int index = line.indexOf(':') + 1;
                        String valor = line.substring(index).trim();
                        if (valor.length() > 7) {
                            valor = valor.substring(0, 8);
                            changedNew = dateFormatter.parse(valor);
                        }
                    } else if (line.startsWith("expires:")) {
                        int index = line.indexOf(':') + 1;
                        String valor = line.substring(index).trim();
                        if (valor.length() > 7) {
                            valor = valor.substring(0, 8);
                            expiresNew = dateFormatter.parse(valor);
                        }
                    } else if (line.startsWith("status:")) {
                        int index = line.indexOf(':') + 1;
                        statusNew = line.substring(index).trim();
                    } else if (line.startsWith("dsrecord:")) {
                        int index = line.indexOf(':') + 1;
                        dsrecordNew = line.substring(index).trim();
                    } else if (line.startsWith("dsstatus:")) {
                        int index = line.indexOf(':') + 1;
                        dsstatusNew = line.substring(index).trim();
                    } else if (line.startsWith("dslastok:")) {
                        int index = line.indexOf(':') + 1;
                        dslastokNew = line.substring(index).trim();
                    } else if (line.startsWith("saci:")) {
                        int index = line.indexOf(':') + 1;
                        saciNew = line.substring(index).trim();
                    } else if (line.startsWith("web-whois:")) {
                        int index = line.indexOf(':') + 1;
                        web_whoisNew = line.substring(index).trim();
                    } else if (line.startsWith("provider:")) {
                        int index = line.indexOf(':') + 1;
                        providerNew = line.substring(index).trim();
                    } else if (line.startsWith("nic-hdl-br:")) {
                        try {
                            String person = null;
                            String e_mail = null;
                            String created2 = null;
                            String changed2 = null;
                            String provider2 = null;
                            String country2 = null;
                            int index = line.indexOf(':') + 1;
                            String nic_hdl_br = line.substring(index).trim();
                            while ((line = reader.readLine().trim()).length() > 0) {
                                index = line.indexOf(':') + 1;
                                if (line.startsWith("person:")) {
                                    person = line.substring(index).trim();
                                } else if (line.startsWith("e-mail:")) {
                                    e_mail = line.substring(index).trim();
                                } else if (line.startsWith("created:")) {
                                    created2 = line.substring(index).trim();
                                } else if (line.startsWith("changed:")) {
                                    changed2 = line.substring(index).trim();
                                } else if (line.startsWith("provider:")) {
                                    provider2 = line.substring(index).trim();
                                } else if (line.startsWith("country:")) {
                                    country2 = line.substring(index).trim();
                                } else {
                                    Server.logError("Linha no reconhecida: " + line);
                                }
                            }
                            Handle handle = Handle.getHandle(nic_hdl_br);
                            handle.setPerson(person);
                            handle.setEmail(e_mail);
                            handle.setCreated(created2);
                            handle.setChanged(changed2);
                            handle.setProvider(provider2);
                            handle.setCountry(country2);
                        } catch (ProcessException ex) {
                            Server.logError(ex);
                        }
                    } else if (line.startsWith("ticket:")) {
                        // Do nothing.
                    } else if (line.startsWith("% No match for domain")) {
                        throw new ProcessException("ERROR: DOMAIN NOT FOUND");
                    } else if (line.startsWith("% release process: ")) {
                        throw new ProcessException("ERROR: WAITING");
                    } else if (line.startsWith("% reserved:    CG")) {
                        throw new ProcessException("ERROR: RESERVED");
                    } else if (line.startsWith("% Permission denied.")) {
                        throw new ProcessException("ERROR: WHOIS DENIED");
                    } else if (line.startsWith("% Permisso negada.")) {
                        throw new ProcessException("ERROR: WHOIS DENIED");
                    } else if (line.startsWith("% Maximum concurrent connections limit exceeded")) {
                        throw new ProcessException("ERROR: WHOIS CONCURRENT");
                    } else if (line.startsWith("% Query rate limit exceeded. Reduced information.")) {
                        // Informao reduzida devido ao estouro de limite de consultas.
                        Server.removeWhoisQueryHour();
                        reducedNew = true;
                    } else if (line.startsWith("% Query rate limit exceeded")) {
                        // Restrio total devido ao estouro de limite de consultas.
                        Server.removeWhoisQueryDay();
                        throw new ProcessException("ERROR: WHOIS QUERY LIMIT");
                    } else if (line.length() > 0 && Character.isLetter(line.charAt(0))) {
                        Server.logError("Linha no reconhecida: " + line);
                    }
                } catch (NumberFormatException ex) {
                    Server.logError(ex);
                    Server.logError(line);
                }
            }
        } finally {
            reader.close();
        }
        if (domainResult == null) {
            throw new ProcessException("ERROR: DOMAIN NOT FOUND");
        } else {
            this.owner = ownerNew;
            if (owneridNew != null) {
                // Associar ownerid somente se retornar valor.
                this.ownerid = owneridNew;
            }
            this.responsible = responsibleNew;
            this.country = countryNew;
            this.owner_c = owner_cNew;
            this.admin_c = admin_cNew;
            this.tech_c = tech_cNew;
            this.billing_c = billing_cNew;
            this.created = createdNew;
            this.expires = expiresNew;
            this.changed = changedNew;
            this.provider = providerNew;
            this.status = statusNew;
            this.dsrecord = dsrecordNew;
            this.dsstatus = dsstatusNew;
            this.dslastok = dslastokNew;
            this.saci = saciNew;
            this.web_whois = web_whoisNew;
            this.nameServerList.clear();
            this.nameServerList.addAll(nameServerListNew);
            this.reduced = reducedNew;
            DOMAIN_CHANGED = true;
            this.lastRefresh = System.currentTimeMillis();
            this.queries = 1;
            // Retorna o domnio real indicado pelo WHOIS.
            return domainResult;
        }
    } catch (ProcessException ex) {
        throw ex;
    } catch (Exception ex) {
        Server.logError(ex);
        throw new ProcessException("ERROR: PARSING " + result, ex);
    }
}