List of usage examples for java.lang Character isLetter
public static boolean isLetter(int codePoint)
From source file:userinterface.Citizen.CitizenWorkAreaJPanel.java
private void resRateFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_resRateFieldKeyPressed if (Character.isLetter(evt.getKeyChar())) { evt.consume();//w ww .ja va 2 s .co m } else { return; } }
From source file:org.zaproxy.zap.extension.zest.ZestZapUtils.java
public static boolean isValidVariableName(String name) { if (name == null || name.length() == 0) { return false; }//from w w w .j a v a 2 s .c o m if (!Character.isLetter(name.charAt(0))) { // Seams reasonable to require it starts with a character return false; } for (char chr : name.toCharArray()) { if (!Character.isLetterOrDigit(chr) && ZEST_VAR_VALID_CHRS.indexOf(chr) == -1) { return false; } } return true; }
From source file:edu.umich.robot.GuiApplication.java
public void connectSuperdroidRobotDialog() { final int defaultPort = 3192; FormLayout layout = new FormLayout("right:pref, 4dlu, 35dlu, 4dlu, 35dlu", "pref, 2dlu, pref, 2dlu, pref, 2dlu, pref"); final JDialog dialog = new JDialog(frame, "Connect to Superdroid", true); dialog.setLayout(layout);/*from w ww.j av a 2s. c om*/ final JTextField namefield = new JTextField("charlie"); final JTextField hostfield = new JTextField("192.168.1.165"); final JTextField portfield = new JTextField(Integer.toString(defaultPort)); 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(namefield, cc.xyw(3, 1, 3)); dialog.add(new JLabel("Host"), cc.xy(1, 3)); dialog.add(hostfield, cc.xyw(3, 3, 3)); dialog.add(new JLabel("Port"), cc.xy(1, 5)); dialog.add(portfield, cc.xyw(3, 5, 3)); dialog.add(cancel, cc.xy(3, 7)); dialog.add(ok, cc.xy(5, 7)); portfield.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { int p = defaultPort; try { p = Integer.parseInt(portfield.getText()); if (p < 1) p = 1; if (p > 65535) p = 65535; } catch (NumberFormatException ex) { } portfield.setText(Integer.toString(p)); } }); final ActionListener okListener = new ActionListener() { public void actionPerformed(ActionEvent e) { String robotName = namefield.getText().trim(); if (robotName.isEmpty()) { logger.error("Connect 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; } } try { controller.createRealSuperdroid(robotName, hostfield.getText(), Integer.valueOf(portfield.getText())); } catch (UnknownHostException ex) { ex.printStackTrace(); logger.error("Connect Superdroid: " + ex); } catch (SocketException ex) { ex.printStackTrace(); logger.error("Connect Superdroid: " + ex); } dialog.dispose(); } }; namefield.addActionListener(okListener); hostfield.addActionListener(okListener); portfield.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:com.insprise.common.lang.StringUtilities.java
/** * <p>Creates a random string based on a variety of options, using * supplied source of randomness.</p> */* w ww .j a v a 2 s . c o m*/ * <p>If start and end are both <code>0</code>, start and end are set * to <code>' '</code> and <code>'z'</code>, the ASCII printable * characters, will be used, unless letters and numbers are both * <code>false</code>, in which case, start and end are set to * <code>0</code> and <code>Integer.MAX_VALUE</code>. * * <p>If set is not <code>null</code>, characters between start and * end are chosen.</p> * * <p>This method accepts a user-supplied {@link Random} * instance to use as a source of randomness. By seeding a single * {@link Random} instance with a fixed seed and using it for each call, * the same random sequence of strings can be generated repeatedly * and predictably.</p> * * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from. * If <code>null</code>, then it will use the set of all chars. * @param random a source of randomness. * @return the random string * @throws ArrayIndexOutOfBoundsException if there are not * <code>(end - start) + 1</code> characters in the set array. * @throws IllegalArgumentException if <code>count</code> < 0. * @since 2.0 */ public static String randomString(int count, int start, int end, boolean letters, boolean numbers, char[] chars) { Random random = RANDOM; // random instance. if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if ((start == 0) && (end == 0)) { end = 'z' + 1; start = ' '; if (!letters && !numbers) { start = 0; end = Integer.MAX_VALUE; } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if ((letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) { if (ch >= 56320 && ch <= 57343) { if (count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if (ch >= 55296 && ch <= 56191) { if (count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if (ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); }
From source file:util.program.ProgramTextCreator.java
private static void addEntry(ExtendedHTMLDocument doc, StringBuilder buffer, Program prog, ProgramFieldType fieldType, boolean createLinks, boolean showHelpLinks, boolean showPersonLinks) { try {/*from w ww . ja va 2 s .co m*/ String text = null; String name = fieldType.getLocalizedName(); int blank = name.indexOf(' ', 16); if (blank > 0) { name = name.substring(0, blank) + "<br>" + name.substring(blank + 1); } if (fieldType.getFormat() == ProgramFieldType.TEXT_FORMAT) { text = prog.getTextField(fieldType); if (ProgramFieldType.SHORT_DESCRIPTION_TYPE == fieldType) { text = checkDescription(text); } // Lazily add short description, but only if it differs from description if (fieldType == ProgramFieldType.DESCRIPTION_TYPE) { String description = checkDescription(prog.getDescription()); text = description; if (prog.getShortInfo() != null) { StringBuilder shortInfo = new StringBuilder(checkDescription(prog.getShortInfo()).trim()); // delete "..." at the end, but only for duplication check, not for display while (shortInfo.toString().endsWith(".")) { shortInfo.deleteCharAt(shortInfo.length() - 1); } if (!description.trim().startsWith(shortInfo.toString())) { addEntry(doc, buffer, prog, ProgramFieldType.SHORT_DESCRIPTION_TYPE, true, showHelpLinks); } } text = text.replace("\\-", ""); // replace conditional dashes text = removeArtificialLineBreaks(text); text = HTMLTextHelper.convertTextToHtml(text, createLinks); // scan for moderation in beginning of description String[] lines = text.split("<br>"); String[] tags = { "von und mit", "prsentiert von", "mit", "film von", "moderation", "zu gast" }; for (int i = 0; i < 2; i++) { if (lines.length > i && lines[i].length() < 60) { String line = lines[i]; for (String tag : tags) { if (line.toLowerCase().startsWith(tag) || line.toLowerCase().startsWith(tag + ':')) { String personsString = line.substring(tag.length(), line.length()).trim(); if (personsString.startsWith(":")) { personsString = personsString.substring(1).trim(); } if (personsString.endsWith(".")) { personsString = personsString.substring(0, personsString.length() - 1) .trim(); } String[] persons = personsString.split(" und "); boolean doLink = true; for (String person : persons) { if (person.isEmpty() || !Character.isLetter(person.charAt(0)) || Character.isLowerCase(person.charAt(0))) { doLink = false; break; } } if (doLink) { for (String person : persons) { String[] names = person.split(" "); int partCount = names.length; if (partCount >= 2 && partCount < 4) { for (String n : names) { if (!StringUtils.isAlpha(n)) { doLink = false; } } if (doLink) { text = StringUtils.replaceOnce(text, person, addSearchLink(person)); } } } break; } } } } } } } else if (fieldType.getFormat() == ProgramFieldType.TIME_FORMAT) { text = prog.getTimeFieldAsString(fieldType); } else if (fieldType.getFormat() == ProgramFieldType.INT_FORMAT) { if (fieldType == ProgramFieldType.RATING_TYPE) { int value = prog.getIntField(fieldType); if (value > -1) { text = new DecimalFormat("##.#").format((double) prog.getIntField(fieldType) / 10) + "/10"; } } else { text = prog.getIntFieldAsString(fieldType); if (text == null && fieldType == ProgramFieldType.AGE_LIMIT_TYPE) { final String ageRating = prog.getTextField(ProgramFieldType.AGE_RATING_TYPE); if (ageRating != null && !ageRating.isEmpty()) { int age = ProgramUtilities.getAgeLimit(ageRating); if (age >= 0) { text = Integer.toString(age); } } } } } if (fieldType == ProgramFieldType.ORIGIN_TYPE) { String temp = prog.getIntFieldAsString(ProgramFieldType.PRODUCTION_YEAR_TYPE); if (temp != null && temp.trim().length() > 0) { if (text == null || text.trim().length() < 1) { name = ProgramFieldType.PRODUCTION_YEAR_TYPE.getLocalizedName(); text = temp; } else { name += "/<br>" + ProgramFieldType.PRODUCTION_YEAR_TYPE.getLocalizedName(); text += " " + temp; } } temp = prog.getIntFieldAsString(ProgramFieldType.LAST_PRODUCTION_YEAR_TYPE); if (temp != null && temp.trim().length() > 0) { if (text == null || text.trim().length() < 1) { name = ProgramFieldType.LAST_PRODUCTION_YEAR_TYPE.getLocalizedName(); text = temp; } else { text += " - " + temp; } } } if (text == null || text.trim().length() < 1) { if (ProgramFieldType.CUSTOM_TYPE == fieldType) { text = mLocalizer.msg("noCustom", "No custom information "); } else { return; } } startInfoSection(buffer, name); // add person links if (ProgramFieldType.DIRECTOR_TYPE == fieldType || ProgramFieldType.SCRIPT_TYPE == fieldType || ProgramFieldType.CAMERA_TYPE == fieldType || ProgramFieldType.CUTTER_TYPE == fieldType || ProgramFieldType.MUSIC_TYPE == fieldType || ProgramFieldType.MODERATION_TYPE == fieldType || ProgramFieldType.ADDITIONAL_PERSONS_TYPE == fieldType || ProgramFieldType.PRODUCER_TYPE == fieldType) { if (showPersonLinks && text.length() < 200) { // if field is longer, this is probably not a list of names if (text.endsWith(".")) { text = text.substring(0, text.length() - 1); } String[] persons = splitPersons(text); for (int i = 0; i < persons.length; i++) { // remove duplicate entries boolean duplicate = false; if (i < persons.length - 1) { for (int j = i + 1; j < persons.length; j++) { if (persons[i].equalsIgnoreCase(persons[j])) { duplicate = true; break; } } } if (duplicate) { text = text.replaceFirst(Pattern.quote(persons[i]), "").trim(); if (text.startsWith(",")) { text = text.substring(1).trim(); } text = text.replaceAll(",\\s*,", ","); continue; } // a name shall not have more name parts if (persons[i].trim().split(" ").length <= 3) { String link; if (persons[i].contains("(")) { int index = persons[i].indexOf('('); String topic = persons[i].substring(0, index).trim(); link = addSearchLink(topic) + " " + persons[i].substring(index).trim(); } else { link = addSearchLink(persons[i]); } text = text.replace(persons[i], link); } } } buffer.append(text); } else if (ProgramFieldType.DESCRIPTION_TYPE == fieldType) { buffer.append(text); } else { buffer.append(HTMLTextHelper.convertTextToHtml(text, createLinks)); } if ((ProgramFieldType.CUSTOM_TYPE == fieldType) && (showHelpLinks)) { buffer.append(" (<a href=\"").append( mLocalizer.msg("customInfo", "http://enwiki.tvbrowser.org/index.php/CustomInformation")) .append("\">?</a>)"); } if ((ProgramFieldType.AGE_RATING_TYPE == fieldType) && (showHelpLinks)) { addHelpLink(buffer, mLocalizer.msg("ratingInfo", "http://en.wikipedia.org/wiki/Motion_picture_rating_system")); } buffer.append("</td></tr>"); addSeparator(doc, buffer); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.moqui.impl.service.ServiceDefinition.java
private boolean validateParameterSingle(MNode valNode, String parameterName, Object pv, ExecutionContextImpl eci) {/*from w ww . j a v a2 s. c om*/ // should never be null (caller checks) but check just in case if (pv == null) return true; String validateName = valNode.getName(); if ("val-or".equals(validateName)) { boolean anyPass = false; for (MNode child : valNode.getChildren()) if (validateParameterSingle(child, parameterName, pv, eci)) anyPass = true; return anyPass; } else if ("val-and".equals(validateName)) { boolean allPass = true; for (MNode child : valNode.getChildren()) if (!validateParameterSingle(child, parameterName, pv, eci)) allPass = false; return allPass; } else if ("val-not".equals(validateName)) { boolean allPass = true; for (MNode child : valNode.getChildren()) if (!validateParameterSingle(child, parameterName, pv, eci)) allPass = false; return !allPass; } else if ("matches".equals(validateName)) { if (!(pv instanceof CharSequence)) { Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is not a string, cannot do matches validation.", "", map), null); return false; } String pvString = pv.toString(); String regexp = valNode.attribute("regexp"); if (regexp != null && !regexp.isEmpty() && !pvString.matches(regexp)) { // a message attribute should always be there, but just in case we'll have a default final String message = valNode.attribute("message"); Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("regexp", regexp); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource() .expand(message != null && !message.isEmpty() ? message : "Value entered (${pv}) did not match expression: ${regexp}", "", map), null); return false; } return true; } else if ("number-range".equals(validateName)) { BigDecimal bdVal = new BigDecimal(pv.toString()); String minStr = valNode.attribute("min"); if (minStr != null && !minStr.isEmpty()) { BigDecimal min = new BigDecimal(minStr); if ("false".equals(valNode.attribute("min-include-equals"))) { if (bdVal.compareTo(min) <= 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("min", min); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is less than or equal to ${min} must be greater than.", "", map), null); return false; } } else { if (bdVal.compareTo(min) < 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("min", min); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is less than ${min} and must be greater than or equal to.", "", map), null); return false; } } } String maxStr = valNode.attribute("max"); if (maxStr != null && !maxStr.isEmpty()) { BigDecimal max = new BigDecimal(maxStr); if ("true".equals(valNode.attribute("max-include-equals"))) { if (bdVal.compareTo(max) > 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("max", max); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is greater than ${max} and must be less than or equal to.", "", map), null); return false; } } else { if (bdVal.compareTo(max) >= 0) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("max", max); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}) is greater than or equal to ${max} and must be less than.", "", map), null); return false; } } } return true; } else if ("number-integer".equals(validateName)) { try { new BigInteger(pv.toString()); } catch (NumberFormatException e) { if (logger.isTraceEnabled()) logger.trace( "Adding error message for NumberFormatException for BigInteger parse: " + e.toString()); Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${pv}] is not a whole (integer) number.", "", map), null); return false; } return true; } else if ("number-decimal".equals(validateName)) { try { new BigDecimal(pv.toString()); } catch (NumberFormatException e) { if (logger.isTraceEnabled()) logger.trace( "Adding error message for NumberFormatException for BigDecimal parse: " + e.toString()); Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${pv}] is not a decimal number.", "", map), null); return false; } return true; } else if ("text-length".equals(validateName)) { String str = pv.toString(); String minStr = valNode.attribute("min"); if (minStr != null && !minStr.isEmpty()) { int min = Integer.parseInt(minStr); if (str.length() < min) { Map<String, Object> map = new HashMap<>(3); map.put("pv", pv); map.put("str", str); map.put("minStr", minStr); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}), length ${str.length()}, is shorter than ${minStr} characters.", "", map), null); return false; } } String maxStr = valNode.attribute("max"); if (maxStr != null && !maxStr.isEmpty()) { int max = Integer.parseInt(maxStr); if (str.length() > max) { Map<String, Object> map = new HashMap<>(3); map.put("pv", pv); map.put("str", str); map.put("maxStr", maxStr); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand( "Value entered (${pv}), length ${str.length()}, is longer than ${maxStr} characters.", "", map), null); return false; } } return true; } else if ("text-email".equals(validateName)) { String str = pv.toString(); if (!emailValidator.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) is not a valid email address.", "", map), null); return false; } return true; } else if ("text-url".equals(validateName)) { String str = pv.toString(); if (!urlValidator.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) is not a valid URL.", "", map), null); return false; } return true; } else if ("text-letters".equals(validateName)) { String str = pv.toString(); for (char c : str.toCharArray()) { if (!Character.isLetter(c)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${str}) must have only letters.", "", map), null); return false; } } return true; } else if ("text-digits".equals(validateName)) { String str = pv.toString(); for (char c : str.toCharArray()) { if (!Character.isDigit(c)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value [${str}] must have only digits.", "", map), null); return false; } } return true; } else if ("time-range".equals(validateName)) { Calendar cal; String format = valNode.attribute("format"); if (pv instanceof CharSequence) { cal = eci.getL10n().parseDateTime(pv.toString(), format); } else { // try letting groovy convert it cal = Calendar.getInstance(); // TODO: not sure if this will work: ((pv as java.util.Date).getTime()) cal.setTimeInMillis((DefaultGroovyMethods.asType(pv, Date.class)).getTime()); } String after = valNode.attribute("after"); if (after != null && !after.isEmpty()) { // handle after date/time/date-time depending on type of parameter, support "now" too Calendar compareCal; if ("now".equals(after)) { compareCal = Calendar.getInstance(); compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime()); } else { compareCal = eci.getL10n().parseDateTime(after, format); } if (cal != null && !cal.after(compareCal)) { Map<String, Object> map = new HashMap<>(2); map.put("pv", pv); map.put("after", after); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${pv}) is before ${after}.", "", map), null); return false; } } String before = valNode.attribute("before"); if (before != null && !before.isEmpty()) { // handle after date/time/date-time depending on type of parameter, support "now" too Calendar compareCal; if ("now".equals(before)) { compareCal = Calendar.getInstance(); compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime()); } else { compareCal = eci.getL10n().parseDateTime(before, format); } if (cal != null && !cal.before(compareCal)) { Map<String, Object> map = new HashMap<>(1); map.put("pv", pv); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand("Value entered (${pv}) is after ${before}.", "", map), null); return false; } } return true; } else if ("credit-card".equals(validateName)) { long creditCardTypes = 0; String types = valNode.attribute("types"); if (types != null && !types.isEmpty()) { for (String cts : types.split(",")) creditCardTypes += creditCardTypeMap.get(cts.trim()); } else { creditCardTypes = allCreditCards; } CreditCardValidator ccv = new CreditCardValidator(creditCardTypes); String str = pv.toString(); if (!ccv.isValid(str)) { Map<String, String> map = new HashMap<>(1); map.put("str", str); eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource() .expand("Value entered (${str}) is not a valid credit card number.", "", map), null); return false; } return true; } // shouldn't get here, but just in case return true; }
From source file:lucee.commons.lang.StringUtil.java
/** * returns true if all characters in the string are letters * * @param str// w w w. j a va2s. c o m * @return */ public static boolean isAllAlpha(String str) { if (str == null) return false; for (int i = str.length() - 1; i >= 0; i--) { if (!Character.isLetter(str.charAt(i))) return false; } return true; }
From source file:com.orange.api.atmosdav.AtmosDavServlet.java
public static String encode(String s) { int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now StringBuffer out = new StringBuffer(s.length()); ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); try {/* w w w .ja va2s . co m*/ OutputStreamWriter writer = new OutputStreamWriter(buf, dfltEncName); for (int i = 0; i < s.length(); i++) { int c = (int) s.charAt(i); if (dontNeedEncoding.get(c)) { out.append((char) c); } else { // convert to external encoding before hex conversion try { writer.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) { if ((i + 1) < s.length()) { int d = (int) s.charAt(i + 1); if (d >= 0xDC00 && d <= 0xDFFF) { writer.write(d); i++; } } } writer.flush(); } catch (IOException e) { buf.reset(); continue; } byte[] ba = buf.toByteArray(); 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); } buf.reset(); } } return out.toString(); } catch (UnsupportedEncodingException e) { return s; } }
From source file:lucee.commons.lang.StringUtil.java
/** * returns true if the input string has letters and they are all UPPERCASE * * @param str/*from ww w .j a v a 2 s .co m*/ * @return */ public static boolean isAllUpperCase(String str) { if (str == null) return false; boolean hasLetters = false; char c; for (int i = str.length() - 1; i >= 0; i--) { c = str.charAt(i); if (Character.isLetter(c)) { if (!Character.isUpperCase(c)) return false; hasLetters = true; } } return hasLetters; }
From source file:com.udojava.evalex.Expression.java
/** * Implementation of the <i>Shunting Yard</i> algorithm to transform an * infix expression to a RPN expression. * * @param expression The input expression in infx. * @return A RPN representation of the expression, with each token as a list * member.//w w w . j a v a 2 s. c om */ private List<String> shuntingYard(String expression) { List<String> outputQueue = new ArrayList<>(); Stack<String> stack = new Stack<>(); Tokenizer tokenizer = new Tokenizer(expression); String lastFunction = null; String previousToken = null; while (tokenizer.hasNext()) { String token = tokenizer.next(); if (isNumber(token)) { if (token.startsWith("x")) { BigInteger bd = new BigInteger(token.substring(1), 16); outputQueue.add(bd.toString(10)); } else if (token.startsWith("b")) { BigInteger bd = new BigInteger(token.substring(1), 2); outputQueue.add(bd.toString(10)); } else if (token.startsWith("o")) { BigInteger bd = new BigInteger(token.substring(1), 8); outputQueue.add(bd.toString(10)); } else { outputQueue.add(token); } } else if (mainVars.containsKey(token)) { outputQueue.add(token); } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) { stack.push(token); lastFunction = token; } else if ((Character.isLetter(token.charAt(0)) || token.charAt(0) == '_') && !operators.containsKey(token)) { mainVars.put(token, new MyComplex(0, 0)); // create variable outputQueue.add(token); //stack.push(token); } else if (",".equals(token)) { if (operators.containsKey(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + previousToken + " at character position " + (tokenizer.getPos() - 1 - previousToken.length())); } while (!stack.isEmpty() && !"(".equals(stack.peek())) { outputQueue.add(stack.pop()); } if (stack.isEmpty()) { throw new ExpressionException("Parse error for function '" + lastFunction + "'"); } } else if (operators.containsKey(token)) { if (",".equals(previousToken) || "(".equals(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + token + " at character position " + (tokenizer.getPos() - token.length())); } Operator o1 = operators.get(token); String token2 = stack.isEmpty() ? null : stack.peek(); while (token2 != null && operators.containsKey(token2) && ((o1.isLeftAssoc() && o1.getPrecedence() <= operators.get(token2).getPrecedence()) || (o1.getPrecedence() < operators.get(token2).getPrecedence()))) { outputQueue.add(stack.pop()); token2 = stack.isEmpty() ? null : stack.peek(); } stack.push(token); } else if ("(".equals(token)) { if (previousToken != null) { if (isNumber(previousToken)) { throw new ExpressionException( "Missing operator at character position " + tokenizer.getPos()); } // if the ( is preceded by a valid function, then it // denotes the start of a parameter list if (functions.containsKey(previousToken.toUpperCase(Locale.ROOT))) { outputQueue.add(token); } } stack.push(token); } else if (")".equals(token)) { if (operators.containsKey(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + previousToken + " at character position " + (tokenizer.getPos() - 1 - previousToken.length())); } while (!stack.isEmpty() && !"(".equals(stack.peek())) { outputQueue.add(stack.pop()); } if (stack.isEmpty()) { throw new ExpressionException("Mismatched parentheses"); } stack.pop(); if (!stack.isEmpty() && functions.containsKey(stack.peek().toUpperCase(Locale.ROOT))) { outputQueue.add(stack.pop()); } } previousToken = token; } while (!stack.isEmpty()) { String element = stack.pop(); if ("(".equals(element) || ")".equals(element)) { throw new ExpressionException("Mismatched parentheses"); } if (!operators.containsKey(element)) { throw new ExpressionException("Unknown operator or function: " + element); } outputQueue.add(element); } return outputQueue; }