List of usage examples for java.lang StringBuffer setLength
@Override public synchronized void setLength(int newLength)
From source file:org.latticesoft.util.common.ConvertUtil.java
public static String formatBinary(int value) { StringBuffer sb = new StringBuffer(); String s = Integer.toBinaryString(value); for (int i = s.length(); i < 32; i++) { sb.append("0"); }//from ww w .jav a2 s .c o m sb.append(s); s = sb.toString(); sb.setLength(0); for (int i = 0; i < 32; i++) { sb.append(s.charAt(i)); if (i > 0 && (i + 1) % 4 == 0) { sb.append(" "); } } return sb.toString(); }
From source file:org.latticesoft.util.common.NumeralUtil.java
public static byte[] convertHexStringToByteArray(String s) { byte[] retVal = null; if (s == null || s.length() == 0) { return null; }//from w ww . j a v a 2s .c om if (s.length() % 2 != 0) { return null; } s = s.toUpperCase(); int index = 0; //int len = s.length(); List l = new ArrayList(); StringBuffer sb = new StringBuffer(); while (index < s.length()) { sb.setLength(0); sb.append(s.charAt(index++)); sb.append(s.charAt(index++)); byte b = convertHexStringToByte(sb.toString()); l.add(new Byte(b)); } retVal = new byte[l.size()]; for (int i = 0; i < l.size(); i++) { Byte bb = (Byte) l.get(i); retVal[i] = bb.byteValue(); } return retVal; }
From source file:Main.java
/** * Parse the 'compressed' binary form of Android XML docs * such as for AndroidManifest.xml in .apk files *///w ww .j a va 2s . co m private static String decompressXML(byte[] bytes_xml) { StringBuilder stringBuilder = new StringBuilder(); //Compressed XML file/bytes starts with 24x bytes of data, //9 32 bit words in little endian order (LSB first): // 0th word is 03 00 08 00 // 3rd word SEEMS TO BE: Offset at then of StringTable // 4th word is: Number of strings in string table //WARNING: Sometime I indiscriminently display or refer to word in //little endian storage format, or in integer format (ie MSB first). int num_strings = LEW(bytes_xml, 4 * 4); //StringIndexTable starts at offset 24x, an array of 32 bit LE offsets //of the length/string data in the StringTable. int sit_off = 0x24;//Offset of start of StringIndexTable //StringTable, each string is represented with a 16 bit little endian //character count, followed by that number of 16 bit (LE) (Unicode) chars. int st_off = sit_off + num_strings * 4;//StringTable follows StrIndexTable //XMLTags, The XML tag tree starts after some unknown content after the //StringTable. There is some unknown data after the StringTable, scan //forward from this point to the flag for the start of an XML start tag. int xml_tag_off = LEW(bytes_xml, 3 * 4);//Start from the offset in the 3rd word. //Scan forward until we find the bytes: 0x02011000(x00100102 in normal int) for (int i = xml_tag_off, len = bytes_xml.length - 4; i < len; i += 4) { if (LEW(bytes_xml, i) == START_TAG) { xml_tag_off = i; break; } } //XML tags and attributes: //Every XML start and end tag consists of 6 32 bit words: // 0th word: 02011000 for startTag and 03011000 for endTag // 1st word: a flag?, like 38000000 // 2nd word: Line of where this tag appeared in the original source file // 3rd word: FFFFFFFF ?? // 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS // 5th word: StringIndex of Element Name //(Note: 01011000 in 0th word means end of XML document, endDocTag) //Start tags (not end tags) contain 3 more words: // 6th word: 14001400 meaning?? // 7th word: Number of Attributes that follow this tag(follow word 8th) // 8th word: 00000000 meaning?? //Attributes consist of 5 words: // 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF // 1st word: StringIndex of Attribute Name // 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used // 3rd word: Flags? // 4th word: str ind of attr value again, or ResourceId of value stringBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); StringBuffer buffer = new StringBuffer(); //Step through the XML tree element tags and attributes int off = xml_tag_off; int indent = 0; while (off < bytes_xml.length) { int tag0 = LEW(bytes_xml, off); int name_si = LEW(bytes_xml, off + 5 * 4); if (tag0 == START_TAG) { int num_attrs = LEW(bytes_xml, off + 7 * 4);//Number of Attributes to follow off += 9 * 4;//Skip over 6 + 3 words of startTag data String name = compXmlString(bytes_xml, sit_off, st_off, name_si); //Look for the Attributes buffer.setLength(0); for (int i = 0; i < num_attrs; ++i) { int attr_name_si = LEW(bytes_xml, off + 1 * 4);//AttrName String Index int attr_value_si = LEW(bytes_xml, off + 2 * 4);//AttrValue Str Ind, or FFFFFFFF int attr_res_id = LEW(bytes_xml, off + 4 * 4);//AttrValue ResourceId or dup AttrValue StrInd off += 5 * 4;//Skip over the 5 words of an attribute String attr_name = compXmlString(bytes_xml, sit_off, st_off, attr_name_si); String attr_value = attr_value_si != -1 ? compXmlString(bytes_xml, sit_off, st_off, attr_value_si) : String.valueOf(attr_res_id); buffer.append(String.format(" %1$s=\"%2$s\"", attr_name, attr_value)); } stringBuilder.append("\n"); stringBuilder.append(String.format("%1$s<%2$s%3$s>", getIndent(indent), name, buffer)); ++indent; } else if (tag0 == END_TAG) { --indent; off += 6 * 4;//Skip over 6 words of endTag data String name = compXmlString(bytes_xml, sit_off, st_off, name_si); stringBuilder.append("\n"); stringBuilder.append(String.format("%1$s</%2$s>", getIndent(indent), name)); } else if (tag0 == END_DOC_TAG) { break; } } return stringBuilder.toString(); }
From source file:org.latticesoft.util.common.NumeralUtil.java
/** * Compares 2 float value based on the given number of decimal * place to compare.// w w w . j a v a 2 s . c o m * @param f1 float variable 1 * @param f2 float variable 2 * @param decimalPlace the number of dp to compare * @return 0 if they are the same, 1 if f1 */ public static int compareFloat(float f1, float f2, int decimalPlace) { String[][] s = new String[2][]; s[0] = StringUtil.tokenizeIntoStringArray(Float.toString(f1), "."); s[1] = StringUtil.tokenizeIntoStringArray(Float.toString(f2), "."); if (s[0] == null || s[1] == null) return 0; int[] x = new int[2]; x[0] = NumeralUtil.parseInt(s[0][0]); x[1] = NumeralUtil.parseInt(s[1][0]); if (x[0] > x[1]) return 1; if (x[0] < x[1]) return -1; // they are equal in whole number // now compare decimal point up the the stated decimal places StringBuffer sb = new StringBuffer(); for (int i = 0; i < 2; i++) { sb.setLength(0); int nextPoint = 0; if (s[0][1].length() < decimalPlace) { sb.append(s[i][1]); for (int j = s[i][1].length(); j < decimalPlace; j++) { sb.append("0"); } nextPoint = 0; } else { sb.append(s[i][1].substring(0, decimalPlace)); if (s[i][1].length() >= decimalPlace + 1) { nextPoint = NumeralUtil.parseInt(s[i][1].substring(decimalPlace, decimalPlace + 1)); } else { nextPoint = 0; } } x[i] = NumeralUtil.parseInt(sb.toString()); if (nextPoint >= 5) x[i]++; } if (x[0] > x[1]) return 1; else if (x[0] < x[1]) return -1; else return 0; }
From source file:com.tremolosecurity.scale.config.ScaleCommonConfig.java
public static String includeEnvironmentVariables(String srcPath) throws IOException { StringBuffer b = new StringBuffer(); String line = null;/*from w w w .ja va 2s . c o m*/ BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(srcPath))); while ((line = in.readLine()) != null) { b.append(line).append('\n'); } String cfg = b.toString(); if (logger.isDebugEnabled()) { logger.debug("---------------"); logger.debug("Before environment variables : '" + srcPath + "'"); logger.debug(cfg); logger.debug("---------------"); } int begin, end; b.setLength(0); begin = 0; end = 0; String finalCfg = null; begin = cfg.indexOf("#["); while (begin > 0) { if (end == 0) { b.append(cfg.substring(0, begin)); } else { b.append(cfg.substring(end, begin)); } end = cfg.indexOf(']', begin + 2); String envVarName = cfg.substring(begin + 2, end); String value = System.getenv(envVarName); if (value == null) { value = System.getProperty(envVarName); } if (logger.isDebugEnabled()) { logger.debug("Environment Variable '" + envVarName + "'='" + value + "'"); } b.append(value); begin = cfg.indexOf("#[", end + 1); end++; } if (end == 0) { finalCfg = cfg; } else { b.append(cfg.substring(end)); finalCfg = b.toString(); } if (logger.isDebugEnabled()) { logger.debug("---------------"); logger.debug("After environment variables : '" + srcPath + "'"); logger.debug(finalCfg); logger.debug("---------------"); } return finalCfg; }
From source file:org.apache.cocoon.util.IOUtils.java
/** * Return a modified filename suitable for replicating directory * structures below the store's base directory. The following * conversions are performed:// w ww . ja v a 2 s . c om * <ul> * <li>Path separators are converted to regular directory names</li> * <li>File path components are transliterated to make them valid (?) * programming language identifiers. This transformation may well * generate collisions for unusual filenames.</li> * </ul> * @return The transformed filename */ public static String normalizedFilename(String filename) { if ("".equals(filename)) { return ""; } filename = (File.separatorChar == '\\') ? filename.replace('/', '\\') : filename.replace('\\', '/'); String[] path = StringUtils.split(filename, File.separator); int start = (path[0].length() == 0) ? 1 : 0; StringBuffer buffer = new StringBuffer(); for (int i = start; i < path.length; i++) { if (i > start) { buffer.append(File.separator); } if (path[i].equals("..")) { int lio; for (lio = buffer.length() - 2; lio >= 0; lio--) { if (buffer.substring(lio).startsWith(File.separator)) { break; } } if (lio >= 0) { buffer.setLength(lio); } } else { char[] chars = path[i].toCharArray(); if (chars.length < 1 || !Character.isLetter(chars[0])) { buffer.append('_'); } for (int j = 0; j < chars.length; j++) { if (org.apache.cocoon.util.StringUtils.isAlphaNumeric(chars[j])) { buffer.append(chars[j]); } else { buffer.append('_'); } } // Append the suffix if necessary. if (isJavaKeyword(path[i])) buffer.append(keywordSuffix); } } return buffer.toString(); }
From source file:org.opencms.jsp.search.result.CmsSearchStateParameters.java
/** Converts a parameter map to the parameter string. * @param parameters the parameter map.// ww w.j a va 2 s. com * @return the parameter string. */ public static String paramMapToString(final Map<String, String[]> parameters) { final StringBuffer result = new StringBuffer(); for (final String key : parameters.keySet()) { String[] values = parameters.get(key); if (null == values) { result.append(key).append('&'); } else { for (final String value : parameters.get(key)) { result.append(key).append('=').append(value).append('&'); } } } // remove last '&' if (result.length() > 0) { result.setLength(result.length() - 1); } return result.toString(); }
From source file:jcurl.core.io.OldConfigReader.java
/** * Read a single token.//from w ww . j a v a2 s. c om * * @param read * @return - * @throws IOException */ static String readToken(final Reader read) throws IOException { final StringBuffer ret = new StringBuffer(); final int pre = 1; final int content = 2; final int comment = 3; char sep = '-'; int state = pre; for (;;) { int ch = read.read(); switch (state) { case pre: if (ch == -1) { log.debug("token=[null]"); return null; } if (Character.isWhitespace((char) ch)) continue; if ('#' == (char) ch) state = comment; else { ret.setLength(0); if ('"' == (char) ch) sep = '"'; else { sep = ' '; ret.append((char) ch); } state = content; } break; case content: final String s0 = ret.toString().trim(); if (ch == -1) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == ' ' && Character.isWhitespace((char) ch)) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == '"' && '"' == (char) ch) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == ' ' && '#' == (char) ch) state = comment; else ret.append((char) ch); break; case comment: final String s = ret.toString().trim(); if (ch == -1) { log.debug("token=[" + s + "]"); return s; } if ('\n' == (char) ch || '\r' == (char) ch) { if (s.length() == 0) state = pre; else { log.debug("token=[" + s + "]"); return s; } } break; } } }
From source file:org.jcurl.core.io.OldConfigReader.java
/** * Read a single token./*from ww w. ja v a 2 s. c o m*/ * * @param read * @return - * @throws IOException */ static String readToken(final Reader read) throws IOException { final StringBuffer ret = new StringBuffer(); final int pre = 1; final int content = 2; final int comment = 3; char sep = '-'; int state = pre; for (;;) { final int ch = read.read(); switch (state) { case pre: if (ch == -1) { log.debug("token=[null]"); return null; } if (Character.isWhitespace((char) ch)) continue; if ('#' == (char) ch) state = comment; else { ret.setLength(0); if ('"' == (char) ch) sep = '"'; else { sep = ' '; ret.append((char) ch); } state = content; } break; case content: final String s0 = ret.toString().trim(); if (ch == -1) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == ' ' && Character.isWhitespace((char) ch)) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == '"' && '"' == (char) ch) { log.debug("token=[" + s0 + "]"); return s0; } if (sep == ' ' && '#' == (char) ch) state = comment; else ret.append((char) ch); break; case comment: final String s = ret.toString().trim(); if (ch == -1) { log.debug("token=[" + s + "]"); return s; } if ('\n' == (char) ch || '\r' == (char) ch) if (s.length() == 0) state = pre; else { log.debug("token=[" + s + "]"); return s; } break; } } }
From source file:org.ppwcode.vernacular.l10n_III.I18nExceptionHelpers.java
/** * Helper method for processTemplate to scan the full pattern, once the beginning of a pattern was found. *///from w ww . j a v a 2s . co m private static String processTemplatePattern(Object context, Locale locale, List<Object> objects, CharacterIterator iterator) throws I18nException { // previous token was "{", scan up to balanced "}" // scan full pattern now StringBuffer patternAcc = new StringBuffer(128); char token = ' '; // initialise with dummy value int balance = 1; while ((balance > 0) && (token != CharacterIterator.DONE)) { token = iterator.next(); patternAcc.append(token); if (token == '{') { balance++; } else if (token == '}') { balance--; } } // done or bad template ?!? if (token == CharacterIterator.DONE) { throw new I18nTemplateException("Bad template pattern", patternAcc.toString()); } // remove last "}" patternAcc.setLength(patternAcc.length() - 1); // prepare pattern, treat the "," for formatting parts int comma = patternAcc.indexOf(","); String pattern = null; String patternPostfix = ""; if (comma == -1) { pattern = patternAcc.toString(); } else if (comma == 0) { throw new I18nTemplateException("Bad template pattern", patternAcc.toString()); } else { pattern = patternAcc.substring(0, comma); patternPostfix = patternAcc.substring(comma, patternAcc.length()); } // process pattern String processedPattern = processPattern(pattern, context, locale, objects); return processedPattern + patternPostfix; }