private static String fourDigits2Chinese(String digit) { int value = Integer.parseInt(digit); boolean hasZero = false; StringBuilder chineseDigit = new StringBuilder(); int exponent = 3; for (; exponent >= 0; exponent--) { int divisor = (int) Math.pow(10, exponent); int result = value / divisor; if (result != 0) { chineseDigit.append(TOBIG[result]); chineseDigit.append(FOUR_DIGIT_UNIT[exponent]); hasZero = false; } else if (result == 0 && !hasZero) { chineseDigit.append(TOBIG[0]); hasZero = true; } value %= divisor; } // Delete redundant zero at head if (chineseDigit.toString().startsWith("零")) { chineseDigit.deleteCharAt(0); } // Delete redundant zero at tail if (chineseDigit.toString().endsWith("零")) { return chineseDigit.deleteCharAt(chineseDigit.length() - 1).toString(); } else { return chineseDigit.toString(); } }
/** * Configures the basic escapes based on the configured options. * * @param options Options that will affect what is escaped. */ private void setupEscapes(Options options) { escapes = new ArrayList<Escape>(); // confusingly, this replaces single backslashes with double backslashes. // Man, I miss Groovy's slashy strings in these moments... escapes.add(new Escape("\\\\", "\\\\\\\\")); // creates an set of characters that are universally escaped. // these characters are wrapped in \Q...\E to ensure they aren't treated as special characters. StringBuilder chars = new StringBuilder("([\\Q`*_{}[]#"); if (options.tables.isConvertedToText() && !options.tables.isRenderedAsCode()) { chars.append('|'); } chars.append("\\E])"); escapes.add(new Escape(chars.toString(), "\\\\$1")); // finally, escape certain characters only if they are leading characters StringBuilder leadingChars = new StringBuilder("^( ?+)([\\Q-+"); if (options.definitionLists) { leadingChars.append(':'); } leadingChars.append("\\E])"); escapes.add(new Escape(leadingChars.toString(), "$1\\\\$2")); // setup the leading character reverser // this is a bit of a hack to undo leading character escapes. unescapeLeadingChars = Pattern.compile(leadingChars.insert(6, "\\\\").toString()); }
@LargeTest public void testManyRowsTxtLong() throws Exception { mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, txt TEXT, data INT);"); Random random = new Random(System.currentTimeMillis()); StringBuilder randomString = new StringBuilder(1979); for (int i = 0; i < 1979; i++) { randomString.append((random.nextInt() & 0xf) % 10); } // if cursor window size changed, adjust this value too final int count = 600; for (int i = 0; i < count; i++) { StringBuilder sql = new StringBuilder(2100); sql.append("INSERT INTO test (txt, data) VALUES ('"); sql.append(randomString); sql.append("','"); sql.append(i); sql.append("');"); mDatabase.execSQL(sql.toString()); } Cursor c = mDatabase.query("test", new String[] {"txt", "data"}, null, null, null, null, null); assertNotNull(c); int i = 0; while (c.moveToNext()) { assertEquals(randomString.toString(), c.getString(0)); assertEquals(i, c.getInt(1)); i++; } assertEquals(count, i); assertEquals(count, c.getCount()); c.close(); }
/** * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf"); * No special handling implemented for escaped (\") quotes. */ private static StringList breakCommas(String contents) { StringList outgoing = new StringList(); boolean insideQuote = false; // The current word being read StringBuilder current = new StringBuilder(); char[] chars = contents.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (insideQuote) { current.append(c); if (c == '\"') { insideQuote = false; } } else { if (c == ',') { if (current.length() != 0) { outgoing.append(current.toString()); current.setLength(0); } } else { current.append(c); if (c == '\"') { insideQuote = true; } } } } if (current.length() != 0) { outgoing.append(current.toString()); } return outgoing; }
/** * Given a string, return an array of tokens. The separator can be escaped with the '\' character. * The '\' character may also be escaped by the '\' character. * * @param s the string to tokenize. * @param separator the separator char. * @param maxTokens the maxmimum number of tokens returned. If the max is reached, the remaining * part of s is appended to the end of the last token. * @return an array of tokens. */ public static String[] tokenize(String s, char separator, int maxTokens) { List tokens = new ArrayList(); StringBuilder token = new StringBuilder(); boolean prevIsEscapeChar = false; for (int i = 0; i < s.length(); i += Character.charCount(i)) { int currentChar = s.codePointAt(i); if (prevIsEscapeChar) { // Case 1: escaped character token.appendCodePoint(currentChar); prevIsEscapeChar = false; } else if (currentChar == separator && tokens.size() < maxTokens - 1) { // Case 2: separator tokens.add(token.toString()); token = new StringBuilder(); } else if (currentChar == '\\') { // Case 3: escape character prevIsEscapeChar = true; } else { // Case 4: regular character token.appendCodePoint(currentChar); } } if (token.length() > 0) { tokens.add(token.toString()); } return (String[]) tokens.toArray(new String[] {}); }
@MediumTest public void testLargeField() throws Exception { mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);"); StringBuilder sql = new StringBuilder(2100); sql.append("INSERT INTO test (data) VALUES ('"); Random random = new Random(System.currentTimeMillis()); StringBuilder randomString = new StringBuilder(1979); for (int i = 0; i < 1979; i++) { randomString.append((random.nextInt() & 0xf) % 10); } sql.append(randomString); sql.append("');"); mDatabase.execSQL(sql.toString()); Cursor c = mDatabase.query("test", null, null, null, null, null, null); assertNotNull(c); assertEquals(1, c.getCount()); assertTrue(c.moveToFirst()); assertEquals(0, c.getPosition()); String largeString = c.getString(c.getColumnIndexOrThrow("data")); assertNotNull(largeString); assertEquals(randomString.toString(), largeString); c.close(); }
public void addSetterComment(Method method, FullyQualifiedTable table, String columnName) { StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); // $NON-NLS-1$ method.addJavaDocLine(" * This method was generated by Apache iBATIS ibator."); // $NON-NLS-1$ sb.append(" * This method sets the value of the database column "); // $NON-NLS-1$ sb.append(table); sb.append('.'); sb.append(columnName); method.addJavaDocLine(sb.toString()); method.addJavaDocLine(" *"); // $NON-NLS-1$ Parameter parm = method.getParameters().get(0); sb.setLength(0); sb.append(" * @param "); // $NON-NLS-1$ sb.append(parm.getName()); sb.append(" the value for "); // $NON-NLS-1$ sb.append(table); sb.append('.'); sb.append(columnName); method.addJavaDocLine(sb.toString()); addIbatorJavadocTag(method); method.addJavaDocLine(" */"); // $NON-NLS-1$ }
private String urlEncodeQueryParams(String url) { final StringBuilder sb = new StringBuilder((int) (url.length() * 1.2)); final int pos = url.indexOf('?'); if (pos > 0) { // split url into base and query expression final String queryExpr = url.substring(pos + 1); LOG.trace("queryExpr {}", queryExpr); final Pattern p = Pattern.compile( "\\G([A-Za-z0-9-_]+)=([A-Za-z0-9-+:#|^\\.,<>;%*\\(\\)_/\\[\\]\\{\\}\\\\ ]+)[&]?"); final Matcher m = p.matcher(queryExpr); while (m.find()) { LOG.trace("group 1: {} group 2: {}", m.group(1), m.group(2)); if (sb.length() > 0) { sb.append("&"); } sb.append(m.group(1)); sb.append("="); try { // URL Encode the value of each query parameter sb.append(URLEncoder.encode(m.group(2), "UTF-8")); } catch (UnsupportedEncodingException e) { // Ignore - We know UTF-8 is supported } } LOG.trace("new query Expr: {}", sb.toString()); sb.insert(0, url.substring(0, pos + 1)); } return sb.toString(); }
public void addGetterComment(Method method, FullyQualifiedTable table, String columnName) { StringBuilder sb = new StringBuilder(); method.addJavaDocLine("/**"); // $NON-NLS-1$ method.addJavaDocLine(" * This method was generated by Apache iBATIS ibator."); // $NON-NLS-1$ sb.append(" * This method returns the value of the database column "); // $NON-NLS-1$ sb.append(table); sb.append('.'); sb.append(columnName); method.addJavaDocLine(sb.toString()); method.addJavaDocLine(" *"); // $NON-NLS-1$ sb.setLength(0); sb.append(" * @return the value of "); // $NON-NLS-1$ sb.append(table); sb.append('.'); sb.append(columnName); method.addJavaDocLine(sb.toString()); addIbatorJavadocTag(method); method.addJavaDocLine(" */"); // $NON-NLS-1$ }
@Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("title") && sect) { section.setTitle(ch_str.toString()); ch_str = new StringBuilder(64); } else if (qName.equalsIgnoreCase("section")) { section.setDescription(ch_str.toString()); book.add(new Chapter(section.getTitle(), section.getDescription())); ch_str = new StringBuilder(64); } else if (descript) { if (qName.equalsIgnoreCase("annotation")) { book.setAnnotation(ch_str.toString() + ""); ch_str = new StringBuilder(64); } if (qName.equalsIgnoreCase("author")) { book.authors.add(authors); authors = new Author(); } } ElementName = ""; }
public static void assertNoLiferayExceptions() throws Exception { if (!_liferayExceptions.isEmpty()) { StringBuilder sb = new StringBuilder(); sb.append(_liferayExceptions.size()); sb.append(" Liferay Exception"); if (_liferayExceptions.size() > 1) { sb.append("s were"); } else { sb.append(" was"); } sb.append(" thrown"); System.out.println(); System.out.println("##"); System.out.println("## " + sb.toString()); System.out.println("##"); for (int i = 0; i < _liferayExceptions.size(); i++) { Exception liferayException = _liferayExceptions.get(i); System.out.println(); System.out.println("##"); System.out.println("## Liferay Exception #" + (i + 1)); System.out.println("##"); System.out.println(); System.out.println(liferayException.getMessage()); System.out.println(); } throw new Exception(sb.toString()); } }
public DNIHandler(String dni) throws MalformedHandlerException { boolean correct = true; StringBuilder error = new StringBuilder(); if (dni == null) { error.append("The dni can't be null"); throw new MalformedHandlerException("Bad DNI: ".concat(error.toString())); } else if (dni.length() < 2) { correct = false; error.append("The DNI must have at least one number and the letter"); } else { Integer dniNumber = Integer.parseInt(dni.substring(0, dni.length() - 1)); Character letterDni = dni.charAt(dni.length() - 1); if (DniLetters.getInstance().isDniValid(dniNumber, letterDni)) { this.dni = dniNumber; this.letter = letterDni; } } if (!correct) { throw new MalformedHandlerException("Bad DNI: ".concat(error.toString())); } }
static DecoderResult decode(byte[] bytes, int mode) { StringBuilder result = new StringBuilder(144); switch (mode) { case 2: case 3: String postcode; if (mode == 2) { int pc = getPostCode2(bytes); NumberFormat df = new DecimalFormat("0000000000".substring(0, getPostCode2Length(bytes))); postcode = df.format(pc); } else { postcode = getPostCode3(bytes); } String country = THREE_DIGITS.format(getCountry(bytes)); String service = THREE_DIGITS.format(getServiceClass(bytes)); result.append(getMessage(bytes, 10, 84)); if (result.toString().startsWith("[)>" + RS + "01" + GS)) { result.insert(9, postcode + GS + country + GS + service + GS); } else { result.insert(0, postcode + GS + country + GS + service + GS); } break; case 4: result.append(getMessage(bytes, 1, 93)); break; case 5: result.append(getMessage(bytes, 1, 77)); break; } return new DecoderResult(bytes, result.toString(), null, String.valueOf(mode)); }
public Weather1(String cityName) throws IOException { this.cityName = cityName; // 解析本机ip地址 URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi?city=" + cityName); urlConnection = url.openConnection(); urlConnection.setConnectTimeout(1000); try { bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.forName("GBK"))); stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(new String(line.getBytes("GBK"), "UTF-8")); } System.out.println(stringBuilder.toString()); // 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。 Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); int c; while ((c = reader.read()) != -1) { System.out.print((char) c); } reader.close(); } catch (SocketTimeoutException e) { System.out.println("连接超时"); } catch (FileNotFoundException e) { System.out.printf("加载文件出错"); } String datas = stringBuilder.toString(); }
public Weather1() throws IOException { // 解析本机ip地址 URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi?city=%E5%8D%97%E4%BA%AC"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(1000); try { bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } System.out.println(stringBuilder.toString()); // 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。 Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); int c; while ((c = reader.read()) != -1) { System.out.print((char) c); } reader.close(); } catch (SocketTimeoutException e) { System.out.println("连接超时"); } catch (FileNotFoundException e) { System.out.printf("加载文件出错"); } String datas = stringBuilder.toString(); }
public static URI getAuthorizationUrl( URI loginServer, String clientId, String callbackUrl, String[] scopes, String clientSecret, String displayType) { if (displayType == null) displayType = "touch"; final StringBuilder sb = new StringBuilder(loginServer.toString()); sb.append(OAUTH_AUTH_PATH); sb.append(displayType); if (clientSecret != null) { sb.append("&").append(RESPONSE_TYPE).append("=").append(ACTIVATED_CLIENT_CODE); } else { sb.append("&").append(RESPONSE_TYPE).append("=").append(TOKEN); } sb.append("&").append(CLIENT_ID).append("=").append(Uri.encode(clientId)); if ((null != scopes) && (scopes.length > 0)) { // need to always have the refresh_token scope to reuse our refresh token sb.append("&").append(SCOPE).append("=").append(REFRESH_TOKEN); StringBuilder scopeStr = new StringBuilder(); for (String scope : scopes) { if (!scope.equalsIgnoreCase(REFRESH_TOKEN)) { scopeStr.append(" ").append(scope); } } String safeScopeStr = Uri.encode(scopeStr.toString()); sb.append(safeScopeStr); } sb.append("&redirect_uri="); sb.append(callbackUrl); return URI.create(sb.toString()); }
/** Returns I2G representation of construction. Intergeo File Format. (Yves Kreis) */ public String getFullI2G() { StringBuilder sb = new StringBuilder(); // addXMLHeader(sb); sb.append( "<!--\n\tIntergeo File Format Version " + GeoGebra.I2G_FILE_FORMAT + "\n\twritten by " + app.getPlain("ApplicationName") + " " + GeoGebra.VERSION_STRING + " (" + GeoGebra.BUILD_DATE + ")\n-->\n"); sb.append("<construction>\n"); // save construction cons.getConstructionI2G(sb, Construction.CONSTRUCTION); StringBuilder display = new StringBuilder(); cons.getConstructionI2G(display, Construction.DISPLAY); if (!display.toString().equals("")) { sb.append("\t<display>\n"); sb.append(display.toString()); sb.append("\t</display>\n"); } sb.append("</construction>\n"); return sb.toString(); }
@PUT @Consumes(MediaType.APPLICATION_JSON) public Response addUpdateListItem(InputStream incomingData) { StringBuilder listBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); String line = null; while ((line = in.readLine()) != null) { listBuilder.append(line); } } catch (Exception e) { System.out.println("Error Parsing :- "); } try { JSONObject json = new JSONObject(listBuilder.toString()); Iterator<String> iterator = json.keys(); ListItem item = new ListItem( (String) json.get(iterator.next()), (String) json.get(iterator.next()), Boolean.parseBoolean((String) json.get(iterator.next()))); int index = list.indexOf(item); item = list.get(index); list.remove(index); item.setTitle((String) json.get(iterator.next())); item.setBody((String) json.get(iterator.next())); list.add(index, item); } catch (JSONException e) { e.printStackTrace(); } // return HTTP response 200 in case of success return Response.status(200).entity(listBuilder.toString()).build(); }
@POST @Consumes(MediaType.APPLICATION_JSON) public Response saveListItem(InputStream incomingData) { StringBuilder listBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); String line = null; while ((line = in.readLine()) != null) { listBuilder.append(line); } } catch (Exception e) { System.out.println("Error Parsing: - "); } try { JSONObject json = new JSONObject(listBuilder.toString()); Iterator<String> iterator = json.keys(); if (list == null) { list = new ArrayList<ListItem>(); } ListItem item = new ListItem( (String) json.get(iterator.next()), (String) json.get(iterator.next()), (Boolean) json.get(iterator.next())); list.add(item); } catch (JSONException e) { e.printStackTrace(); return Response.status(500).entity(listBuilder.toString()).build(); } // return HTTP response 200 in case of success return Response.status(200).entity(listBuilder.toString()).build(); }
/** * beat 14.61% * * @param num * @return */ public static String numberToWords(int num) { if (num == 0) return "Zero"; StringBuilder sb = new StringBuilder(); List<String> list = new LinkedList<>(); int con = 0; while (num != 0) { int remainder = num % 1000; num /= 1000; sb = new StringBuilder(); if (remainder != 0) { sb.append(helper(remainder)); if (con == 1) sb.append("Thousand "); if (con == 2) sb.append("Million "); if (con == 3) sb.append("Billion "); } list.add(0, sb.toString()); con++; } sb = new StringBuilder(); for (String str : list) { sb.append(str); } return sb.toString().trim(); }
public boolean update(final Article article) { Timestamp time = new Timestamp(System.currentTimeMillis()); StringBuilder sf = new StringBuilder("update "); sf.append(tableName).append(" set "); if (notEmpty(article.getTitle())) { sf.append(" title=").append(article.getTitle()).append(","); } if (notEmpty(article.getContent())) { sf.append(" content=").append(article.getContent()).append(","); } if (notEmpty(article.getCategory())) { sf.append(" category=").append(article.getCategory()).append(","); } if (notEmpty(article.getAuthorId())) { sf.append(" authorId=").append(article.getAuthorId()).append(","); } if (notEmpty(article.getEditorId())) { sf.append(" editorId=").append(article.getEditorId()).append(","); } if (notEmpty(article.getMediaId())) { sf.append(" mediaId=").append(article.getMediaId()).append(","); } sf.append(" uptime=").append(time.toString()).append(" where id=").append(article.getId()); logger.info(sf.toString()); int ret = jdbcTemplateWrite.update(sf.toString()); return ret > 0; }
@Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (localName.equals("item")) { stories.add(story); story = null; largestImgWidth = 0; } if (story != null) { if (localName.equals("title")) { story.setTitle(xmlInnerText.toString().trim()); } else if (localName.equals("description")) { story.setDescription(xmlInnerText.toString().trim()); } else if (localName.equals("link")) { story.setLink(xmlInnerText.toString().trim()); } else if (localName.equals("pubDate")) { SimpleDateFormat dtSourceFormat = story.getSourceDateFormater(); SimpleDateFormat dtTargetFormat = story.getTargetDateFormater(); try { story.setPubDate(dtSourceFormat.parse(xmlInnerText.toString().trim())); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("Exam01", "Parsed date : " + dtTargetFormat.format(story.getPubDate())); } xmlInnerText.setLength(0); } }
public void attachFile( String space, String page, String name, InputStream is, boolean failIfExists) throws Exception { // make sure xwiki.Import exists if (!pageExists(space, page)) { createPage(space, page, null, null); } StringBuilder url = new StringBuilder(BASE_REST_URL); url.append("wikis/xwiki/spaces/"); url.append(escapeURL(space)); url.append("/pages/"); url.append(escapeURL(page)); url.append("/attachments/"); url.append(escapeURL(name)); if (failIfExists) { executePut( url.toString(), is, MediaType.APPLICATION_OCTET_STREAM, Status.CREATED.getStatusCode()); } else { executePut( url.toString(), is, MediaType.APPLICATION_OCTET_STREAM, Status.CREATED.getStatusCode(), Status.ACCEPTED.getStatusCode()); } }
/** * Reads the response, throws a BuildException if the response indicates an error. * * @param in the input stream to use * @throws IOException on I/O error * @throws BuildException on other errors */ protected void waitForAck(InputStream in) throws IOException { int b = in.read(); // b may be 0 for success, // 1 for error, // 2 for fatal error, if (b == -1) { // didn't receive any response throw new SSHException("No response from server"); } else if (b != 0) { StringBuilder sb = new StringBuilder(); int c = in.read(); while (c > 0 && c != '\n') { sb.append((char) c); c = in.read(); } if (b == 1) { throw new SSHException("server indicated an error: " + sb.toString()); } else if (b == 2) { throw new SSHException("server indicated a fatal error: " + sb.toString()); } else { throw new SSHException("unknown response, code " + b + " message: " + sb.toString()); } } }
@Override public void pushToDB(Connection con) { Statement stmt; try { stmt = con.createStatement(); StringBuilder sqlString = new StringBuilder("INSERT INTO question_response VALUES(null,"); sqlString.append(statement); sqlString.append("\",\" "); for (String string : answers) { sqlString.append(string); sqlString.append(" &&& "); } sqlString.replace(sqlString.length() - 5, sqlString.length(), ""); sqlString.append("\" "); System.out.print(sqlString.toString()); ResultSet resultSet = stmt.executeQuery(sqlString.toString()); stmt = con.createStatement(); sqlString = new StringBuilder("SELECT * FROM question_response WHERE statement=\""); sqlString.append(statement); sqlString.append("\" "); System.out.print(sqlString.toString()); resultSet = stmt.executeQuery(sqlString.toString()); while (resultSet.next()) { this.setqID(resultSet.getInt("question_id")); // will always be the last one } } catch (Exception e) { } }
public WorkerSumm(WorkerSummary workerSummary) { this.port = String.valueOf(workerSummary.get_port()); this.topology = workerSummary.get_topology(); StringBuilder taskSB = new StringBuilder(); StringBuilder componentSB = new StringBuilder(); boolean isFirst = true; int minUptime = 0; taskSummList = workerSummary.get_tasks(); for (TaskSummary taskSummary : taskSummList) { if (isFirst == false) { taskSB.append(','); componentSB.append(','); } else { minUptime = taskSummary.get_uptime_secs(); } taskSB.append(taskSummary.get_task_id()); componentSB.append(taskSummary.get_component_id()); if (minUptime < taskSummary.get_uptime_secs()) { minUptime = taskSummary.get_uptime_secs(); } isFirst = false; } this.uptime = StatBuckets.prettyUptimeStr(minUptime); this.tasks = taskSB.toString(); this.components = componentSB.toString(); }
private String readString() throws IOException { StringBuilder line = new StringBuilder(); // synchronized (processOut) { while (true) { String subline = processOut.readLine(); if (subline == null) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Pipe to subprocess seems to be broken!"); if (line.length() == 0) { errorMessage.append(" No output read.\n"); } else { errorMessage.append(" Currently read output: " + line.toString() + "\n"); } errorMessage.append("Shell Process Exception:\n"); errorMessage.append(getErrorsString() + "\n"); throw new RuntimeException(errorMessage.toString()); } if (subline.equals("end")) { break; } if (line.length() != 0) { line.append("\n"); } line.append(subline); } // } return line.toString(); }
public void testClass() { SVCorePlugin.getDefault().enableDebug(false); BundleUtils utils = new BundleUtils(SVCoreTestsPlugin.getDefault().getBundle()); ByteArrayOutputStream bos; bos = utils.readBundleFile("/indent/class1.svh"); String ref = bos.toString(); StringBuilder sb = removeLeadingWS(ref); // Run the indenter over the reference source SVIndentScanner scanner = new SVIndentScanner(new StringTextScanner(sb)); ISVIndenter indenter = SVCorePlugin.getDefault().createIndenter(); indenter.init(scanner); indenter.setTestMode(true); StringBuilder result = new StringBuilder(indenter.indent(-1, -1)); fLog.debug("Reference:\n" + ref); fLog.debug("==="); fLog.debug("Result:\n" + result.toString()); IndentComparator.compare("testClass", ref, result.toString()); }
public static void createBatterylow(Context context) { VibratePattern vibratePattern = createVibratePatternFromPreference(context, "settingsBatteryNumberBuzzes"); StringBuilder builder = new StringBuilder(); builder.append(Monitors.BatteryData.level); builder.append("%"); String description = "Battery low"; Bitmap icon = Utils.getBitmap(context, "batterylow.bmp"); if (MetaWatchService.watchType == WatchType.DIGITAL) { Bitmap bitmap = smartLines( context, icon, "Battery", new String[] {"Phone battery at", builder.toString()}); Notification.addBitmapNotification( context, bitmap, vibratePattern, Notification.getDefaultNotificationTimeout(context), description); } else { Notification.addOledNotification( context, Protocol.createOled1line(context, icon, "Warning!"), Protocol.createOled2lines(context, "Phone battery at", builder.toString()), null, 0, vibratePattern, description); } }
/** * Deletes all Results and ResultSets of a test, selftest or survey * * @param olatRes * @param olatResDet * @param repRef * @return deleted ResultSets */ public int deleteAllResults(Long olatRes, String olatResDet, Long repRef) { StringBuilder sb = new StringBuilder(); sb.append("select rset from ").append(QTIResultSet.class.getName()).append(" as rset "); sb.append( " where rset.olatResource=:resId and rset.olatResourceDetail=:resSubPath and rset.repositoryRef=:repoKey "); EntityManager em = dbInstance.getCurrentEntityManager(); List<QTIResultSet> sets = em.createQuery(sb.toString(), QTIResultSet.class) .setParameter("resId", olatRes) .setParameter("resSubPath", olatResDet) .setParameter("repoKey", repRef) .getResultList(); StringBuilder delSb = new StringBuilder(); delSb .append("delete from ") .append(QTIResult.class.getName()) .append(" as res where res.resultSet.key=:setKey"); Query delResults = em.createQuery(delSb.toString()); for (QTIResultSet set : sets) { delResults.setParameter("setKey", set.getKey()).executeUpdate(); em.remove(set); } return sets.size(); }