List of usage examples for java.util.regex Matcher end
public int end()
From source file:co.cask.cdap.common.conf.Configuration.java
private String substituteVars(String expr) { if (expr == null) { return null; }/* w ww .j a va2s . co m*/ Matcher match = VAR_PAT.matcher(""); String eval = expr; for (int s = 0; s < MAX_SUBST; s++) { match.reset(eval); if (!match.find()) { return eval; } String var = match.group(); var = var.substring(2, var.length() - 1); // remove ${ .. } String val = null; try { val = System.getProperty(var); } catch (SecurityException se) { LOG.warn("Unexpected SecurityException in Configuration", se); } if (val == null) { val = getRaw(var); } if (val == null) { return eval; // return literal ${var}: var is unbound } // substitute eval = eval.substring(0, match.start()) + val + eval.substring(match.end()); } throw new IllegalStateException("Variable substitution depth too large: " + MAX_SUBST + " " + expr); }
From source file:mobisocial.musubi.util.OGUtil.java
public static OGData getOrGuess(String url) { DefaultHttpClient hc = new DefaultHttpClient(); HttpResponse res;//from w w w . j av a 2 s .c om try { HttpGet hg = new HttpGet(url); res = hc.execute(hg); } catch (Exception e) { Log.e(TAG, "unable to fetch page to get og tags", e); return null; } String location = url; //TODO: if some kind of redirect magic happened, then //make the location match that OGData og = new OGData(); HttpEntity he = res.getEntity(); Header content_type = he.getContentType(); //TODO: check the content directly if they forget the type header if (content_type == null || content_type.getValue() == null) { Log.e(TAG, "page missing content type ..abandoning: " + url); return null; } og.mMimeType = content_type.getValue(); //just make a thumbnail if the shared item is an image if (og.mMimeType.startsWith("image/")) { Bitmap b; try { b = BitmapFactory.decodeStream(he.getContent()); } catch (Exception e) { return null; } //TODO: scaling int w = b.getWidth(); int h = b.getHeight(); if (w > h) { h = h * 200 / w; w = 200; } else { w = w * 200 / h; h = 200; } Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true); b.recycle(); b = b2; ByteArrayOutputStream baos = new ByteArrayOutputStream(); b.compress(CompressFormat.PNG, 100, baos); og.mImage = baos.toByteArray(); b.recycle(); return og; } //if its not html, we can't extract more details, the caller //should rely on what they already know. if (!og.mMimeType.startsWith("text/html") && !og.mMimeType.startsWith("application/xhtml")) { Log.e(TAG, "shared content is not a known type for meta data processing " + og.mMimeType); return og; } String html; try { html = IOUtils.toString(he.getContent()); } catch (Exception e) { Log.e(TAG, "failed to read html content", e); return og; } Matcher m = sTitleRegex.matcher(html); if (m.find()) { og.mTitle = StringEscapeUtils.unescapeHtml4(m.group(1)); } m = sMetaRegex.matcher(html); int offset = 0; String raw_description = null; while (m.find(offset)) { try { String meta_tag = m.group(); Matcher mp = sPropertyOfMeta.matcher(meta_tag); if (!mp.find()) continue; String type = mp.group(1); type = type.substring(1, type.length() - 1); Matcher md = sContentOfMeta.matcher(meta_tag); if (!md.find()) continue; String data = md.group(1); //remove quotes data = data.substring(1, data.length() - 1); data = StringEscapeUtils.unescapeHtml4(data); if (type.equalsIgnoreCase("og:title")) { og.mTitle = data; } else if (type.equalsIgnoreCase("og:image")) { HttpResponse resi; try { HttpGet hgi = new HttpGet(data); resi = hc.execute(hgi); } catch (Exception e) { Log.e(TAG, "unable to fetch og image url", e); continue; } HttpEntity hei = resi.getEntity(); if (!hei.getContentType().getValue().startsWith("image/")) { Log.e(TAG, "image og tag points to non image data" + hei.getContentType().getValue()); } try { Bitmap b; try { b = BitmapFactory.decodeStream(hei.getContent()); } catch (Exception e) { return null; } //TODO: scaling int w = b.getWidth(); int h = b.getHeight(); if (w > h) { h = h * Math.min(200, w) / w; w = Math.min(200, w); } else { w = w * Math.min(200, h) / h; h = Math.min(200, h); } Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true); b.recycle(); b = b2; ByteArrayOutputStream baos = new ByteArrayOutputStream(); b.compress(CompressFormat.PNG, 100, baos); b.recycle(); og.mImage = baos.toByteArray(); } catch (Exception e) { Log.e(TAG, "failed to fetch image for og", e); continue; } } else if (type.equalsIgnoreCase("description")) { raw_description = data; } else if (type.equalsIgnoreCase("og:description")) { og.mDescription = data; } else if (type.equalsIgnoreCase("og:url")) { og.mUrl = data; } } finally { offset = m.end(); } } HashSet<String> already_fetched = new HashSet<String>(); if (og.mImage == null) { int max_area = 0; m = sImageRegex.matcher(html); int img_offset = 0; while (m.find(img_offset)) { try { String img_tag = m.group(); Matcher ms = sSrcOfImage.matcher(img_tag); if (!ms.find()) continue; String img_src = ms.group(1); img_src = img_src.substring(1, img_src.length() - 1); img_src = StringEscapeUtils.unescapeHtml4(img_src); //don't fetch an image twice (like little 1x1 images) if (already_fetched.contains(img_src)) continue; already_fetched.add(img_src); HttpResponse resi; try { HttpGet hgi = new HttpGet(new URL(new URL(location), img_src).toString()); resi = hc.execute(hgi); } catch (Exception e) { Log.e(TAG, "unable to fetch image url for biggest image search" + img_src, e); continue; } HttpEntity hei = resi.getEntity(); if (hei == null) { Log.w(TAG, "image missing en ..trying entity response: " + url); continue; } Header content_type_image = hei.getContentType(); if (content_type_image == null || content_type_image.getValue() == null) { Log.w(TAG, "image missing content type ..trying anyway: " + url); } if (!content_type_image.getValue().startsWith("image/")) { Log.w(TAG, "image tag points to non image data " + hei.getContentType().getValue() + " " + img_src); } try { Bitmap b; try { b = BitmapFactory.decodeStream(hei.getContent()); } catch (Exception e) { return null; } //TODO: scaling int w = b.getWidth(); int h = b.getHeight(); if (w * h <= max_area) { continue; } if (w < 32 || h < 32) { //skip dinky crap continue; } if (w > h) { h = h * Math.min(200, w) / w; w = Math.min(200, w); } else { w = w * Math.min(200, h) / h; h = Math.min(200, h); } Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true); b.recycle(); b = b2; ByteArrayOutputStream baos = new ByteArrayOutputStream(); b.compress(CompressFormat.PNG, 100, baos); og.mImage = baos.toByteArray(); b.recycle(); max_area = w * h; } catch (Exception e) { Log.e(TAG, "failed to fetch image for og", e); continue; } } finally { img_offset = m.end(); } } } if (og.mDescription == null) og.mDescription = raw_description; return og; }
From source file:org.jets3t.apps.uploader.Uploader.java
/** * Replaces variables of the form ${variableName} in the input string with the value of that * variable name in the local uploaderProperties properties object, or with one of the * following special variables://from ww w. j av a2 s. com * <ul> * <li>fileName : Name of file being uploaded</li> * <li>fileSize : Size of the file being uploaded, eg 1.04 MB</li> * <li>filePath : Absolute path of the file being uploaded</li> * <li>maxFileSize : The maxiumum allowed file size in MB</li> * <li>maxFileCount : The maximum number of files that may be uploaded</li> * <li>validFileExtensions : A list of the file extensions allowed</li> * </ul> * If the variable named in the input string is not available, or has no value, the variable * reference is left in the result. * * @param message * string that may have variables to replace * @return * the input string with any variable referenced replaced with the variable's value. */ private String replaceMessageVariables(String message) { if (message == null) { return ""; } String result = message; // Replace upload file variables, if an upload file has been chosen. if (filesToUpload != null) { long filesSize = 0; StringBuffer fileNameList = new StringBuffer(); for (int i = 0; i < filesToUpload.length; i++) { filesSize += filesToUpload[i].length(); fileNameList.append(filesToUpload[i].getName()).append(" "); } result = result.replaceAll("\\$\\{fileNameList\\}", fileNameList.toString()); result = result.replaceAll("\\$\\{filesSize\\}", byteFormatter.formatByteSize(filesSize)); } result = result.replaceAll("\\$\\{maxFileSize\\}", String.valueOf(fileMaxSizeMB)); result = result.replaceAll("\\$\\{maxFileCount\\}", String.valueOf(fileMaxCount)); String extList = validFileExtensions.toString(); extList = extList.substring(1, extList.length() - 1); extList = extList.replaceAll(",", " "); result = result.replaceAll("\\$\\{validFileExtensions\\}", extList); Pattern pattern = Pattern.compile("\\$\\{.+?\\}"); Matcher matcher = pattern.matcher(result); int offset = 0; while (matcher.find(offset)) { String variable = matcher.group(); String variableName = variable.substring(2, variable.length() - 1); String replacement = null; if (userInputProperties != null && userInputProperties.containsKey(variableName)) { log.debug("Replacing variable '" + variableName + "' with value from a user input field"); replacement = userInputProperties.getProperty(variableName, null); } else if (parametersMap != null && parametersMap.containsKey(variableName)) { log.debug("Replacing variable '" + variableName + "' with value from Uploader's parameters"); replacement = (String) parametersMap.get(variableName); } else if (uploaderProperties != null && uploaderProperties.containsKey(variableName)) { log.debug("Replacing variable '" + variableName + "' with value from uploader.properties file"); replacement = uploaderProperties.getStringProperty(variableName, null); } if (replacement != null) { result = result.substring(0, matcher.start()) + replacement + result.substring(matcher.end()); offset = matcher.start() + 1; matcher.reset(result); } else { offset = matcher.start() + 1; } } if (!result.equals(message)) { log.debug("Replaced variables in text: " + message + " => " + result); } return result; }
From source file:au.org.theark.study.model.dao.StudyDao.java
public void createSubject(SubjectVO subjectVo) throws ArkUniqueException, ArkSubjectInsertException { Study study = subjectVo.getLinkSubjectStudy().getStudy(); if (study.getAutoGenerateSubjectUid()) { String subjectUID = getNextGeneratedSubjectUID(study); if (isSubjectUIDUnique(subjectUID, study.getId(), "Insert")) { subjectVo.getLinkSubjectStudy().setSubjectUID(subjectUID); } else {// TODO : maybe a for loop to guard against a manual db insert, or just throw exception and holds someone up from further inserts until // investigated why? subjectUID = getNextGeneratedSubjectUID(study); subjectVo.getLinkSubjectStudy().setSubjectUID(subjectUID); }//from w w w .ja v a 2 s.c o m } else { if (!isSubjectUIDUnique(subjectVo.getLinkSubjectStudy().getSubjectUID(), subjectVo.getLinkSubjectStudy().getStudy().getId(), "Insert")) { throw new ArkUniqueException("Subject UID must be unique"); } } // Set default foreign key reference if (subjectVo.getLinkSubjectStudy().getSubjectStatus() == null || StringUtils.isBlank(subjectVo.getLinkSubjectStudy().getSubjectStatus().getName())) { SubjectStatus subjectStatus = getSubjectStatusByName("Subject"); subjectVo.getLinkSubjectStudy().setSubjectStatus(subjectStatus); } // Set default foreign key reference if (subjectVo.getLinkSubjectStudy().getPerson().getTitleType() == null || StringUtils.isBlank(subjectVo.getLinkSubjectStudy().getPerson().getTitleType().getName())) { TitleType titleType = getTitleType(new Long(0)); subjectVo.getLinkSubjectStudy().getPerson().setTitleType(titleType); } // Set default foreign key reference if (subjectVo.getLinkSubjectStudy().getPerson().getGenderType() == null || StringUtils.isBlank(subjectVo.getLinkSubjectStudy().getPerson().getGenderType().getName())) { GenderType genderType = getGenderType(new Long(0)); subjectVo.getLinkSubjectStudy().getPerson().setGenderType(genderType); } // Set default foreign key reference if (subjectVo.getLinkSubjectStudy().getPerson().getVitalStatus() == null || StringUtils.isBlank(subjectVo.getLinkSubjectStudy().getPerson().getVitalStatus().getName())) { VitalStatus vitalStatus = getVitalStatus(new Long(0)); subjectVo.getLinkSubjectStudy().getPerson().setVitalStatus(vitalStatus); } //log.info("create subject otherIDs: " + subjectVo.getLinkSubjectStudy().getPerson().getOtherIDs()); if (subjectVo.getLinkSubjectStudy().getPerson().getOtherIDs() == null || subjectVo.getLinkSubjectStudy().getPerson().getOtherIDs().isEmpty()) { // get List<OtherID> otherIDs = new ArrayList<OtherID>(); subjectVo.getLinkSubjectStudy().getPerson().setOtherIDs(otherIDs); } Session session = getSession(); Person person = subjectVo.getLinkSubjectStudy().getPerson(); if (person.getId() == null) { session.save(person); PersonLastnameHistory personLastNameHistory = null; // Previous LastName (if supplied on new Subject) if (subjectVo.getSubjectPreviousLastname() != null && !subjectVo.getSubjectPreviousLastname().isEmpty()) { personLastNameHistory = new PersonLastnameHistory(); personLastNameHistory.setPerson(person); personLastNameHistory.setLastName(subjectVo.getSubjectPreviousLastname()); session.save(personLastNameHistory); } /* * only keeping previous names from now on // Current lastName if (person.getLastName() != null) { personLastNameHistory = new * PersonLastnameHistory(); personLastNameHistory.setPerson(person); personLastNameHistory.setLastName(person.getLastName()); * session.save(personLastNameHistory); } */ } // Update subjectPreviousLastname TODO investigate subjectVo.setSubjectPreviousLastname(getPreviousLastname(person)); LinkSubjectStudy linkSubjectStudy = subjectVo.getLinkSubjectStudy(); String subjectUID = linkSubjectStudy.getSubjectUID(); StringBuilder natBuilder = new StringBuilder(); Matcher matcher = Pattern.compile("\\d+").matcher(subjectUID); int last_end = 0; while (matcher.find()) { if (matcher.start() > last_end) { natBuilder.append(subjectUID.substring(last_end, matcher.start())); } String subjectUIDNumber = org.apache.commons.lang.StringUtils .leftPad(subjectUID.substring(matcher.start(), matcher.end()), 20, '0'); natBuilder.append(subjectUIDNumber); last_end = matcher.end(); } linkSubjectStudy.setNaturalUID(natBuilder.toString()); session.save(linkSubjectStudy);// The hibernate session is the same. This should be automatically bound with Spring's autoConsentLinkSubjectStudy(subjectVo.getLinkSubjectStudy()); // TODO EXCEPTIONHANDLING }
From source file:com.github.gekoh.yagen.ddl.CreateDDL.java
private String addConstraintsAndNames(Dialect dialect, StringBuffer additionalObjects, String sqlCreate, String nameLC, Map<String, String> column2EnumConstraint) { List<String> pkColumns = getPkColumnNamesFrom(sqlCreate); TableConfig tableConfig = tblNameToConfig.get(nameLC); StringBuilder b = new StringBuilder(); StringBuilder enumConstraints = new StringBuilder(); Matcher matcher = COL_PATTERN.matcher(sqlCreate); int idx = 0;//w w w . j a va2s .com while (matcher.find(idx)) { String defColName = matcher.group(COL_PATTERN_IDX_COLNAME); String colName = TableConfig.getIdentifierForReference(defColName); String constraintDef = column2EnumConstraint != null ? column2EnumConstraint.get(colName) : null; if (constraintDef != null) { String constraintName = getProfile().getNamingStrategy().constraintName(getEntityClassName(nameLC), nameLC, colName, Constants._CK); enumConstraints.append(", constraint ").append(constraintName); enumConstraints.append(" check (").append(defColName).append(" in (").append(constraintDef) .append("))"); } // name not null constraint idx = appendConstraint(b, sqlCreate, nameLC, colName, idx, matcher, COL_PATTERN_IDX_NOTNULL, Constants._NN); // name unique constraint idx = appendConstraint(b, sqlCreate, nameLC, colName, idx, matcher, COL_PATTERN_IDX_UNIQUE, Constants._UK); b.append(sqlCreate.substring(idx, matcher.end())); idx = matcher.end(); } b.append(sqlCreate.substring(idx)); sqlCreate = b.toString(); b = new StringBuilder(); matcher = UNIQUE_PATTERN.matcher(sqlCreate); idx = 0; while (matcher.find(idx)) { // name unique constraint idx = appendConstraint(b, sqlCreate, nameLC, DefaultNamingStrategy.concatColumnNames(matcher.group(3)), idx, matcher, 2, Constants._UK); b.append(sqlCreate.substring(idx, matcher.end())); idx = matcher.end(); } b.append(sqlCreate.substring(idx)); sqlCreate = b.toString(); matcher = TBL_PATTERN.matcher(sqlCreate); if (matcher.find() && matcher.group(TBL_PATTERN_IDX_PK_CLAUSE) != null) { b = new StringBuilder(); idx = matcher.start(TBL_PATTERN_IDX_PK_START); b.append(sqlCreate.substring(0, idx)); // name primary key constraint idx = appendConstraint(b, sqlCreate, nameLC, DefaultNamingStrategy.concatColumnNames(matcher.group(TBL_PATTERN_IDX_PK_COLLIST)), idx, matcher, TBL_PATTERN_IDX_PK_START, Constants._PK); b.append(sqlCreate.substring(idx)); sqlCreate = b.toString(); } else { LOG.info("no primary key found for table {}", nameLC); } matcher = TBL_PATTERN_WO_PK.matcher(sqlCreate); if (matcher.matches()) { b = new StringBuilder(sqlCreate.substring(0, matcher.start(TBL_PATTERN_WO_PK_IDX_AFTER_COL_DEF))); if (enumConstraints.length() > 0) { b.append(enumConstraints); } com.github.gekoh.yagen.api.Table tblAnnotation = tableConfig != null ? tableConfig.getTableAnnotationOfType(com.github.gekoh.yagen.api.Table.class) : null; if (tblAnnotation != null) { for (CheckConstraint checkConstraint : tblAnnotation.checkConstraints()) { String constraintName = getProfile().getNamingStrategy().constraintName(checkConstraint); if (StringUtils.isEmpty(constraintName)) { throw new IllegalArgumentException( "please specify a check constraint name in annotation CheckConstraint for table " + nameLC); } checkObjectName(dialect, constraintName); if (checkConstraint.initiallyDeferred() && isPostgreSql(dialect)) { String objectName = constraintName + "_FCT"; additionalObjects.append(STATEMENT_SEPARATOR) .append(getDeferredCheckConstraintFunction(dialect, objectName, constraintName, nameLC, String.format(checkConstraint.declaration(), "t."), pkColumns)) .append("\n/"); additionalObjects.append(STATEMENT_SEPARATOR).append("create constraint trigger ") .append(getProfile().getNamingStrategy().triggerName(constraintName + "_TRG")) .append("\n").append("after insert or update\n" + "on ").append(nameLC) .append(" initially deferred for each row\n" + "execute procedure ") .append(objectName).append("();"); } else { b.append(", constraint ").append(constraintName); b.append(" check (").append(String.format(checkConstraint.declaration(), "")).append(")"); if (supportsDeferrable(dialect) && checkConstraint.initiallyDeferred()) { b.append(" deferrable initially deferred"); } } } for (UniqueConstraint uniqueConstraint : tblAnnotation.uniqueConstraints()) { // custom declarations of unique keys need to be created with separate unique index DDL // when specifying column names we may use an inline unique constraint if (uniqueConstraint.columnNames().length < 1) { continue; } String constraintName = getProfile().getNamingStrategy().constraintName(uniqueConstraint); if (StringUtils.isEmpty(constraintName)) { throw new IllegalArgumentException( "please specify a unique constraint name in annotation UniqueConstraint on table " + nameLC); } checkObjectName(dialect, constraintName); if (StringUtils.isNotEmpty(uniqueConstraint.declaration()) && uniqueConstraint.columnNames().length > 0) { throw new IllegalArgumentException( "please specify either a declaration or a set of column names for UniqueConstraint on table " + nameLC); } StringBuilder declaration = new StringBuilder(); for (String columnName : uniqueConstraint.columnNames()) { if (declaration.length() > 0) { declaration.append(", "); } declaration.append(columnName); } b.append(", constraint ").append(constraintName); b.append(" unique (").append(declaration).append(")"); if (supportsDeferrable(dialect) && uniqueConstraint.initiallyDeferred()) { b.append(" deferrable initially deferred"); } if (uniqueConstraint.usingLocalIndex() && supportsPartitioning(dialect)) { b.append(" using index (create unique index ").append(constraintName).append(" on ") .append(nameLC); b.append(" (").append(declaration).append(") local)"); } } } b.append(sqlCreate.substring(matcher.start(TBL_PATTERN_WO_PK_IDX_AFTER_COL_DEF))); sqlCreate = b.toString(); } return sqlCreate; }
From source file:de.vanita5.twittnuker.util.Utils.java
public static CharSequence getKeywordHighlightedText(final CharSequence orig, final CharacterStyle style, final String... keywords) { if (keywords == null || keywords.length == 0 || orig == null) return orig; final SpannableStringBuilder sb = SpannableStringBuilder.valueOf(orig); final StringBuilder patternBuilder = new StringBuilder(); for (int i = 0, j = keywords.length; i < j; i++) { if (i != 0) { patternBuilder.append('|'); }//from w ww . ja v a2 s.c o m patternBuilder.append(Pattern.quote(keywords[i])); } final Matcher m = Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE).matcher(orig); while (m.find()) { sb.setSpan(style, m.start(), m.end(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE); } return sb; }