List of usage examples for java.util.regex Matcher reset
public Matcher reset()
From source file:fr.paris.lutece.plugins.extend.service.content.ExtendableContentPostProcessor.java
/** * {@inheritDoc}// w ww . jav a 2s . co m */ @Override public String process(HttpServletRequest request, String strContent) { String strHtmlContent = strContent; // Check if the process is carried out in client or server side boolean bClientSide = Boolean.valueOf(AppPropertiesService.getProperty(PROPERTY_CLIENT_SIDE, "false")); if (bClientSide) { // CLIENT SIDE int nPos = strHtmlContent.indexOf(END_BODY); if (nPos < 0) { AppLogService.error("ExtendableContentPostProcessor Service : no BODY end tag found"); return strHtmlContent; } Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_BASE_URL, AppPathService.getBaseUrl(request)); model.put(MARK_REGEX_PATTERN, _strRegexPattern); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_CONTENT_POST_PROCESSOR, request.getLocale(), model); StringBuilder sb = new StringBuilder(); sb.append(strHtmlContent.substring(0, nPos)); sb.append(template.getHtml()); sb.append(strHtmlContent.substring(nPos)); strHtmlContent = sb.toString(); } else { // SERVER SIDE /** * Replace all makers @Extender[<idResource>,<resourceType>,<extenderType>,<params>]@ to * the correct HTML content of the extender. * 1) First parse the content of the markers * 2) Get all information (idResource, resourceType, extenderType, params) * 3) Get the html content from the given information * 4) Replace the markers by the html content */ // 1) First parse the content of the markers Matcher match = _regexPattern.matcher(strHtmlContent); Matcher parameterMatch = null; StringBuffer strResultHTML = new StringBuffer(strHtmlContent.length()); while (match.find()) { String strMarker = match.group(); // 2) Get all information (idResource, resourceType, extenderType, params) ResourceExtenderDTO resourceExtender = _mapper.map(match.group(1)); boolean bParameteredId = StringUtils.equalsIgnoreCase(resourceExtender.getIdExtendableResource(), EXTEND_PARAMETERED_ID); if (bParameteredId) { if (parameterMatch == null) { parameterMatch = _extendedParameterRegexPattern.matcher(strHtmlContent); } else { parameterMatch.reset(); } while (parameterMatch.find()) { ResourceExtenderDTO realResourceExtender = _mapper.map(parameterMatch.group(1)); if (StringUtils.equals(realResourceExtender.getExtendableResourceType(), resourceExtender.getExtendableResourceType()) && StringUtils.equals(realResourceExtender.getExtenderType(), resourceExtender.getExtenderType())) { resourceExtender .setIdExtendableResource(realResourceExtender.getIdExtendableResource()); break; } } } String strHtml = StringUtils.EMPTY; if (!bParameteredId || !StringUtils.equalsIgnoreCase(resourceExtender.getIdExtendableResource(), EXTEND_PARAMETERED_ID)) { // 3) Get the html content from the given information if (!StringUtils.equals(resourceExtender.getExtendableResourceType(), Page.RESOURCE_TYPE) || (StringUtils.isBlank(request.getParameter(PARAM_PAGE)) && StringUtils.isBlank(request.getParameter(PARAM_PORTLET_ID)))) { strHtml = _extenderService.getContent(resourceExtender.getIdExtendableResource(), resourceExtender.getExtendableResourceType(), resourceExtender.getExtenderType(), resourceExtender.getParameters(), request); } } // 4) Replace the markers by the html content match.appendReplacement(strResultHTML, Matcher.quoteReplacement(strHtml)); } match.appendTail(strResultHTML); strHtmlContent = strResultHTML.toString(); } if (StringUtils.isNotBlank(_strExtenderParameterRegexPattern)) { strHtmlContent = _extendedParameterRegexPattern.matcher(strHtmlContent).replaceAll(""); } return strHtmlContent; }
From source file:com.timrae.rikaidroid.MainActivity.java
/** * Add the reading to the kanji as Ruby furigana, ensuring that there is only furigana above * the kanji, not above any hiragana included in the word. * @param kanji a word in kanji//w w w .ja v a 2 s.c o m * @param reading the hiragana reading for the word * @return a String with the reading correctly added to the kanji as Ruby */ private String makeFurigana(String kanji, String reading) { Matcher kanaMatcher = KANA_REGEXP.matcher(kanji); // All characeters are kanji; simple replacement will work if (!kanaMatcher.find()) { return String.format(RUBY, kanji, reading); } // Strip off any kana from the beginning of the word StringBuilder output = new StringBuilder(); if (kanaMatcher.start() == 0) { String prefix = kanaMatcher.group(); kanji = kanji.substring(prefix.length()); reading = reading.substring(prefix.length()); output.append(prefix); kanaMatcher = KANA_REGEXP.matcher(kanji); } else { kanaMatcher.reset(); } // Keep track of number of kana added to output to see if the algorithm was successful int numKana = output.length(); // Now step through each kanji int lastKanaEnd = 0; int lastReadingKanaEnd = 0; while (kanaMatcher.find()) { // Find the next kana in the kanji string int kanaStart = kanaMatcher.start(); String currentKana = kanaMatcher.group(); // Extract the kanji in-between the current kana and the previous kana String currentKanji = kanji.substring(lastKanaEnd, kanaStart); // Set the end index of current kana in kanji string for next loop iteration lastKanaEnd = kanaMatcher.end(); // Find the current kana in the reading string // Not perfect. Here we take the first occurrence at least number of kanji after the last kana int readingKanaStart = reading.indexOf(currentKana, lastReadingKanaEnd + currentKanji.length()); // Extract the reading in-between the kana found in the kanji this time and last time String currentReading = reading.substring(lastReadingKanaEnd, readingKanaStart); // Set the end index of current kana in reading string for next loop iteration lastReadingKanaEnd = readingKanaStart + currentKana.length(); // Append current kanji and reading to the StringBuilder as furigana output.append(String.format(RUBY, currentKanji, currentReading)); // Append the current kana to the StringBuilder (outside the furigana) output.append(currentKana); // Keep track of number of kana addded to see if the algorithm was successful numKana += currentReading.length() + currentKana.length(); } // Add any kanji / reading at the end of the string to the builder if (lastKanaEnd < kanji.length()) { String currentKanji = kanji.substring(lastKanaEnd + 1); String currentReading = reading.substring(lastReadingKanaEnd + 1); output.append(String.format(RUBY, currentKanji, currentReading)); numKana += currentReading.length(); } // Do sanity check, returning naiive substitution if it failed if (numKana < reading.length()) { return String.format(RUBY, kanji, reading); } return output.toString().trim(); }
From source file:org.openhab.binding.mpd.internal.MpdBinding.java
@SuppressWarnings("rawtypes") public void updated(Dictionary config) throws ConfigurationException { if (config != null) { disconnectPlayersAndMonitors();/* w w w. ja v a 2 s . co m*/ cancelScheduler(); Enumeration keys = config.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_PLAYER_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given mpd player-config-key '" + key + "' does not follow the expected pattern '<playername>.<host|port>'"); continue; } matcher.reset(); matcher.find(); String playerId = matcher.group(1); MpdPlayerConfig playerConfig = playerConfigCache.get(playerId); if (playerConfig == null) { playerConfig = new MpdPlayerConfig(); playerConfigCache.put(playerId, playerConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("host".equals(configKey)) { playerConfig.host = value; } else if ("port".equals(configKey)) { playerConfig.port = Integer.valueOf(value); } else if ("password".equals(configKey)) { playerConfig.password = value; } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } connectAllPlayersAndMonitors(); scheduleReconnect(); } }
From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java
private void maskSensitiveInfo(EsbMessage em, EsbMessageEntity eme) { em.setPayload(em.getPayload().replaceAll("\n", "")); em.setPayload(em.getPayload().replaceAll("\r", "")); em.setPayload(em.getPayload().replaceAll("\t", "")); em.setPayload(em.getPayload().replaceAll(">\\s*<", "><")); Map<String, String> matchedConfiguration = matchCriteria(em, getPartiallyViewableMessages()); if (matchedConfiguration != null) { String parentTag = matchedConfiguration.get("sensitiveTag"); Pattern pattern = Pattern .compile("<(" + parentTag + ")>((?!<(" + parentTag + ")>).)*</(" + parentTag + ")>"); Matcher matcher = pattern.matcher(em.getPayload()); List<String> sensitiveInformation = new ArrayList<>(); while (matcher.find()) { sensitiveInformation.add(matcher.group(0)); }//from www .ja v a 2s . c o m matcher.reset(); String maskedText = matcher.replaceAll("<$1>" + matchedConfiguration.get("replacementText") + "</$1>"); eme.setErrorSensitiveInfo( ConversionUtility.convertToEsbMessageSensitiveInfo(getEncryptor(), eme, sensitiveInformation)); eme.setPayload(maskedText); } }
From source file:org.kuali.rice.krad.demo.uif.components.ComponentLibraryView.java
/** * Translates the source by removing chracters that the dom will misinterpret as html and to ensure * source spacing is correct// w ww. j a v a2 s .c o m * * @param source the original source * @return that translated source used in the SyntaxHighlighter of the exhibit */ private String translateSource(String source) { //convert characters to ascii equivalent source = source.replace("<", "<"); source = source.replace(">", ">"); source = source.replaceAll("[ \\t]", " "); Pattern linePattern = Pattern.compile("(( )*).*?(\\n)+"); Matcher matcher = linePattern.matcher(source); int toRemove = -1; //find the line with the least amount of spaces while (matcher.find()) { String spaces = matcher.group(1); int count = StringUtils.countMatches(spaces, " "); if (toRemove == -1 || count < toRemove) { toRemove = count; } } matcher.reset(); String newSource = ""; //remove the min number of spaces from each line to get them to align left properly in the viewer while (matcher.find()) { String line = matcher.group(); newSource = newSource + line.replaceFirst("( ){" + toRemove + "}", ""); } //remove very last newline newSource = newSource.replaceAll("\\n$", ""); //replace remaining newlines with ascii equivalent newSource = newSource.replace("\n", "
"); return newSource; }
From source file:org.jbosson.plugins.amq.ArtemisMBeanDiscoveryComponent.java
protected static String formatMessage(String messageTemplate, Map<String, String> variableValues) { StringBuffer result = new StringBuffer(); // collect keys and values to determine value size limit if needed final Map<String, String> replaceMap = new HashMap<String, String>(); final Matcher matcher = PROPERTY_NAME_PATTERN.matcher(messageTemplate); int count = 0; while (matcher.find()) { final String key = matcher.group(1); final String value = variableValues.get(key); if (value != null) { replaceMap.put(key, value);/*from www . j a v a 2 s . com*/ matcher.appendReplacement(result, Matcher.quoteReplacement(value)); } else { matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); } count++; } matcher.appendTail(result); // check if the result exceeds MAX_LENGTH for formatted properties if (!replaceMap.isEmpty() && result.length() > MAX_LENGTH) { // sort values according to size final SortedSet<String> values = new TreeSet<String>(new Comparator<String>() { public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); values.addAll(replaceMap.values()); // find total value characters allowed int available = MAX_LENGTH - PROPERTY_NAME_PATTERN.matcher(messageTemplate).replaceAll("").length(); // fit values from small to large in the allowed size to determine the maximum average int averageLength = available / count; for (String value : values) { final int length = value.length(); if (length > averageLength) { break; } available -= length; count--; averageLength = available / count; } // replace values matcher.reset(); result.delete(0, result.length()); while (matcher.find()) { String value = replaceMap.get(matcher.group(1)); if (value != null && value.length() > averageLength) { value = value.substring(0, averageLength); } matcher.appendReplacement(result, value != null ? value : matcher.group()); } matcher.appendTail(result); } return result.toString(); }
From source file:org.openhab.binding.modbus.internal.ModbusBinding.java
@Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { // remove all known items if configuration changed modbusSlaves.clear();//from w w w. ja v a 2s . c om if (config != null) { Enumeration<String> keys = config.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_MODBUS_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { if ("poll".equals(key)) { if (StringUtils.isNotBlank((String) config.get(key))) { pollInterval = Integer.valueOf((String) config.get(key)); } } else if ("writemultipleregisters".equals(key)) { ModbusSlave.setWriteMultipleRegisters(Boolean.valueOf(config.get(key).toString())); } else { logger.debug( "given modbus-slave-config-key '{}' does not follow the expected pattern or 'serial.<slaveId>.<{}>'", key, VALID_COFIG_KEYS); } continue; } matcher.reset(); matcher.find(); String slave = matcher.group(2); ModbusSlave modbusSlave = modbusSlaves.get(slave); if (modbusSlave == null) { if (matcher.group(1).equals(TCP_PREFIX)) { modbusSlave = new ModbusTcpSlave(slave); } else if (matcher.group(1).equals(UDP_PREFIX)) { modbusSlave = new ModbusUdpSlave(slave); } else if (matcher.group(1).equals(SERIAL_PREFIX)) { modbusSlave = new ModbusSerialSlave(slave); } else { throw new ConfigurationException(slave, "the given slave type '" + slave + "' is unknown"); } logger.debug("modbusSlave '{}' instanciated", slave); modbusSlaves.put(slave, modbusSlave); } String configKey = matcher.group(3); String value = (String) config.get(key); if ("connection".equals(configKey)) { String[] chunks = value.split(":"); if (modbusSlave instanceof ModbusIPSlave) { // expecting: // <devicePort>:<port> ((ModbusIPSlave) modbusSlave).setHost(chunks[0]); if (chunks.length == 2) { ((ModbusIPSlave) modbusSlave).setPort(Integer.valueOf(chunks[1])); } } else if (modbusSlave instanceof ModbusSerialSlave) { // expecting: // <devicePort>[:<baudRate>:<dataBits>:<parity>:<stopBits>:<encoding>] ((ModbusSerialSlave) modbusSlave).setPort(chunks[0]); if (chunks.length >= 2) { ((ModbusSerialSlave) modbusSlave).setBaud(Integer.valueOf(chunks[1])); } if (chunks.length >= 3) { ((ModbusSerialSlave) modbusSlave).setDatabits(Integer.valueOf(chunks[2])); } if (chunks.length >= 4) { ((ModbusSerialSlave) modbusSlave).setParity(chunks[3]); } if (chunks.length >= 5) { ((ModbusSerialSlave) modbusSlave).setStopbits(Double.valueOf(chunks[4])); } if (chunks.length == 6) { ((ModbusSerialSlave) modbusSlave).setEncoding(chunks[5]); } } } else if ("start".equals(configKey)) { modbusSlave.setStart(Integer.valueOf(value)); } else if ("length".equals(configKey)) { modbusSlave.setLength(Integer.valueOf(value)); } else if ("id".equals(configKey)) { modbusSlave.setId(Integer.valueOf(value)); } else if ("type".equals(configKey)) { if (ArrayUtils.contains(ModbusBindingProvider.SLAVE_DATA_TYPES, value)) { modbusSlave.setType(value); } else { throw new ConfigurationException(configKey, "the given slave type '" + value + "' is invalid"); } } else if ("valuetype".equals(configKey)) { if (ArrayUtils.contains(ModbusBindingProvider.VALUE_TYPES, value)) { modbusSlave.setValueType(value); } else { throw new ConfigurationException(configKey, "the given value type '" + value + "' is invalid"); } } else if ("rawdatamultiplier".equals(configKey)) { modbusSlave.setRawDataMultiplier(Double.valueOf(value.toString())); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } logger.debug("config looked good, proceeding with slave-connections"); // connect instances to modbus slaves for (ModbusSlave slave : modbusSlaves.values()) { slave.connect(); } setProperlyConfigured(true); } }
From source file:org.openhab.binding.atlona.internal.pro3.AtlonaPro3PortocolHandler.java
/** * Handles the port output response. This matcher can have multiple groups separated by commas. Find each group and * that group should have two groups within - an input port nbr and an output port number * * @param m the non-null {@link Matcher} that matched the response * @param resp the possibly null, possibly empty actual response *//*from www . j a v a 2s . co m*/ private void handlePortOutputResponse(Matcher m, String resp) { if (m == null) { throw new IllegalArgumentException("m (matcher) cannot be null"); } m.reset(); while (m.find()) { try { int inPort = Integer.parseInt(m.group(1)); int outPort = Integer.parseInt(m.group(2)); _callback.stateChanged(AtlonaPro3Utilities.createChannelID(AtlonaPro3Constants.GROUP_PORT, outPort, AtlonaPro3Constants.CHANNEL_PORTOUTPUT), new DecimalType(inPort)); } catch (NumberFormatException e) { logger.warn("Invalid port output response (can't parse number): '{}'", resp); } } }
From source file:org.openhab.binding.sonos.internal.SonosBinding.java
@SuppressWarnings("rawtypes") public void updated(Dictionary config) throws ConfigurationException { if (config != null) { Enumeration keys = config.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); // the config-key enumeration contains additional keys that we // don't want to process here ... if ("service.pid".equals(key)) { continue; }//from w w w.j av a 2 s. com if ("pollingPeriod".equals(key)) { pollingPeriod = Integer.parseInt((String) config.get(key)); logger.debug("Setting polling period to {} ms", pollingPeriod); continue; } Matcher matcher = EXTRACT_SONOS_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given sonos-config-key '" + key + "' does not follow the expected pattern '<sonosId>.<udn>'"); continue; } matcher.reset(); matcher.find(); String sonosID = matcher.group(1); SonosZonePlayer sonosConfig = sonosZonePlayerCache.getById(sonosID); if (sonosConfig == null) { sonosConfig = new SonosZonePlayer(sonosID, self); sonosZonePlayerCache.add(sonosConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("udn".equals(configKey)) { sonosConfig.setUdn(new UDN(value)); logger.debug("Add predefined Sonos device with UDN {}", sonosConfig.getUdn()); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } } setProperlyConfigured(true); }