List of usage examples for java.util.regex Matcher appendReplacement
public Matcher appendReplacement(StringBuilder sb, String replacement)
From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java
/** * Increment source code of filePath using template fragment. * /*w w w . j a va2s . c o m*/ * @param filePath * @param incrementPath * @param incrementPattern * @param dataGroup */ public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern, String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) { try { HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template if (params != null && params.size() > 0) { /* for (String name : params.keySet()) { velocityVariables.put("params."+name, params.get(name)); }*/ velocityVariables.put("params", params); } //rodando velocity do incremento TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true); String incrementSource = templateEngine.runFile(incrementPath, velocityVariables); // Create the pattern Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*" para pegar as quebras de linhas que podem existir no incremento Matcher matcher = pattern.matcher(""); //novo incremento //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento matcher.reset(incrementSource); Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>(); while (matcher.find()) { String[] groups = new String[matcher.groupCount()]; for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } String increment = matcher.group(); //new increment mapGroupIncrement.put(increment, groups); //map increment vs groups } if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta return; } //le o arquivo atual FileInputStream inputFilePath = new FileInputStream(filePath); BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath); StringBuffer filePathContent = new StringBuffer(); int ch = 0; while ((ch = bufferedInput.read()) > -1) { filePathContent.append((char) ch); } inputFilePath.close(); bufferedInput.close(); //procura no arquivo todo pela expresso regular matcher = pattern.matcher(""); matcher.reset(filePathContent); StringBuffer newContentFile = new StringBuffer(); int countMatcher = 0; Map<String, String[]> mapGroupFile = new HashMap<String, String[]>(); while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado for (int i = 0; i < matcher.groupCount(); i++) { groups[i] = matcher.group(i + 1); } mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois countMatcher++; //isso vai contar onde esta o ltimo matcher } //valida quais incrementos so realmente novos, comparando os groups List<String> newIncrements = new LinkedList<String>(); for (String groupIncrement : mapGroupIncrement.keySet()) { String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento boolean itemFound = false; for (String groupFile : mapGroupFile.keySet()) { String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto itemFound = true; } } if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array newIncrements.add(groupIncrement); } } //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo StringBuffer newIncrementSource = new StringBuffer(); int i = 0; for (String incremento : newIncrements) { if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar newIncrementSource.append("\r\n"); } newIncrementSource.append(incremento); i++; } if (newIncrements.size() > 0) { //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) { pattern = Pattern.compile(firstAfter, Pattern.DOTALL); matcher = pattern.matcher(""); matcher.reset(filePathContent); //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :( countMatcher = 0; while (matcher.find()) { //verifica cada ocorrncia da expresso countMatcher++; } } //aqui vou realmente substituir os valores, j sabendo qual a ltima ocorrencia da palavra no arquivo i = 0; matcher.reset(); while (matcher.find()) { //verifica cada ocorrncia da expresso i++; if (countMatcher == i) { //se encontrou a ltima ocorrencia String matcherGroup = matcher.group(); matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement } } matcher.appendTail(newContentFile); } //save new file if (newContentFile.length() > 0) { FileUtil.writeFile(filePath, newContentFile.toString()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
From source file:de.escidoc.core.aa.business.UserAccountHandler.java
/** * replaces group-id-filter with resolved userIds. * * @param filter cql-filter/*from w w w .java 2s .c o m*/ * @return Map with replaced cql-query (groupId replaced with userIds) * @throws InvalidSearchQueryException e * @throws SystemException e */ private Map<String, String[]> fixCqlGroupFilter(final Map<String, String[]> filter) throws InvalidSearchQueryException, SystemException { Map<String, String[]> returnFilter = filter; final Object[] queryPartsObject = filter.get(Constants.SRU_PARAMETER_QUERY); if (queryPartsObject != null) { final String[] queryParts = new String[queryPartsObject.length]; for (int i = 0; i < queryPartsObject.length; i++) { if (queryPartsObject[i] != null) { queryParts[i] = queryPartsObject[i].toString(); } } boolean groupFilterFound = false; for (int i = 0; i < queryParts.length; i++) { final Matcher matcher = GROUP_FILTER_PATTERN.matcher(queryParts[i]); if (matcher.find()) { groupFilterFound = true; final Matcher groupFilterMatcher = GROUP_FILTER_PATTERN.matcher(queryParts[i]); final StringBuffer result = new StringBuffer(""); while (groupFilterMatcher.find()) { if (groupFilterMatcher.group(6).matches(".*?%.*")) { throw new InvalidSearchQueryException("Wildcards not allowed in group-filter"); } if (groupFilterMatcher.group(3) != null && groupFilterMatcher.group(3).matches(">|<|<=|>=|<>") || groupFilterMatcher.group(4) != null || groupFilterMatcher.group(5) != null) { throw new InvalidSearchQueryException("non-supported relation in group-filter"); } // get users for group final StringBuilder replacement = new StringBuilder(" ("); try { final Set<String> userIds = retrieveUsersForGroup(groupFilterMatcher.group(6)); // write user-cql-query // and replace group-expression with it. if (userIds != null && !userIds.isEmpty()) { for (final String userId : userIds) { if (replacement.length() > 2) { replacement.append(" or "); } replacement.append('\"'); replacement.append(Constants.FILTER_PATH_ID); replacement.append("\"=").append(userId).append(' '); } } else { throw new UserGroupNotFoundException(""); } } catch (final UserGroupNotFoundException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Error on getting users for group."); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Error on getting users for group.", e); } // if group has no users or group not found, // write nonexisting user in query replacement.append('\"'); replacement.append(Constants.FILTER_PATH_ID); replacement.append("\"=").append("nonexistinguser").append(' '); } replacement.append(") "); groupFilterMatcher.appendReplacement(result, replacement.toString()); } groupFilterMatcher.appendTail(result); queryParts[i] = result.toString(); } } if (groupFilterFound) { final Map<String, String[]> filter1 = new HashMap<String, String[]>(); for (final Entry<String, String[]> entry : filter.entrySet()) { if (entry.getValue() != null) { // noinspection RedundantCast filter1.put(entry.getKey(), new String[((Object[]) entry.getValue()).length]); // noinspection RedundantCast for (int j = 0; j < ((Object[]) entry.getValue()).length; j++) { filter1.get(entry.getKey())[j] = entry.getValue()[j]; } } else { filter1.put(entry.getKey(), null); } } filter1.put(Constants.SRU_PARAMETER_QUERY, queryParts); returnFilter = filter1; } } return returnFilter; }
From source file:org.apache.synapse.mediators.transform.PayloadFactoryMediator.java
/** * Replaces the payload format with SynapsePath arguments which are evaluated using getArgValues(). * * @param format//from w w w . jav a2 s .c o m * @param result * @param synCtx */ private void replace(String format, StringBuffer result, MessageContext synCtx) { HashMap<String, String>[] argValues = getArgValues(synCtx); HashMap<String, String> replacement; Map.Entry<String, String> replacementEntry; String replacementValue = null; Matcher matcher; matcher = pattern.matcher(format); try { while (matcher.find()) { String matchSeq = matcher.group(); int argIndex; try { argIndex = Integer.parseInt(matchSeq.substring(1, matchSeq.length())); } catch (NumberFormatException e) { argIndex = Integer.parseInt(matchSeq.substring(2, matchSeq.length() - 1)); } replacement = argValues[argIndex - 1]; replacementEntry = replacement.entrySet().iterator().next(); if (mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(XML_TYPE)) { // XML to JSON conversion here try { replacementValue = "<jsonObject>" + replacementEntry.getKey() + "</jsonObject>"; OMElement omXML = AXIOMUtil.stringToOM(replacementValue); // This is to replace \" with \\" and \\$ with \$. Because for Matcher, $ sign is // a special character and for JSON " is a special character. replacementValue = JsonUtil.toJsonString(omXML).toString() .replaceAll(ESCAPE_DOUBLE_QUOTE_WITH_FIVE_BACK_SLASHES, ESCAPE_DOUBLE_QUOTE_WITH_NINE_BACK_SLASHES) .replaceAll(ESCAPE_DOLLAR_WITH_TEN_BACK_SLASHES, ESCAPE_DOLLAR_WITH_SIX_BACK_SLASHES); } catch (XMLStreamException e) { handleException( "Error parsing XML for JSON conversion, please check your xPath expressions return valid XML: ", synCtx); } catch (AxisFault e) { handleException("Error converting XML to JSON", synCtx); } } else if (mediaType.equals(XML_TYPE) && inferReplacementType(replacementEntry).equals(JSON_TYPE)) { // JSON to XML conversion here try { OMElement omXML = JsonUtil.toXml(IOUtils.toInputStream(replacementEntry.getKey()), false); if (JsonUtil.isAJsonPayloadElement(omXML)) { // remove <jsonObject/> from result. Iterator children = omXML.getChildElements(); String childrenStr = ""; while (children.hasNext()) { childrenStr += (children.next()).toString().trim(); } replacementValue = childrenStr; } else { ///~ replacementValue = omXML.toString(); } //replacementValue = omXML.toString(); } catch (AxisFault e) { handleException( "Error converting JSON to XML, please check your JSON Path expressions return valid JSON: ", synCtx); } } else { // No conversion required, as path evaluates to regular String. replacementValue = replacementEntry.getKey(); // This is to replace " with \" and \\ with \\\\ if (mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(STRING_TYPE) && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) { replacementValue = replacementValue .replaceAll(Matcher.quoteReplacement("\\\\"), ESCAPE_BACK_SLASH_WITH_SIXTEEN_BACK_SLASHES) .replaceAll("\"", ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES); } else if ((mediaType.equals(JSON_TYPE) && inferReplacementType(replacementEntry).equals(JSON_TYPE)) && (!replacementValue.startsWith("{") && !replacementValue.startsWith("["))) { // This is to handle only the string value replacementValue = replacementValue.replaceAll("\"", ESCAPE_DOUBLE_QUOTE_WITH_TEN_BACK_SLASHES); } } matcher.appendReplacement(result, replacementValue); } } catch (ArrayIndexOutOfBoundsException e) { log.error("#replace. Mis-match detected between number of formatters and arguments", e); } matcher.appendTail(result); }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * parse embedded content resource urls/* w w w . j a v a 2s .com*/ * * @param message * - message * @param parentPath * - parent path * @param embeddedRefs * - embedded references * @return * - modifed content */ private String parseEmbeddedContentResourceUrls(String message, String parentPath, Set<String> embeddedRefs) { /*try { parentPath = URLDecoder.decode(parentPath, "UTF-8"); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) logger.warn("parseEmbeddedContentResourceUrls: " + e); }*/ StringBuffer sb = new StringBuffer(); Pattern p = getEmbeddedContentResourcePattern(); Matcher m = p.matcher(message); while (m.find()) { if (m.groupCount() == 2) { String ref = m.group(2); if (logger.isDebugEnabled()) logger.debug("parseEmbeddedContentResourceUrls Before : ref : " + ref); //check for the resource in the unzipped file before changing the url // embeddedRefs.add(ref); boolean excludeParentPath = false; // for relative paths if (ref.startsWith("..")) { ref = ref.substring(ref.lastIndexOf("..") + "..".length() + 1); excludeParentPath = true; } if (logger.isDebugEnabled()) logger.debug("parseEmbeddedContentResourceUrls After : ref : " + ref); String siteId = ToolManager.getCurrentPlacement().getContext(); if (excludeParentPath) { m.appendReplacement(sb, Matcher.quoteReplacement( m.group(1) + "=\"/access/content/group/" + siteId + "/" + ref + "\"")); embeddedRefs.add(ref); } else { m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"/access/content/group/" + siteId + Validator.escapeUrl(parentPath) + "/" + ref + "\"")); embeddedRefs.add(parentPath + "/" + ref); } } } m.appendTail(sb); return sb.toString(); }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * parse and replace emebeded references * @param message - message/*www . j a v a 2 s.c om*/ * @param embeddedRef - embedded reference * @return - modified message */ private String parseAndReplacePostTextUrls(String message, String embeddedRef) { StringBuffer sb = new StringBuffer(); Pattern p = getExportContentResourcePattern(); Matcher m = p.matcher(message); while (m.find()) { if (m.groupCount() == 3) { String ref = m.group(3); String refPathWithFolders = ref.substring(ref.indexOf("/")); String embeddedRefPathWithFolders = embeddedRef.substring("/content/group/".length()); embeddedRefPathWithFolders = embeddedRefPathWithFolders .substring(embeddedRefPathWithFolders.indexOf("/")); String siteId = ToolManager.getCurrentPlacement().getContext(); try { refPathWithFolders = URLDecoder.decode(refPathWithFolders, "UTF-8"); //This is alreaded docoded //embeddedRefPathWithFolders = URLDecoder.decode(embeddedRefPathWithFolders, "UTF-8"); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) logger.warn("parseAndReplacePostTextUrls: " + e); } if (refPathWithFolders.equalsIgnoreCase(embeddedRefPathWithFolders)) { m.appendReplacement(sb, Matcher.quoteReplacement( m.group(1) + "=\"" + "embeded_jf_content/content/group" + refPathWithFolders + "\"")); } } } m.appendTail(sb); return sb.toString(); }
From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java
/** * {@inheritDoc}//from w w w . j av a 2s . c om */ protected String translateEmbeddedReferences(String data, Collection<Translation> translations, String parentRef) { if (data == null) return data; if (translations == null) return data; // pattern to find any src= or href= text // groups: 0: the whole matching text 1: src|href 2: the string in the quotes 3: the terminator character Pattern p = Pattern.compile("(src|href)[\\s]*=[\\s]*\"([^#\"]*)([#\"])", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher m = p.matcher(data); StringBuffer sb = new StringBuffer(); // process each "harvested" string (avoiding like strings that are not in src= or href= patterns) while (m.find()) { if (m.groupCount() == 3) { String ref = m.group(2); String terminator = m.group(3); if (ref != null) ref = ref.trim(); // expand to a full reference if relative ref = adjustRelativeReference(ref, parentRef); // harvest any content hosting reference int index = ref.indexOf("/access/content/"); if (index != -1) { // except for any in /user/ or /public/ if (ref.indexOf("/access/content/user/") != -1) { index = -1; } else if (ref.indexOf("/access/content/public/") != -1) { index = -1; } } // harvest also the mneme docs references if (index == -1) index = ref.indexOf("/access/mneme/content/"); if (index != -1) { // save just the reference part (i.e. after the /access); String normal = ref.substring(index + 7); // deal with %20, &, and other encoded URL stuff normal = decodeUrl(normal); // translate the normal form String translated = normal; for (Translation translation : translations) { translated = translation.translate(translated); } // URL encode translated String escaped = EscapeRefUrl.escapeUrl(translated); // if changed, replace if (!normal.equals(translated)) { m.appendReplacement(sb, Matcher.quoteReplacement( m.group(1) + "=\"" + ref.substring(0, index + 7) + escaped + terminator)); } } } } m.appendTail(sb); return sb.toString(); }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * parse export content resource reference urls * @param message/* ww w . j ava 2 s.com*/ * - messge * @param ref * - reference * @param parentPath * - parent path * @return * - modified content */ private String parseExportContentResourceUrls(String message, String ref, String parentPath) { ref = Validator.escapeUrl(ref); // file name with spaces doesn't have %20 for spaces // get file name /*This may not be needed as spaces have %20 String fileName = ref.substring(ref.lastIndexOf("/") + 1); try { fileName = URLDecoder.decode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) logger.warn("parseExportContentResourceUrls: " + e); }*/ //ref = ref.substring(0, ref.lastIndexOf("/") + 1) + fileName; parentPath = Validator.escapeUrl(parentPath); StringBuffer sb = new StringBuffer(); Pattern p = Pattern.compile("(src|href)[\\s]*=[\\s]*[\\\"'](/access" + ref + ")[\\\"']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.UNICODE_CASE); Matcher m = p.matcher(message); while (m.find()) { if (m.groupCount() == 2) { String refMatch = m.group(2); if (parentPath == null || parentPath.trim().length() == 0) { String siteId = ToolManager.getCurrentPlacement().getContext(); refMatch = refMatch.substring(("/access/content/group/" + siteId).length() + 1); } else { if (refMatch.indexOf(parentPath) == -1) { String siteId = ToolManager.getCurrentPlacement().getContext(); refMatch = refMatch.substring(("/access/content/group/" + siteId).length() + 1); String pathRef[] = parentPath.split("/"); StringBuilder refPath = new StringBuilder(); for (int i = 0; i < (pathRef.length - 1); i++) { refPath.append("../"); } refMatch = refPath.toString() + refMatch; } else { int index = refMatch.indexOf(parentPath); refMatch = refMatch.substring(index + parentPath.length() + 1); } } /*String fileName1 = null; boolean escapeFilePath = false; try { if (logger.isDebugEnabled()) logger.debug("parseExportContentResourceUrls: refMatch :"+ refMatch); if (refMatch.lastIndexOf("/") != -1) { fileName1 = refMatch.substring(refMatch.lastIndexOf("/")+1); refMatch = refMatch.substring(0, refMatch.lastIndexOf("/")+1); if (logger.isDebugEnabled()) logger.debug("parseExportContentResourceUrls: refMatch sub string :"+ refMatch); fileName1 = URLDecoder.decode(fileName1, "UTF-8"); escapeFilePath = true; } } catch (UnsupportedEncodingException e) { if (logger.isWarnEnabled()) logger.warn("parseExportContentResourceUrls: " + e); } if (escapeFilePath) { m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1)+ "=\""+ refMatch + fileName1 +"\"")); } else m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1)+ "=\""+ refMatch + "\""));*/ m.appendReplacement(sb, Matcher.quoteReplacement(m.group(1) + "=\"" + refMatch + "\"")); } } m.appendTail(sb); return sb.toString(); }
From source file:au.org.ala.biocache.dao.SearchDAOImpl.java
/** * Format the search input query for a full-text search. * * This includes constructing a user friendly version of the query to * be used for display purposes.//ww w .java 2 s . c o m * * TODO Fix this to use a state. REVISE!! * * @param searchParams */ protected void formatSearchQuery(SpatialSearchRequestParams searchParams, boolean forceQueryFormat) { //Only format the query if it doesn't already supply a formattedQuery. if (forceQueryFormat || StringUtils.isEmpty(searchParams.getFormattedQuery())) { // set the query String query = searchParams.getQ(); //cached query parameters are already formatted if (query.contains("qid:")) { Matcher matcher = qidPattern.matcher(query); long qid = 0; while (matcher.find()) { String value = matcher.group(); try { String qidValue = SearchUtils.stripEscapedQuotes(value.substring(4)); qid = Long.parseLong(qidValue); ParamsCacheObject pco = ParamsCache.get(qid); if (pco != null) { searchParams.setQId(qid); searchParams.setQ(pco.getQ()); //add the fqs from the params cache if (pco.getFqs() != null) { String[] currentFqs = searchParams.getFq(); if (currentFqs == null || (currentFqs.length == 1 && currentFqs[0].length() == 0)) { searchParams.setFq(pco.getFqs()); } else { //we need to add the current Fqs together searchParams.setFq((String[]) ArrayUtils.addAll(currentFqs, pco.getFqs())); } } String displayString = pco.getDisplayString(); if (StringUtils.isNotEmpty(pco.getWkt())) { displayString = displayString + " within user defined polygon"; } searchParams.setDisplayString(displayString); if (searchParams instanceof SpatialSearchRequestParams) { ((SpatialSearchRequestParams) searchParams).setWkt(pco.getWkt()); } else if (StringUtils.isNotEmpty(pco.getWkt())) { String originalQ = searchParams.getQ(); searchParams.setQ(spatialField + ":\"Intersects(" + pco.getWkt() + ")"); if (StringUtils.isNotEmpty(originalQ)) searchParams.setQ(searchParams.getQ() + " AND " + originalQ); } searchParams.setFormattedQuery(searchParams.getQ()); return; } } catch (NumberFormatException e) { } catch (ParamsCacheMissingException e) { } } } StringBuffer queryString = new StringBuffer(); StringBuffer displaySb = new StringBuffer(); String displayString = query; // look for field:term sub queries and catch fields: matched_name & matched_name_children if (query.contains(":")) { // will match foo:bar, foo:"bar bash" & foo:bar\ bash Matcher matcher = termPattern.matcher(query); queryString.setLength(0); while (matcher.find()) { String value = matcher.group(); logger.debug("term query: " + value); logger.debug("groups: " + matcher.group(1) + "|" + matcher.group(2)); if ("matched_name".equals(matcher.group(1))) { // name -> accepted taxon name (taxon_name:) String field = matcher.group(1); String queryText = matcher.group(2); if (queryText != null && !queryText.isEmpty()) { String guid = speciesLookupService.getGuidForName(queryText.replaceAll("\"", "")); // strip any quotes logger.info("GUID for " + queryText + " = " + guid); if (guid != null && !guid.isEmpty()) { String acceptedName = speciesLookupService.getAcceptedNameForGuid(guid); // strip any quotes logger.info("acceptedName for " + queryText + " = " + acceptedName); if (acceptedName != null && !acceptedName.isEmpty()) { field = "taxon_name"; queryText = acceptedName; } } else { field = "taxon_name"; } // also change the display query displayString = displayString.replaceAll("matched_name", "taxon_name"); } if (StringUtils.containsAny(queryText, CHARS) && !queryText.startsWith("[")) { // quote any text that has spaces or colons but not range queries queryText = QUOTE + queryText + QUOTE; } logger.debug("queryText: " + queryText); matcher.appendReplacement(queryString, matcher.quoteReplacement(field + ":" + queryText)); } else if ("matched_name_children".equals(matcher.group(1))) { String field = matcher.group(1); String queryText = matcher.group(2); if (queryText != null && !queryText.isEmpty()) { String guid = speciesLookupService.getGuidForName(queryText.replaceAll("\"", "")); // strip any quotes logger.info("GUID for " + queryText + " = " + guid); if (guid != null && !guid.isEmpty()) { field = "lsid"; queryText = guid; } else { field = "taxon_name"; } } if (StringUtils.containsAny(queryText, CHARS) && !queryText.startsWith("[")) { // quote any text that has spaces or colons but not range queries queryText = QUOTE + queryText + QUOTE; } matcher.appendReplacement(queryString, matcher.quoteReplacement(field + ":" + queryText)); } else { matcher.appendReplacement(queryString, matcher.quoteReplacement(value)); } } matcher.appendTail(queryString); query = queryString.toString(); } //if the query string contains lsid: we will need to replace it with the corresponding lft range int last = 0; if (query.contains("lsid:")) { Matcher matcher = lsidPattern.matcher(query); queryString.setLength(0); while (matcher.find()) { //only want to process the "lsid" if it does not represent taxon_concept_lsid etc... if ((matcher.start() > 0 && query.charAt(matcher.start() - 1) != '_') || matcher.start() == 0) { String value = matcher.group(); logger.debug("preprocessing " + value); String lsid = matcher.group(2); if (lsid.contains("\"")) { //remove surrounding quotes, if present lsid = lsid.replaceAll("\"", ""); } if (lsid.contains("\\")) { //remove internal \ chars, if present //noinspection MalformedRegex lsid = lsid.replaceAll("\\\\", ""); } logger.debug("lsid = " + lsid); String[] values = searchUtils.getTaxonSearch(lsid); String lsidHeader = matcher.group(1).length() > 0 ? matcher.group(1) : ""; matcher.appendReplacement(queryString, lsidHeader + values[0]); displaySb.append(query.substring(last, matcher.start())); if (!values[1].startsWith("taxon_concept_lsid:")) displaySb.append(lsidHeader).append("<span class='lsid' id='").append(lsid).append("'>") .append(values[1]).append("</span>"); else displaySb.append(lsidHeader).append(values[1]); last = matcher.end(); //matcher.appendReplacement(displayString, values[1]); } } matcher.appendTail(queryString); displaySb.append(query.substring(last, query.length())); query = queryString.toString(); displayString = displaySb.toString(); } if (query.contains("urn")) { //escape the URN strings before escaping the rest this avoids the issue with attempting to search on a urn field Matcher matcher = urnPattern.matcher(query); queryString.setLength(0); while (matcher.find()) { String value = matcher.group(); logger.debug("escaping lsid urns " + value); matcher.appendReplacement(queryString, prepareSolrStringForReplacement(value)); } matcher.appendTail(queryString); query = queryString.toString(); } if (query.contains("Intersects")) { Matcher matcher = spatialPattern.matcher(query); if (matcher.find()) { String spatial = matcher.group(); SpatialSearchRequestParams subQuery = new SpatialSearchRequestParams(); logger.debug("region Start : " + matcher.regionStart() + " start : " + matcher.start() + " spatial length " + spatial.length() + " query length " + query.length()); //format the search query of the remaining text only subQuery.setQ(query.substring(matcher.start() + spatial.length(), query.length())); //format the remaining query formatSearchQuery(subQuery); //now append Q's together queryString.setLength(0); //need to include the prefix queryString.append(query.substring(0, matcher.start())); queryString.append(spatial); queryString.append(subQuery.getFormattedQuery()); searchParams.setFormattedQuery(queryString.toString()); //add the spatial information to the display string if (spatial.contains("circles")) { String[] values = spatial.substring(spatial.indexOf("=") + 1, spatial.indexOf("}")) .split(","); if (values.length == 3) { displaySb.setLength(0); displaySb.append(subQuery.getDisplayString()); displaySb.append(" - within ").append(values[2]).append(" km of point(") .append(values[0]).append(",").append(values[1]).append(")"); searchParams.setDisplayString(displaySb.toString()); } } else { searchParams.setDisplayString(subQuery.getDisplayString() + " - within supplied region"); } } } else { //escape reserved characters unless the colon represnts a field name colon queryString.setLength(0); Matcher matcher = spacesPattern.matcher(query); while (matcher.find()) { String value = matcher.group(); //special cases to ignore from character escaping //if the value is a single - or * it means that we don't want to escape it as it is likely to have occurred in the following situation -(occurrence_date:[* TO *]) or *:* if (!value.equals("-") && /*!value.equals("*") && !value.equals("*:*") && */ !value.endsWith("*")) { //split on the colon String[] bits = StringUtils.split(value, ":", 2); if (bits.length == 2) { if (!bits[0].contains("urn") && !bits[1].contains("urn\\")) matcher.appendReplacement(queryString, bits[0] + ":" + prepareSolrStringForReplacement(bits[1])); } else if (!value.endsWith(":")) { //need to ignore field names where the : is at the end because the pattern matching will return field_name: as a match when it has a double quoted value //default behaviour is to escape all matcher.appendReplacement(queryString, prepareSolrStringForReplacement(value)); } } } matcher.appendTail(queryString); //substitute better display strings for collection/inst etc searches if (displayString.contains("_uid")) { displaySb.setLength(0); String normalised = displayString.replaceAll("\"", ""); matcher = uidPattern.matcher(normalised); while (matcher.find()) { String newVal = "<span>" + searchUtils.getUidDisplayString(matcher.group(1), matcher.group(2)) + "</span>"; if (newVal != null) matcher.appendReplacement(displaySb, newVal); } matcher.appendTail(displaySb); displayString = displaySb.toString(); } if (searchParams.getQ().equals("*:*")) { displayString = "[all records]"; } if (searchParams.getLat() != null && searchParams.getLon() != null && searchParams.getRadius() != null) { displaySb.setLength(0); displaySb.append(displayString); displaySb.append(" - within ").append(searchParams.getRadius()).append(" km of point(") .append(searchParams.getLat()).append(",").append(searchParams.getLon()).append(")"); displayString = displaySb.toString(); } // substitute i18n version of field name, if found in messages.properties displayString = formatDisplayStringWithI18n(displayString); searchParams.setFormattedQuery(queryString.toString()); logger.debug("formattedQuery = " + queryString); logger.debug("displayString = " + displayString); searchParams.setDisplayString(displayString); } //format the fq's for facets that need ranges substituted for (int i = 0; i < searchParams.getFq().length; i++) { String fq = searchParams.getFq()[i]; String[] parts = fq.split(":", 2); //check to see if the first part is a range based query and update if necessary Map<String, String> titleMap = RangeBasedFacets.getTitleMap(parts[0]); if (titleMap != null) { searchParams.getFq()[i] = titleMap.get(parts[1]); } } } searchParams.setDisplayString(formatDisplayStringWithI18n(searchParams.getDisplayString())); }
From source file:org.sleeksnap.impl.Language.java
/** * Get a language string/*from w w w . j a v a2 s .com*/ * * @param token * The language token name * @param args * The language arguments * @return The parsed language string, or "" if null */ public static String getString(final String token, final Object... args) { String str = tokens.get(token); if (str == null) { return ""; } if (str.indexOf('{') != -1) { final Matcher m = VAR_PATTERN.matcher(str); final StringBuffer out = new StringBuffer(); while (m.find()) { final int paramIndex = Integer.parseInt(m.group(1)); if (args.length > paramIndex - 1) { m.appendReplacement(out, args[paramIndex - 1].toString()); } } m.appendTail(out); str = out.toString(); } return str; }