List of usage examples for java.lang StringBuilder charAt
char charAt(int index);
From source file:com.edgenius.wiki.service.impl.NotificationServiceImpl.java
public List<String> parseReceivers(StringBuilder buf) { int len = buf.length(); List<String> receivers = new ArrayList<String>(); StringBuilder rece = new StringBuilder(); int isReceiver = 0; int idx;/* w ww .java2 s.com*/ for (idx = 0; idx < len; idx++) { char ch = buf.charAt(idx); if (ch == '@' && isReceiver != 2) { rece.append(ch); isReceiver = 1; //expect text or ' continue; } if (isReceiver == 0) { if (ch != ' ') { break; } else { continue; } } if (ch == '\'' && isReceiver > 0) { rece.append(ch); if (isReceiver == 1 && idx > 0 && buf.charAt(idx - 1) == '@') { isReceiver = 2; //expect end ' } else if (isReceiver == 2) { receivers.add(rece.toString()); rece = new StringBuilder(); isReceiver = 0; } continue; } if (ch == ' ' && isReceiver == 1) { receivers.add(rece.toString()); rece = new StringBuilder(); isReceiver = 0; continue; } if (isReceiver > 0) { rece.append(ch); } } if (rece.length() != 0) { //this already means something wrong - no message in text body, only receivers. //however, just put receiver in list and let outside method to process this case receivers.add(rece.toString()); } buf.delete(0, idx); return receivers; }
From source file:com.github.lindenb.jvarkit.tools.backlocate.BackLocate.java
private void backLocate(PrintStream out, KnownGene gene, String geneName, char aa1, char aa2, int peptidePos1) throws IOException { final GeneticCode geneticCode = getGeneticCodeByChromosome(gene.getChromosome()); RNASequence wildRNA = null;/*from w w w. j ava2 s . com*/ ProteinCharSequence wildProt = null; if (genomicSeq == null || !gene.getChromosome().equals(genomicSeq.getChrom())) { LOG.info("fetch genome"); this.genomicSeq = new GenomicSequence(this.indexedFastaSequenceFile, gene.getContig()); } if (gene.isPositiveStrand()) { int exon_index = 0; while (exon_index < gene.getExonCount()) { for (int i = gene.getExonStart(exon_index); i < gene.getExonEnd(exon_index); ++i) { if (i < gene.getCdsStart()) continue; if (i >= gene.getCdsEnd()) break; if (wildRNA == null) { wildRNA = new RNASequence(genomicSeq, '+'); } wildRNA.genomicPositions.add(i); if (wildRNA.length() % 3 == 0 && wildRNA.length() > 0 && wildProt == null) { wildProt = new ProteinCharSequence(geneticCode, wildRNA); } } ++exon_index; } } else // reverse orientation { int exon_index = gene.getExonCount() - 1; while (exon_index >= 0) { for (int i = gene.getExonEnd(exon_index) - 1; i >= gene.getExonStart(exon_index); --i) { if (i >= gene.getCdsEnd()) continue; if (i < gene.getCdsStart()) break; if (wildRNA == null) { wildRNA = new RNASequence(genomicSeq, '-'); } wildRNA.genomicPositions.add(i); if (wildRNA.length() % 3 == 0 && wildRNA.length() > 0 && wildProt == null) { wildProt = new ProteinCharSequence(geneticCode, wildRNA); } } --exon_index; } } //end of if reverse if (wildProt == null) { stderr().println("#no protein found for transcript:" + gene.getName()); return; } int peptideIndex0 = peptidePos1 - 1; if (peptideIndex0 >= wildProt.length()) { out.println("#index out of range for :" + gene.getName() + " petide length=" + wildProt.length()); return; } if (wildProt.charAt(peptideIndex0) != aa1) { out.println("##Warning ref aminod acid for " + gene.getName() + " [" + peptidePos1 + "] is not the same (" + wildProt.charAt(peptideIndex0) + "/" + aa1 + ")"); } else { out.println("##" + gene.getName()); } int indexesInRNA[] = new int[] { 0 + peptideIndex0 * 3, 1 + peptideIndex0 * 3, 2 + peptideIndex0 * 3 }; final String wildCodon = "" + wildRNA.charAt(indexesInRNA[0]) + wildRNA.charAt(indexesInRNA[1]) + wildRNA.charAt(indexesInRNA[2]); /* 2015 : adding possible mut codons */ final Set<String> possibleAltCodons = new HashSet<>(); final char bases[] = new char[] { 'A', 'C', 'G', 'T' }; for (int codon_pos = 0; codon_pos < 3; ++codon_pos) { StringBuilder sb = new StringBuilder(wildCodon); for (char mutBase : bases) { sb.setCharAt(codon_pos, mutBase); if (geneticCode.translate(sb.charAt(0), sb.charAt(1), sb.charAt(2)) == Character.toUpperCase(aa2)) { possibleAltCodons.add(sb.toString()); } } } for (int indexInRna : indexesInRNA) { out.print(geneName); out.print('\t'); out.print(aa1); out.print('\t'); out.print(peptidePos1); out.print('\t'); out.print(aa2); out.print('\t'); out.print(gene.getName()); out.print('\t'); out.print(gene.getStrand() == Strand.NEGATIVE ? "-" : "+"); out.print('\t'); out.print(wildProt.charAt(peptideIndex0)); out.print('\t'); out.print(indexInRna); out.print('\t'); out.print(wildCodon); out.print('\t'); if (possibleAltCodons.isEmpty()) { out.print('.'); } else { boolean first = true; for (String mutCodon : possibleAltCodons) { if (!first) out.print('|'); first = false; out.print(mutCodon); } } out.print('\t'); out.print(wildRNA.charAt(indexInRna)); out.print('\t'); out.print(gene.getChromosome()); out.print('\t'); out.print(wildRNA.genomicPositions.get(indexInRna)); out.print('\t'); String exonName = null; for (KnownGene.Exon exon : gene.getExons()) { int genome = wildRNA.genomicPositions.get(indexInRna); if (exon.getStart() <= genome && genome < exon.getEnd()) { exonName = exon.getName(); break; } } out.print(exonName); if (this.printSequences) { String s = wildRNA.toString(); out.print('\t'); out.print(s.substring(0, indexInRna) + "[" + s.charAt(indexInRna) + "]" + (indexInRna + 1 < s.length() ? s.substring(indexInRna + 1) : "")); s = wildProt.toString(); out.print('\t'); out.print( s.substring(0, peptideIndex0) + "[" + aa1 + "/" + aa2 + "/" + wildProt.charAt(peptideIndex0) + "]" + (peptideIndex0 + 1 < s.length() ? s.substring(peptideIndex0 + 1) : "")); } out.println(); } }
From source file:com.andexert.calendarlistview.library.SimpleMonthView.java
/** * /*from w w w . j a v a2s . c o m*/ * @param canvas */ private void drawMonthTitle(Canvas canvas) { StringBuilder stringBuilder = new StringBuilder(getMonthAndYearString().toLowerCase()); stringBuilder.setCharAt(0, Character.toUpperCase(stringBuilder.charAt(0))); String text = stringBuilder.toString(); Rect rect = new Rect(); mMonthTitlePaint.getTextBounds(text, 0, text.length(), rect); // int x = (mWidth + 2 * mPadding) / 2; int leftPadding = getResources().getDimensionPixelSize(R.dimen.month_day_left_padding); int x = rect.width() / 2 + leftPadding; // int y = (MONTH_HEADER_SIZE - MONTH_DAY_LABEL_TEXT_SIZE) / 2 + (MONTH_LABEL_TEXT_SIZE / 3); int y = (MONTH_HEADER_SIZE - MONTH_DAY_LABEL_TEXT_SIZE) + (MONTH_LABEL_TEXT_SIZE / 4); if (mIsShowMonthDay) { y = MONTH_HEADER_SIZE - MONTH_DAY_LABEL_TEXT_SIZE - (MONTH_LABEL_TEXT_SIZE * 2); } canvas.drawText(text, x, y, mMonthTitlePaint); int linePadding = getResources().getDimensionPixelSize(R.dimen.month_day_line_padding); canvas.drawLine(leftPadding, y + linePadding, rect.width() + leftPadding, y + linePadding, mMonthNumLinePaint); }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private URI createDestinationURI(ServerInfo serverInfo, String path, MessageContext msgContext) { try {/*from w w w . jav a 2 s . c o m*/ if (serverInfo.tokenExpiration == null) { getTokenForServer(serverInfo, msgContext); } StringBuilder sb = new StringBuilder(); sb.append(serverInfo.url.toExternalForm()); if (sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } sb.append(path); String queryString = msgContext.getHttpServletRequest().getQueryString(); String tokenToUse = null; if (serverInfo.encryptedToken != null) { tokenToUse = Crypto.doDecrypt(serverInfo.encryptedToken); } if (!StringUtils.isEmpty(queryString)) { sb.append('?'); if (serverInfo.tokenExpiration == null || System.currentTimeMillis() > serverInfo.tokenExpiration) { getTokenForServer(serverInfo, msgContext); } List<NameValuePair> params = parseQueryStringAndAddToken(queryString, tokenToUse); sb.append(URLEncodedUtils.format(params, "UTF-8")); } else if (tokenToUse != null) { sb.append("?token="); sb.append(tokenToUse); } return new URI(sb.toString()); } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:com.cloudant.sync.datastore.DatastoreImplForceInsertTest.java
@Test public void forceInsert_sameLengthOfPath_remoteRevisionWins() throws Exception { {//from w w w.j a v a 2 s . c om DocumentRevision rev = createDbObject(); datastore.forceInsert(rev, "1-rev", "2-rev", "3-rev", "4-rev"); DocumentRevision insertedObj = datastore.getDocument(OBJECT_ID); insertedObj.setBody(bodyTwo); DocumentRevision updateObj = datastore.updateDocumentFromRevision(insertedObj); insertedObj.setBody(bodyTwo); DocumentRevision updateObj2 = datastore.updateDocumentFromRevision(updateObj); Assert.assertNotNull(updateObj2); assertDBObjectIsCorrect(OBJECT_ID, 6, bodyTwo); } String localRevisionId6 = null; String remoteRevisionId6 = null; { DocumentRevisionTree tree = datastore.getAllRevisionsOfDocument(OBJECT_ID); DocumentRevision current = tree.getCurrentRevision(); List<DocumentRevision> all = tree.getPathForNode(current.getSequence()); // Make sure the latest revision from remote db has bigger String (in terms of String comparison) for (DocumentRevision a : all) { int g = CouchUtils.generationFromRevId(a.getRevision()); if (g == 6) { localRevisionId6 = a.getRevision(); StringBuilder sb = new StringBuilder(localRevisionId6); sb.setCharAt(2, (char) (sb.charAt(2) + 1)); remoteRevisionId6 = sb.toString(); } } Assert.assertNotNull(localRevisionId6); Assert.assertNotNull(remoteRevisionId6); DocumentRevisionBuilder builder = new DocumentRevisionBuilder(); builder.setDocId(OBJECT_ID); builder.setRevId(remoteRevisionId6); builder.setDeleted(false); builder.setBody(bodyOne); DocumentRevision newRev = builder.build(); datastore.forceInsert(newRev, "1-rev", "2-rev", "3-rev", "4-rev", "5-rev", remoteRevisionId6); } DocumentRevision obj = datastore.getDocument(OBJECT_ID); Assert.assertEquals(remoteRevisionId6, obj.getRevision()); Assert.assertTrue(Arrays.equals(bodyOne.asBytes(), obj.getBody().asBytes())); }
From source file:com.cloudant.sync.datastore.DatastoreImplForceInsertTest.java
@Test public void forceInsert_sameLengthOfPath_localRevisionWins() throws Exception { {/* w w w .ja va 2 s .c o m*/ DocumentRevision rev = createDbObject(); datastore.forceInsert(rev, "1-rev", "2-rev", "3-rev", "4-rev"); DocumentRevision insertedObj = datastore.getDocument(OBJECT_ID); insertedObj.setBody(bodyTwo); DocumentRevision updateObj = datastore.updateDocumentFromRevision(insertedObj); insertedObj.setBody(bodyTwo); DocumentRevision updateObj2 = datastore.updateDocumentFromRevision(updateObj); Assert.assertNotNull(updateObj2); assertDBObjectIsCorrect(OBJECT_ID, 6, bodyTwo); } String localRevisionId6 = null; String remoteRevisionId6 = null; { // Make sure the latest revision from remote db has smaller String (in terms of String comparison) DocumentRevisionTree tree = datastore.getAllRevisionsOfDocument(OBJECT_ID); DocumentRevision current = tree.getCurrentRevision(); List<DocumentRevision> all = tree.getPathForNode(current.getSequence()); for (DocumentRevision a : all) { int g = CouchUtils.generationFromRevId(a.getRevision()); if (g == 6) { localRevisionId6 = a.getRevision(); StringBuilder sb = new StringBuilder(localRevisionId6); sb.setCharAt(2, (char) (sb.charAt(2) - 1)); remoteRevisionId6 = sb.toString(); } } Assert.assertNotNull(localRevisionId6); Assert.assertNotNull(remoteRevisionId6); DocumentRevisionBuilder builder = new DocumentRevisionBuilder(); builder.setDocId(OBJECT_ID); builder.setRevId(remoteRevisionId6); builder.setDeleted(false); builder.setBody(bodyOne); DocumentRevision newRev = builder.build(); datastore.forceInsert(newRev, "1-rev", "2-rev", "3-rev", "4-rev", "5-rev", remoteRevisionId6); } DocumentRevision obj = datastore.getDocument(OBJECT_ID); Assert.assertEquals(localRevisionId6, obj.getRevision()); Assert.assertTrue(Arrays.equals(bodyTwo.asBytes(), obj.getBody().asBytes())); }
From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java
private ArchiveEntries createArchiveEntries(final File sourceDirectory, final String pathPrefix) throws IOException { final ArchiveEntries archiveEntries = new ArchiveEntries(); final Path sourcePath = Paths.get(sourceDirectory.toURI()); final StringBuilder normalizedPathPrefix = new StringBuilder(); if (null != pathPrefix && !pathPrefix.isEmpty()) { normalizedPathPrefix.append(pathPrefix.replace("\\", "/")); if (normalizedPathPrefix.charAt(normalizedPathPrefix.length() - 1) != '/') { normalizedPathPrefix.append('/'); }// w w w . j av a 2 s . co m } Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(dir); String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; if (!normalizedPath.isEmpty()) { if (!normalizedPath.endsWith("/")) { normalizedPath += "/"; } archiveEntries.dirs.add(normalizedPath.replace("\\", "/")); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { final Path relativeSourcePath = sourcePath.relativize(file); final String normalizedPath = normalizedPathPrefix.toString() + relativeSourcePath; final byte[] md5Digest = getMd5Digest(Files.newInputStream(file), true); archiveEntries.files.put(normalizedPath.replace("\\", "/"), md5Digest); return FileVisitResult.CONTINUE; } }); return archiveEntries; }
From source file:mml.handler.get.MMLGetMMLHandler.java
/** * Count the numebr of newlines at the end of the MML text being built * @param sb the mml text// w w w . j a v a2s . c om * @return the number of terminal NLs */ int countTerminalNLs(StringBuilder sb) { int nNLs = 0; for (int i = sb.length() - 1; i > 0; i--) { if (sb.charAt(i) == '\n') nNLs++; else break; } return nNLs; }
From source file:gool.generator.common.CommonCodeGenerator.java
/** * <pre>//from www. j av a 2s .com * Produce indented code in a manner similar to printf but with custom conversions. * %% a single "%" * %s Print an argument as a string, without indentation or newlines added. * Similar to the corresponding flag of <i>String.format</i>. * %<i>n</i> (where <i>n</i> is a digit) * Print an argument as a bloc indented <i>n</i> times from the current indentation level. * Newlines are inserted before and after the bloc. * %-<i>n</i> (where <i>n</i> is a digit) * <i>n</i> times the indentation string, does not consumes a argument. * %-0 becomes a empty string (it does nothing but is still parsed) * * @param format * the format string * @param arguments * the objects to format, each one corresponding to a % code * @return the formated string */ protected String formatIndented(String format, Object... arguments) { StringBuilder sb = new StringBuilder(format); int pos = sb.indexOf("%"); int arg = 0; while (pos != -1) { if (sb.charAt(pos + 1) == '%') { sb = sb.replace(pos, pos + 2, "%"); } else if (sb.charAt(pos + 1) == 's') { sb = sb.replace(pos, pos + 2, arguments[arg].toString()); pos += arguments[arg].toString().length() - 1; arg++; } else if (Character.isDigit(sb.charAt(pos + 1))) { String replacement = ("\n" + arguments[arg].toString().replaceFirst("\\s*\\z", "")).replace("\n", "\n" + StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 1), 10))) + "\n"; sb = sb.replace(pos, pos + 2, replacement); pos += replacement.length() - 1; arg++; } else if (sb.charAt(pos + 1) == '-' && Character.isDigit(sb.charAt(pos + 2))) { String replacement = StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 2), 10)); sb = sb.replace(pos, pos + 3, replacement); pos += replacement.length(); } pos = sb.indexOf("%", pos); } return sb.toString(); }
From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java
private TemporaryMedia getInformation(StringBuilder mySb) { TemporaryMedia returnMedia = new TemporaryMedia(); StringBuilder wordSb = new StringBuilder(); int tmpYear;/*from w w w. j a va 2 s. c o m*/ int year = -1; int thisYear = Calendar.getInstance().get(Calendar.YEAR); boolean deleteYear = false; boolean finalWord = true; for (int i = 0; i < mySb.length(); i++) { if (mySb.charAt(i) == '.' || mySb.charAt(i) == ' ' || mySb.charAt(i) == '-' || mySb.charAt(i) == '_') { if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) { mySb.delete(i - (wordSb.length() + 1), mySb.length()); finalWord = false; // final useful word found. No point in continuing. break; } mySb.replace(i, i + 1, " "); tmpYear = checkForYear(wordSb); if (tmpYear > 1900 && tmpYear <= thisYear) { year = tmpYear; deleteYear = true; } wordSb.setLength(0); } else if (wordSb.length() == 0 && (mySb.charAt(i) == 'S' || mySb.charAt(i) == 's' || Character.isDigit(mySb.charAt(i)))) { // See if new word contains series and episode information. StringBuilder whatsLeft = new StringBuilder(mySb.subSequence(i, mySb.length())); if (getEpisodePotential(whatsLeft)) { TemporaryMedia tmpMedia = getEpisodeInfo(whatsLeft); returnMedia.setIsMovie(false); returnMedia.setSeason(tmpMedia.getSeason()); returnMedia.setEpisode(tmpMedia.getEpisode()); mySb.delete(i, mySb.length()); // series and episode information saved. No point in continuing. break; } else { wordSb.append(mySb.charAt(i)); } } else if (mySb.charAt(i) == '[' || mySb.charAt(i) == '(') { // Brackets shoudl usually be removed. They could possibly contain realease year. if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) { mySb.delete(i - (wordSb.length() + 1), mySb.length()); finalWord = false; // final useful word found. No point in continuing. break; } tmpYear = checkForYear(wordSb); if (tmpYear > 1900 && tmpYear <= thisYear) { year = tmpYear; deleteYear = true; } wordSb.setLength(0); if (mySb.charAt(i) == '[') { tmpYear = removeUntil(mySb, i, ']'); } else if (mySb.charAt(i) == '(') { tmpYear = removeUntil(mySb, i, ')'); } if (tmpYear > 1900 && tmpYear <= thisYear) { year = tmpYear; deleteYear = false; } i--; // Need to compensate for removing bracket. } else { // Nothing useful here. Save the char and continue. wordSb.append(mySb.charAt(i)); } } if (finalWord && Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) { mySb.delete(mySb.length() - wordSb.length(), mySb.length()); } else { tmpYear = checkForYear(wordSb); if (tmpYear > 1900 && tmpYear <= thisYear) { year = tmpYear; deleteYear = true; } } if (deleteYear && returnMedia.IsMovie()) { int i = mySb.lastIndexOf(year + ""); mySb.delete(i, i + 4); } returnMedia.setYear(year); returnMedia.setName(mySb.toString().trim()); return returnMedia; }