List of usage examples for java.util.regex Matcher end
public int end()
From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java
@Override public void replaceOrderBy(boolean desc, String... properties) { Matcher entityMatcher = FROM_ENTITY_PATTERN.matcher(buffer); String alias = findAlias(entityMatcher); Matcher orderByMatcher = ORDER_BY_PATTERN.matcher(buffer); if (orderByMatcher.find()) { buffer.replace(orderByMatcher.end(), buffer.length(), ""); } else {//from w w w . java 2 s.co m buffer.append(" order by"); } String separator = " "; for (String property : properties) { int dotPos = property.lastIndexOf("."); if (dotPos > -1) { String path = property.substring(0, dotPos); String joinedAlias = alias + "_" + path.replace(".", "_"); if (buffer.indexOf(" " + joinedAlias) == -1) { String join = "left join " + alias + "." + path + " " + joinedAlias; addJoinAsIs(join); } String orderBy = joinedAlias + "." + property.substring(dotPos + 1) + (desc ? " desc" : ""); buffer.append(separator).append(orderBy); } else { String orderBy = alias + "." + property + (desc ? " desc" : ""); buffer.append(separator).append(orderBy); } separator = ", "; } }
From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java
/** * Percent-encode a parameter for construction of the base string and the Authorization header, * as specified in http://tools.ietf.org/html/rfc5849#section-3.6 * /* ww w .j a v a2 s.c o m*/ * @param p Unencoded string * @return Encoded text */ private String encodeParameter(String p) { String encoded = URLEncoder.encodeUriComponent(p); StringBuffer sb = new StringBuffer(encoded.length()); Pattern pattern = Pattern.compile("%[0-9a-f]{2}"); Matcher m = pattern.matcher(encoded); int lastEnd = 0; while (m.find()) { sb.append(encoded.substring(lastEnd, m.start())).append(m.group().toUpperCase(Locale.ENGLISH)); lastEnd = m.end(); } sb.append(encoded.substring(lastEnd)); return sb.toString().replaceAll("!", "%21").replaceAll("\\(", "%28").replaceAll("\\)", "%29") .replaceAll("\\*", "%2A"); }
From source file:PropertiesHelper.java
/** * Adds new properties to an existing set of properties while * substituting variables. This function will allow value * substitutions based on other property values. Value substitutions * may not be nested. A value substitution will be ${property.key}, * where the dollar-brace and close-brace are being stripped before * looking up the value to replace it with. Note that the ${..} * combination must be escaped from the shell. * * @param b is the set of properties to add to existing properties. * @return the combined set of properties. *///from w w w .j a va2 s . co m protected Properties addProperties(Properties b) { // initial // Properties result = new Properties(this); Properties sys = System.getProperties(); Pattern pattern = Pattern.compile("\\$\\{[-a-zA-Z0-9._]+\\}"); for (Enumeration e = b.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); String value = b.getProperty(key); // unparse value ${prop.key} inside braces Matcher matcher = pattern.matcher(value); StringBuffer sb = new StringBuffer(); while (matcher.find()) { // extract name of properties from braces String newKey = value.substring(matcher.start() + 2, matcher.end() - 1); // try to find a matching value in result properties String newVal = getProperty(newKey); // if still not found, try system properties if (newVal == null) { newVal = sys.getProperty(newKey); } // replace braced string with the actual value or empty string matcher.appendReplacement(sb, newVal == null ? "" : newVal); } matcher.appendTail(sb); setProperty(key, sb.toString()); } return this; }
From source file:com.bellman.bible.service.device.speak.SpeakTextProvider.java
/** * ICS rejects text longer than 4000 chars so break it up *//* w w w . jav a 2 s .co m*/ private List<String> breakUpText(String text) { // // first try to split text nicely at the end of sentences // List<String> chunks1 = new ArrayList<String>(); // is the text short enough to use as is if (text.length() < MAX_SPEECH_ITEM_CHAR_LENGTH) { chunks1.add(text); } else { // break up the text at sentence ends Matcher matcher = BREAK_PATTERN.matcher(text); int matchedUpTo = 0; while (matcher.find()) { int nextEnd = matcher.end(); chunks1.add(text.substring(matchedUpTo, nextEnd)); matchedUpTo = nextEnd; } // add on the final part of the text, if there is any if (matchedUpTo < text.length()) { chunks1.add(text.substring(matchedUpTo)); } } // // If any text is still too long because the regexp was not matched then forcefully split it up // All chunks are probably now less than 4000 chars as required by tts but go through again for languages that don't have '. ' at the end of sentences // List<String> chunks2 = new ArrayList<String>(); for (String chunk : chunks1) { if (chunk.length() < MAX_SPEECH_ITEM_CHAR_LENGTH) { chunks2.add(chunk); } else { // force chunks to be correct length -10 is just to allow a bit of extra room chunks2.addAll(splitEqually(chunk, MAX_SPEECH_ITEM_CHAR_LENGTH - 10)); } } return chunks2; }
From source file:de.ks.text.AsciiDocParser.java
private String copyFiles(String parse, File dataDir) throws IOException { Pattern pattern = Pattern.compile("\"file:.*\""); Matcher matcher = pattern.matcher(parse); int bodyTag = parse.indexOf("<body"); Map<String, String> replacements = new HashMap<>(); while (matcher.find()) { int start = matcher.start(); if (start < bodyTag) { continue; }// ww w . j ava 2 s. co m int end = matcher.end(); String fileReference = parse.substring(start + 1, end - 1); end = fileReference.indexOf("\""); fileReference = fileReference.substring(0, end); log.debug("Found file reference {}", fileReference); URI uri = URI.create(fileReference.replace('\\', '/')); File sourceFile = new File(uri); File targetFile = new File(dataDir, sourceFile.getName()); java.nio.file.Files.copy(sourceFile.toPath(), targetFile.toPath()); replacements.put(fileReference, dataDir.getName() + "/" + targetFile.getName()); } for (Map.Entry<String, String> entry : replacements.entrySet()) { String original = entry.getKey(); String replacement = entry.getValue(); parse = StringUtils.replace(parse, original, replacement); } return parse; }
From source file:com.nextep.designer.sqlgen.ui.editors.SQLTextHtmlHover.java
@SuppressWarnings("unchecked") @Override/*from w w w .j a v a 2 s . c o m*/ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { final int offset = hoverRegion.getOffset(); final IDocument document = textViewer.getDocument(); if (document == null) return null; IRegion lineInfo; String line; try { lineInfo = document.getLineInformationOfOffset(offset); line = document.get(lineInfo.getOffset(), lineInfo.getLength()); } catch (BadLocationException ex) { return null; } // Retrieving proposals ITypedObjectTextProvider provider = SQLEditorUIServices.getInstance().getTypedObjectTextProvider(); List<String> allProposals = provider.listProvidedElements(); for (String s : allProposals) { if (line.toUpperCase().contains(s.toUpperCase())) { // More accurate search Pattern p = Pattern.compile("(\\W|\\s|^)" + s.toUpperCase() + "(\\W|\\s|$)"); //$NON-NLS-1$ //$NON-NLS-2$ Matcher m = p.matcher(line.toUpperCase()); while (m.find()) { if (offset >= (m.start() + lineInfo.getOffset()) && offset <= (m.end() + lineInfo.getOffset())) { final ITypedObject obj = provider.getElement(s); final StringBuffer buf = new StringBuffer(); final INamedObject named = (INamedObject) obj; buf.append("<html>"); //$NON-NLS-1$ addStyleSheet(buf); appendColors(buf, FontFactory.BLACK.getRGB(), FontFactory.LIGHT_YELLOW.getRGB()); // buf.append("\n<table BORDER=0 BORDERCOLOR=\"#000000\" CELLPADDING=0 cellspacing=0 >\n"); // buf.append("<tr><td>\n"); URL u = ImageService.getInstance() .getImageURL(ImageFactory.getImageDescriptor(obj.getType().getIcon())); buf.append("<table border=0><tr valign=\"CENTER\"><td><img src=\"" //$NON-NLS-1$ + u.toExternalForm() + "\"/> "); //$NON-NLS-1$ buf.append("</td><td><b>" + obj.getType().getName() + " " + named.getName() //$NON-NLS-1$ //$NON-NLS-2$ + "</b></td></tr></table>"); //$NON-NLS-1$ if (named.getDescription() != null && !"".equals(named.getDescription().trim())) { //$NON-NLS-1$ buf.append("<i>" + named.getDescription() + "</i><br><br>"); //$NON-NLS-1$ //$NON-NLS-2$ } else { buf.append("<i>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.noDesc")); //$NON-NLS-1$ buf.append("</i><br><br>"); //$NON-NLS-1$ } // Temporarily adding table definition here if (obj instanceof IBasicTable) { final IBasicTable t = (IBasicTable) obj; buf.append("<table BORDER=1 BORDERCOLOR=\"#000000\" CELLPADDING=4 cellspacing=0 >\n"); // + //$NON-NLS-1$ buf.append("<tr bgcolor=\""); //$NON-NLS-1$ appendColor(buf, new RGB(220, 250, 220)); buf.append("\"><td><b>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.columnNameCol")); //$NON-NLS-1$ buf.append("</b></td><td><b>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.datatypeCol")); //$NON-NLS-1$ buf.append("</b></td><td><b>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.descriptionCol")); //$NON-NLS-1$ buf.append("</b></td></tr>\n"); //$NON-NLS-1$ // /*cellspacing=\"0\" callpadding=\"0\" */ "border=\"1\" align=\"left\" width=\"350\">\n"); for (IBasicColumn c : t.getColumns()) { buf.append("<tr>\n"); //$NON-NLS-1$ buf.append("<td>" + c.getName() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$ buf.append("<td>" + c.getDatatype() + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$ final String desc = c.getDescription(); buf.append("<td>" + (desc == null ? "" : desc) + "</td>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append("</tr>"); //$NON-NLS-1$ } buf.append("</table><br>"); //$NON-NLS-1$ } else { buf.append("<br>"); //$NON-NLS-1$ } if (obj instanceof IReferencer) { Collection<IReference> refs = ((IReferencer) obj).getReferenceDependencies(); if (refs != null && !refs.isEmpty()) { buf.append("<b>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.dependentOf")); //$NON-NLS-1$ buf.append("</b><br><span>"); //$NON-NLS-1$ for (IReference r : refs) { IReferenceable ref = VersionHelper.getReferencedItem(r); buf.append("<li>" + ((ITypedObject) ref).getType().getName() //$NON-NLS-1$ + " <u>" + ((INamedObject) ref).getName() //$NON-NLS-1$ + "</u></li>"); //$NON-NLS-1$ // buf.append(Designer.getInstance().getQualifiedName(ref) // + "<br>"); } buf.append("</span><br>"); //$NON-NLS-1$ } } if (obj instanceof IReferenceable && invRefMap != null) { Collection<IReferencer> referencers = (Collection<IReferencer>) invRefMap .get(((IReferenceable) obj).getReference()); if (referencers != null && !referencers.isEmpty()) { buf.append("<b>"); //$NON-NLS-1$ buf.append(SQLMessages.getString("sqlHover.dependencies")); //$NON-NLS-1$ buf.append("</b><br><span>"); //$NON-NLS-1$ for (IReferencer r : referencers) { buf.append("<li>" + ((ITypedObject) r).getType().getName() //$NON-NLS-1$ + " <u>" + ((INamedObject) r).getName() //$NON-NLS-1$ + "</u></li>"); //$NON-NLS-1$ } } buf.append("</span>"); //$NON-NLS-1$ } // buf.append("</td></tr></table>"); buf.append("</body></html>"); //$NON-NLS-1$ return buf.toString(); } } } } return null; }
From source file:de.chaosfisch.google.youtube.upload.metadata.AbstractMetadataService.java
private Map<String, Object> getMetadataMonetization(final String content, final Upload upload) { final Map<String, Object> params = Maps.newHashMapWithExpectedSize(MONETIZE_PARAMS_SIZE); final Metadata metadata = upload.getMetadata(); final Monetization monetization = upload.getMonetization(); if (monetization.isClaim() && License.YOUTUBE == upload.getMetadata().getLicense()) { params.put("video_monetization_style", "ads"); if (!monetization.isPartner() || ClaimOption.MONETIZE == monetization.getClaimoption()) { params.put("claim_style", "ads"); params.put("enable_overlay_ads", boolConverter(monetization.isOverlay())); params.put("trueview_instream", boolConverter(monetization.isTrueview())); params.put("instream", boolConverter(monetization.isInstream())); params.put("long_ads_checkbox", boolConverter(monetization.isInstreamDefaults())); params.put("paid_product", boolConverter(monetization.isProduct())); params.put("allow_syndication", boolConverter(Syndication.GLOBAL == monetization.getSyndication())); }/*w w w .j a v a2 s. c o m*/ if (monetization.isPartner()) { params.put("claim_type", ClaimType.AUDIO_VISUAL == monetization.getClaimtype() ? "B" : ClaimType.VISUAL == monetization.getClaimtype() ? "V" : "A"); final String toFind = ClaimOption.MONETIZE == monetization.getClaimoption() ? "Monetize in all countries" : ClaimOption.TRACK == monetization.getClaimoption() ? "Track in all countries" : "Block in all countries"; final Pattern pattern = Pattern.compile( "<option\\s*value=\"([^\"]+?)\"\\s*(selected(=\"\")?)?\\sdata-is-monetized-policy=\"(true|false)\"\\s*>\\s*([^<]+?)\\s*</option>"); final Matcher matcher = pattern.matcher(content); String usagePolicy = null; int position = 0; while (matcher.find(position)) { position = matcher.end(); if (matcher.group(5).trim().equals(toFind)) { usagePolicy = matcher.group(1); } } params.put("usage_policy", usagePolicy); final String assetName = monetization.getAsset().name().toLowerCase(Locale.getDefault()); params.put("asset_type", assetName); params.put(assetName + "_custom_id", monetization.getCustomId().isEmpty() ? upload.getVideoid() : monetization.getCustomId()); params.put(assetName + "_notes", monetization.getNotes()); params.put(assetName + "_tms_id", monetization.getTmsid()); params.put(assetName + "_isan", monetization.getIsan()); params.put(assetName + "_eidr", monetization.getEidr()); if (Asset.TV != monetization.getAsset()) { // WEB + MOVIE ONLY params.put(assetName + "_title", !monetization.getTitle().isEmpty() ? monetization.getTitle() : metadata.getTitle()); params.put(assetName + "_description", monetization.getDescription()); } else { // TV ONLY params.put("show_title", monetization.getTitle()); params.put("episode_title", monetization.getTitleepisode()); params.put("season_nb", monetization.getSeasonNb()); params.put("episode_nb", monetization.getEpisodeNb()); } } } return params; }
From source file:com.google.enterprise.connector.filesystem.FileConnectorTypeTest.java
/** * Make sure HTML tags in {@code s} are balanced. * * @param s/*w w w . j a v a2s . co m*/ */ private void assertBalancedTags(String s) { LinkedList<String> stack = Lists.newLinkedList(); Matcher m = TAG.matcher(s); int start = 0; while (m.find(start)) { String tag = s.substring(m.start(), m.end()); if (isOpenTag(tag)) { stack.addFirst(tag); } else if (isCloseTag(tag)) { String open = stack.poll(); assertNotNull(String.format("extra tag: %s", tag), open); assertEquals(String.format("mismatched tags: %s vs %s", open, tag), getName(open), getName(tag)); } else { // Ignore open-closed tags (<tag/>). } start = m.end(); } assertEquals("Open tags at end of input", 0, stack.size()); }
From source file:com.cotrino.knowledgemap.db.Question.java
private void generateQuestion(Page page, List<String> sentences) { int firstSentence = (int) Math.round(Math.random() * (sentences.size() - QUESTION_SENTENCES)); String question = ""; for (int i = firstSentence; i < firstSentence + QUESTION_SENTENCES; i++) { question += sentences.get(i);/* w w w. j ava 2s . c o m*/ } Matcher matcher = LINK_PATTERN.matcher(question); List<Integer> matchStart = new LinkedList<Integer>(); List<Integer> matchEnd = new LinkedList<Integer>(); List<String> matchLink = new LinkedList<String>(); while (matcher.find()) { String link = matcher.group(1); if (!link.contains(":")) { matchStart.add(matcher.start()); matchEnd.add(matcher.end()); matchLink.add(link); } } if (matchLink.size() > 0) { int linkToBeReplaced = (int) Math.round(Math.random() * (matchLink.size() - 1)); int start = matchStart.get(linkToBeReplaced); int end = matchEnd.get(linkToBeReplaced); String link = matchLink.get(linkToBeReplaced); String[] answers = link.split("\\|"); for (String answer : answers) { this.answers.add(answer); } String placeholder = link.replaceAll("[^ \\|]", "."); if (placeholder.contains("|")) { placeholder = placeholder.split("\\|")[1]; } String text = question.substring(0, start) + "<span class='placeholder'>" + placeholder + "</span>" + question.substring(end); // replace other links of the kind [[A|B]] with A text = text.replaceAll("\\[\\[[^\\]\\|]+\\|", ""); // replace other links of the kind [[A]] with A text = text.replaceAll("\\[\\[", "").replaceAll("\\]\\]", ""); //System.out.println("Question: "+text); this.question = text; this.page = page; } }
From source file:nya.miku.wishmaster.chans.cirno.MikubaModule.java
@Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { String body, video;/* ww w. jav a 2s . c om*/ Matcher ytLink = YOUTUBE_PATTERN.matcher(model.comment); if (ytLink.find()) { body = new StringBuilder(model.comment).delete(ytLink.start(), ytLink.end()).toString(); video = "http://www.youtube.com/watch?v=" + ytLink.group(1); } else { body = model.comment; video = ""; } String url = (useHttps() ? "https://" : "http://") + MIKUBA_DOMAIN + "/reply/" + (model.threadNumber == null ? "0" : model.threadNumber); ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task) .addString("title", model.subject).addString("captcha", model.captchaAnswer).addString("body", body) .addString("video", video).addString("email", ""); if (model.attachments != null && model.attachments.length > 0) postEntityBuilder.addFile("image", model.attachments[0], model.randomHash); else postEntityBuilder.addPart("image", new ByteArrayBody(new byte[0], "")); HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true) .build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); Logger.d(TAG, response.statusCode + " - " + response.statusReason); if (response.statusCode == 303) { return null; } else if (response.statusCode == 200) { ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copyStream(response.stream, output); String htmlResponse = output.toString("UTF-8"); //Logger.d(TAG, htmlResponse); if (htmlResponse.contains("/static/captcha.gif")) { throw new Exception(" ?!"); } } else throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); saveCookiesToPreferences(); } return null; }