List of usage examples for java.lang Character toString
public static String toString(int codePoint)
From source file:me.taylorkelly.mywarp.bukkit.util.FormattingUtils.java
/** * Centralizes the given string relative to the given width by padding it with the given character. */*from ww w.j av a2 s . c om*/ * @param str the string to centralize * @param pad the padding char * @param paddedWidth the width of the padded string * @return the centered string */ public static String center(String str, char pad, int paddedWidth) { paddedWidth -= getWidth(str); String padding = StringUtils.repeat(Character.toString(pad), paddedWidth / getWidth(pad) / 2); return padding + str + padding; }
From source file:com.l2jfree.gameserver.util.Util.java
/** * Capitalizes the first letter of every "word" in a string.<BR> * (Based on ucwords() function of PHP)/*w ww .j av a2 s. c om*/ * * @param String str * @return String containing the modified string. */ public static String capitalizeWords(String str) { char[] charArray = str.toCharArray(); String result = ""; // Capitalize the first letter in the given string! charArray[0] = Character.toUpperCase(charArray[0]); for (int i = 0; i < charArray.length; i++) { if (Character.isWhitespace(charArray[i])) charArray[i + 1] = Character.toUpperCase(charArray[i + 1]); result += Character.toString(charArray[i]); } return result; }
From source file:org.apache.pdfbox.encoding.Encoding.java
/** * This will take a character code and get the name from the code. * * @param c The character./*ww w .j a v a2 s. c o m*/ * * @return The name of the character. * * @throws IOException If there is no name for the character. */ public String getNameFromCharacter(char c) throws IOException { String name = CHARACTER_TO_NAME.get(Character.toString(c)); if (name == null) { throw new IOException("No name for character '" + c + "'"); } return name; }
From source file:org.easyrec.service.core.impl.ActionServiceImpl.java
public void importActionsFromCSV(String fileName, ActionVO<Integer, Integer> defaults) { long start = System.currentTimeMillis(); if (logger.isInfoEnabled()) { logger.info("==================== starting importing 'action' ======================="); logger.info("importing 'action' from CSV '" + fileName + "'"); logger.info("using interface defaults '" + defaults + "'"); logger.info("========================================================================"); }/*from www. ja v a2 s .c om*/ if (fileName == null) { throw new IllegalArgumentException("missing 'fileName'"); } BufferedReader br = null; int lineCounter = 3; int savedCounter = 0; int removedCounter = 0; int skippedCounter = 0; int errorCounter = 0; int currentSavedCounter = 0; String command = null; try { try { br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); } catch (FileNotFoundException e) { throw new IllegalArgumentException("file '" + fileName + "' not found", e); } String line = null; String elementsOfLine[] = null; // read command try { line = br.readLine(); } catch (IOException e) { throw new IllegalStateException("unexpected IOException", e); } try { // in case of we have an 'old style' file format, containing no 'type' definition, then the first line would contain the command command = AutoImportUtils.retrieveCommandFromLine(line); } catch (IllegalArgumentException e) { // this should be the normal case, the file contains a 'type' definition, so we need to skip this line // read/skip type try { line = br.readLine(); } catch (IOException ioe) { throw new IllegalStateException("unexpected IOException", ioe); } command = AutoImportUtils.retrieveCommandFromLine(line); } // skip file if the command is not an 'insert' command if (!AutoImportUtils.COMMAND_INSERT.equalsIgnoreCase(command)) { throw new IllegalStateException("command '" + command + "' is not allowed for the type 'action'"); } // read header and generate headerDefaults try { line = br.readLine(); } catch (IOException e) { throw new IllegalStateException("unexpected IOException", e); } ActionVO<Integer, Integer> headerDefaults = generateDefaultsFromHeader(line, defaults); if (logger.isInfoEnabled()) { logger.info("extracted header defaults from csv file, using: " + headerDefaults); } // fetch next line try { while ((line = br.readLine()) != null) { lineCounter++; // skip empty lines if ("".equals(line)) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "line is empty"); skippedCounter++; continue; } // skip comment lines if (line.startsWith(Character.toString(AutoImportUtils.CSV_COMMENT_CHAR))) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "line is a comment"); skippedCounter++; continue; } // skip lines, with wrong number of columns elementsOfLine = line.split(AutoImportUtils.CSV_SEPARATOR, ActionVO.CSV_NUMBER_OF_COLUMNS); if (elementsOfLine.length != ActionVO.CSV_NUMBER_OF_COLUMNS) { StringBuilder s = new StringBuilder("', number of columns should be '"); s.append(ActionVO.CSV_NUMBER_OF_COLUMNS); s.append("', but was '"); s.append(elementsOfLine.length); s.append("'"); AutoImportUtils.logSkippedLine(logger, lineCounter, line, s.toString()); skippedCounter++; continue; } ActionVO<Integer, Integer> action = null; try { action = (ActionVO<Integer, Integer>) headerDefaults.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "value object 'ActionVO' does not support .clone() anymore, check that!!"); } // parse 'tenantId' if (!"".equals(elementsOfLine[0])) { try { action.setTenant(Integer.parseInt(elementsOfLine[0])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'tenantId' is no valid 'Integer'"); skippedCounter++; continue; } } else { // 'tenantId' NOT NULL if (action.getTenant() == null) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "no value for field 'tenantId' is set"); skippedCounter++; continue; } } // parse 'userId' if (!"".equals(elementsOfLine[1])) { try { action.setUser(Integer.parseInt(elementsOfLine[1])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'userId' is no valid 'Integer'"); skippedCounter++; continue; } } // parse 'sessionId' if (!"".equals(elementsOfLine[2])) { action.setSessionId(elementsOfLine[2]); } // parse 'ip' if (!"".equals(elementsOfLine[3])) { action.setIp(elementsOfLine[3]); } // parse 'itemId' if (!"".equals(elementsOfLine[4])) { try { action.getItem().setItem(Integer.parseInt(elementsOfLine[4])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'itemId' is no valid 'Integer'"); skippedCounter++; continue; } } // parse 'itemTypeId' if (!"".equals(elementsOfLine[5])) { try { action.getItem().setType(Integer.parseInt(elementsOfLine[5])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'itemTypeId' is no valid 'Integer'"); skippedCounter++; continue; } } else { // 'itemTypeId' NOT NULL if (action.getItem().getType() == null) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "no value for field 'itemTypeId' is set"); skippedCounter++; continue; } } // parse 'actionTypeId' if (!"".equals(elementsOfLine[6])) { try { action.setActionType(Integer.parseInt(elementsOfLine[6])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'actionTypeId' is no valid 'Integer'"); skippedCounter++; continue; } } else { // 'actionTypeId' NOT NULL if (action.getActionType() == null) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "no value for field 'actionTypeId' is set"); skippedCounter++; continue; } } // parse 'ratingValue' if (!"".equals(elementsOfLine[7])) { try { action.setRatingValue(Integer.parseInt(elementsOfLine[7])); } catch (NumberFormatException nfe) { AutoImportUtils.logSkippedLine(logger, lineCounter, line, "value for field 'ratingValue' is no valid 'Integer'"); skippedCounter++; continue; } } // parse 'description' if (!"".equals(elementsOfLine[8])) { action.setActionInfo(elementsOfLine[8]); } try { int savedThisIteration = 0; // inserting action (no update allowed for type 'action') savedThisIteration = insertAction(action); currentSavedCounter += savedThisIteration; savedCounter += savedThisIteration; int currentSavedMultiplier = currentSavedCounter / reportBlockSize; if (currentSavedMultiplier > 0) { if (logger.isInfoEnabled()) { logger.info("number of saved 'action' entries: " + (currentSavedMultiplier * reportBlockSize)); } currentSavedCounter %= reportBlockSize; } /*} catch (DataIntegrityViolationException dive) { // wait a little, we have two identical actions, without an actionDate try { Thread.sleep(1000); } catch (InterruptedException ie) { logger.info("error occured during (delayed try of) insertAction() '" + action + "'", ie); } int savedThisIteration = 0; // inserting action (no update allowed for type 'action') savedThisIteration = insertAction(action); currentSavedCounter += savedThisIteration; savedCounter += savedThisIteration; int currentSavedMultiplier = currentSavedCounter / reportBlockSize; if (currentSavedMultiplier > 0) { if (logger.isInfoEnabled()) { logger.info("number of saved 'action' entries: " + (currentSavedMultiplier * reportBlockSize)); } currentSavedCounter %= reportBlockSize; }*/ } catch (Exception e) { errorCounter++; logger.error("error occured during insertAction() '" + action + "'", e); } } // end of while } catch (IOException e) { throw new IllegalStateException("unexpected IOException", e); } } finally { // close stream if (br != null) { try { br.close(); } catch (IOException e) { throw new IllegalStateException("unexpected IOException", e); } } } if (logger.isInfoEnabled()) { if (currentSavedCounter > 0) { logger.info("number of saved 'action' entries: " + currentSavedCounter); } logger.info( "==================== finished importing from file '" + fileName + "' ===================="); logger.info("total number of saved 'action' entries: " + savedCounter); logger.info("total number of removed 'action' entries: " + removedCounter); logger.info("total number of skipped 'action' entries: " + skippedCounter); logger.info("total number of errors occured while import: " + errorCounter); logger.info("used defaults: '" + defaults + "'"); logger.info("time taken: " + (System.currentTimeMillis() - start) + " ms"); logger.info("========================================================================"); } }
From source file:jp.terasoluna.fw.util.ConvertUtil.java
/** * <code>value</code>??????? * ?<code>String</code>????<code>List</code>?? * ?// www . j a v a 2 s . c om * * @param value ?? * @return ??????????<code>List</code> * ??????<code>value</code>???? */ public static Object convertPrimitiveArrayToList(Object value) { if (value == null) { return value; } Class<?> type = value.getClass().getComponentType(); // value??????? if (type == null) { return value; } // ????????? if (!type.isPrimitive()) { return value; } List<Object> list = new ArrayList<Object>(); if (value instanceof boolean[]) { for (boolean data : (boolean[]) value) { // String??????? list.add(data); } } else if (value instanceof byte[]) { for (byte data : (byte[]) value) { list.add(Byte.toString(data)); } } else if (value instanceof char[]) { for (char data : (char[]) value) { list.add(Character.toString(data)); } } else if (value instanceof double[]) { for (double data : (double[]) value) { list.add(Double.toString(data)); } } else if (value instanceof float[]) { for (float data : (float[]) value) { list.add(Float.toString(data)); } } else if (value instanceof int[]) { for (int data : (int[]) value) { list.add(Integer.toString(data)); } } else if (value instanceof long[]) { for (long data : (long[]) value) { list.add(Long.toString(data)); } } else if (value instanceof short[]) { for (short data : (short[]) value) { list.add(Short.toString(data)); } } return list; }
From source file:org.hyperic.hq.ui.taglib.ConstantsTag.java
public int doEndTag() throws JspException { try {//from ww w . j a v a 2 s. c o m JspWriter out = pageContext.getOut(); if (className == null) { className = pageContext.getServletContext().getInitParameter(constantsClassNameParam); } if (validate(out)) { // we're misconfigured. getting this far // is a matter of what our failure mode is // if we haven't thrown an Error, carry on log.debug("constants tag misconfigured"); return EVAL_PAGE; } HashMap fieldMap; if (constants.containsKey(className)) { // we cache the result of the constants class // reflection field walk as a map fieldMap = (HashMap) constants.get(className); } else { fieldMap = new HashMap(); Class typeClass = Class.forName(className); //Object con = typeClass.newInstance(); Field[] fields = typeClass.getFields(); for (int i = 0; i < fields.length; i++) { // string comparisons of class names should be cheaper // than reflective Class comparisons, the asumption here // is that most constants are Strings, ints and booleans // but a minimal effort is made to accomadate all types // and represent them as String's for our tag's output //BIG NEW ASSUMPTION: Constants are statics and do not require instantiation of the class if (Modifier.isStatic(fields[i].getModifiers())) { String fieldType = fields[i].getType().getName(); String strVal; if (fieldType.equals("java.lang.String")) { strVal = (String) fields[i].get(null); } else if (fieldType.equals("int")) { strVal = Integer.toString(fields[i].getInt(null)); } else if (fieldType.equals("boolean")) { strVal = Boolean.toString(fields[i].getBoolean(null)); } else if (fieldType.equals("char")) { strVal = Character.toString(fields[i].getChar(null)); } else if (fieldType.equals("double")) { strVal = Double.toString(fields[i].getDouble(null)); } else if (fieldType.equals("float")) { strVal = Float.toString(fields[i].getFloat(null)); } else if (fieldType.equals("long")) { strVal = Long.toString(fields[i].getLong(null)); } else if (fieldType.equals("short")) { strVal = Short.toString(fields[i].getShort(null)); } else if (fieldType.equals("byte")) { strVal = Byte.toString(fields[i].getByte(null)); } else { Object val = (Object) fields[i].get(null); strVal = val.toString(); } fieldMap.put(fields[i].getName(), strVal); } } // cache the result constants.put(className, fieldMap); } if (symbol != null && !fieldMap.containsKey(symbol)) { // tell the developer that he's being a dummy and what // might be done to remedy the situation // TODO: what happens if the constants change? // do we need to throw a JspException, here? String err1 = symbol + " was not found in " + className + "\n"; String err2 = err1 + "use <constants:diag classname=\"" + className + "\"/>\n" + "to figure out what you're looking for"; log.error(err2); die(out, err1); } if (varSpecified) { doSet(fieldMap); } else { doOutput(fieldMap, out); } } catch (JspException e) { throw e; } catch (Exception e) { log.debug("doEndTag() failed: ", e); throw new JspException("Could not access constants tag", e); } return EVAL_PAGE; }
From source file:org.apache.qpid.server.security.access.config.PlainConfiguration.java
@Override public RuleSet load() { RuleSet ruleSet = super.load(); File file = getFile();/*from w w w . j a va2 s.c o m*/ FileReader fileReader = null; try { if (_logger.isDebugEnabled()) { _logger.debug("About to load ACL file " + file); } fileReader = new FileReader(file); _st = new StreamTokenizer(new BufferedReader(fileReader)); _st.resetSyntax(); // setup the tokenizer _st.commentChar(COMMENT); // single line comments _st.eolIsSignificant(true); // return EOL as a token _st.ordinaryChar('='); // equals is a token _st.ordinaryChar(CONTINUATION); // continuation character (when followed by EOL) _st.quoteChar('"'); // double quote _st.quoteChar('\''); // single quote _st.whitespaceChars('\u0000', '\u0020'); // whitespace (to be ignored) TODO properly _st.wordChars('a', 'z'); // unquoted token characters [a-z] _st.wordChars('A', 'Z'); // [A-Z] _st.wordChars('0', '9'); // [0-9] _st.wordChars('_', '_'); // underscore _st.wordChars('-', '-'); // dash _st.wordChars('.', '.'); // dot _st.wordChars('*', '*'); // star _st.wordChars('@', '@'); // at _st.wordChars(':', ':'); // colon // parse the acl file lines Stack<String> stack = new Stack<String>(); int current; do { current = _st.nextToken(); switch (current) { case StreamTokenizer.TT_EOF: case StreamTokenizer.TT_EOL: if (stack.isEmpty()) { break; // blank line } // pull out the first token from the bottom of the stack and check arguments exist String first = stack.firstElement(); stack.removeElementAt(0); if (stack.isEmpty()) { throw new IllegalConfigurationException(String.format(NOT_ENOUGH_TOKENS_MSG, getLine())); } // check for and parse optional initial number for ACL lines Integer number = null; if (StringUtils.isNumeric(first)) { // set the acl number and get the next element number = Integer.valueOf(first); first = stack.firstElement(); stack.removeElementAt(0); } if (StringUtils.equalsIgnoreCase(ACL, first)) { parseAcl(number, stack); } else if (number == null) { if (StringUtils.equalsIgnoreCase("GROUP", first)) { throw new IllegalConfigurationException(String.format( "GROUP keyword not supported. Groups should defined via a Group Provider, not in the ACL file.", getLine())); } else if (StringUtils.equalsIgnoreCase(CONFIG, first)) { parseConfig(stack); } else { throw new IllegalConfigurationException( String.format(UNRECOGNISED_INITIAL_MSG, first, getLine())); } } else { throw new IllegalConfigurationException( String.format(NUMBER_NOT_ALLOWED_MSG, first, getLine())); } // reset stack, start next line stack.clear(); break; case StreamTokenizer.TT_NUMBER: stack.push(Integer.toString(Double.valueOf(_st.nval).intValue())); break; case StreamTokenizer.TT_WORD: stack.push(_st.sval); // token break; default: if (_st.ttype == CONTINUATION) { int next = _st.nextToken(); if (next == StreamTokenizer.TT_EOL) { break; // continue reading next line } // invalid location for continuation character (add one to line beacuse we ate the EOL) throw new IllegalConfigurationException( String.format(PREMATURE_CONTINUATION_MSG, getLine() + 1)); } else if (_st.ttype == '\'' || _st.ttype == '"') { stack.push(_st.sval); // quoted token } else { stack.push(Character.toString((char) _st.ttype)); // single character } } } while (current != StreamTokenizer.TT_EOF); if (!stack.isEmpty()) { throw new IllegalConfigurationException(String.format(PREMATURE_EOF_MSG, getLine())); } } catch (IllegalArgumentException iae) { throw new IllegalConfigurationException(String.format(PARSE_TOKEN_FAILED_MSG, getLine()), iae); } catch (FileNotFoundException fnfe) { throw new IllegalConfigurationException(String.format(CONFIG_NOT_FOUND_MSG, file.getName()), fnfe); } catch (IOException ioe) { throw new IllegalConfigurationException(String.format(CANNOT_LOAD_MSG, file.getName()), ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { throw new IllegalConfigurationException(String.format(CANNOT_CLOSE_MSG, file.getName()), e); } } } return ruleSet; }
From source file:com.janela.mobile.ui.repo.RepositoryListFragment.java
private void updateHeaders(final List<Repository> repos) { HeaderFooterListAdapter<?> rootAdapter = getListAdapter(); if (rootAdapter == null) return;/*from w ww .j a v a 2 s.com*/ DefaultRepositoryListAdapter adapter = (DefaultRepositoryListAdapter) rootAdapter.getWrappedAdapter(); adapter.clearHeaders(); if (repos.isEmpty()) return; // Add recent header if at least one recent repository Repository first = repos.get(0); if (recentRepos.contains(first)) adapter.registerHeader(first, getString(R.string.recently_viewed)); // Advance past all recent repositories int index; Repository current = null; for (index = 0; index < repos.size(); index++) { Repository repository = repos.get(index); if (recentRepos.contains(repository.getId())) current = repository; else break; } if (index >= repos.size()) return; if (current != null) adapter.registerNoSeparator(current); // Register header for first character current = repos.get(index); char start = Character.toLowerCase(current.getName().charAt(0)); adapter.registerHeader(current, Character.toString(start).toUpperCase(US)); char previousHeader = start; for (index = index + 1; index < repos.size(); index++) { current = repos.get(index); char repoStart = Character.toLowerCase(current.getName().charAt(0)); if (repoStart <= start) continue; // Don't include separator for the last element of the previous // character if (previousHeader != repoStart) adapter.registerNoSeparator(repos.get(index - 1)); adapter.registerHeader(current, Character.toString(repoStart).toUpperCase(US)); previousHeader = repoStart; start = repoStart++; } // Don't include separator for last element adapter.registerNoSeparator(repos.get(repos.size() - 1)); }
From source file:com.android.dialer.lookup.google.GoogleForwardLookup.java
/** * Generate a random string of alphanumeric characters of length [4, 36) * * @return Random alphanumeric string/*from w ww.j av a2 s.c o m*/ */ private String getRandomNoiseString() { StringBuilder garbage = new StringBuilder(); int length = getRandomInteger(32) + 4; for (int i = 0; i < length; i++) { int asciiCode; if (Math.random() >= 0.3) { if (Math.random() <= 0.5) { // Lowercase letters asciiCode = getRandomInteger(26) + 97; } else { // Uppercase letters asciiCode = getRandomInteger(26) + 65; } } else { // Numbers asciiCode = getRandomInteger(10) + 48; } garbage.append(Character.toString((char) asciiCode)); } return garbage.toString(); }
From source file:com.flexive.tests.browser.AdmScriptsTest.java
License:asdf
/** * creates a script/*from w ww . j a v a 2 s . c o m*/ * @param name name of the script * @param defaultScriptEvent default script event, if <code>null</code> than it is ignored * @param script the script * @param defaultImports shall click on default imports * @param syntaxCheck shall click on syntaxcheck (modifies the return value) * @param cancel cancel instead of save * @param expectedResult_syntax expected result of the syntaxcheck * @param expectedResult_save expected result of saving * @param LOG the Log to log * @return <code>true</code> if all the results are expected */ private boolean createScript(String name, String defaultScriptEvent, String script, boolean defaultImports, boolean syntaxCheck, boolean cancel, Boolean expectedResult_syntax, Boolean expectedResult_save, Log LOG) { loadContentPage(SCRIPT_CREATE_PAGE); selectFrame(Frame.Content); boolean returnValue = true; String space = Character.toString(' '); String bb = Character.toString('\b'); selenium.type("frm:name", name); selenium.keyDown("frm:name", space); selenium.keyUp("frm:name", space); sleep(2000); selenium.keyDown("frm:name", bb); selenium.keyUp("frm:name", bb); sleep(2000); // selenium.keyPress(); if (defaultScriptEvent != null) { selenium.select("frm:event", defaultScriptEvent); } if (defaultImports) { clickAndWait("link=Add default imports", 10000); if (syntaxCheck) { clickAndWait("link=Syntax check", 10000); returnValue = returnValue & checkText("Syntax check passed.", expectedResult_syntax, LOG); } } if (script != null) { setCheckboxState("edit_area_toggle_checkbox_frm:code", false); // String code = selenium.getText("frm:code") + "\n"; String code = getElementValue("frm:code"); selenium.type("frm:code", code + script); lastScriptSrc = getElementValue("frm:code"); } if (syntaxCheck) { clickAndWait("link=Syntax check", 10000); returnValue = returnValue & checkText("Syntax check passed.", expectedResult_syntax, LOG); } if (cancel) { clickAndWait("link=Cancel"); } else { clickAndWait("link=Create script"); returnValue = returnValue & checkText("The script " + name + " was successfully created.", expectedResult_save, LOG); } return returnValue; }