List of usage examples for java.util.regex Matcher reset
public Matcher reset()
From source file:org.openhab.binding.exec.internal.ExecGenericBindingProvider.java
/** * {@inheritDoc}/*from w w w . ja va 2s . com*/ */ @Override public void processBindingConfiguration(String context, Item item, String bindingConfig) throws BindingConfigParseException { super.processBindingConfiguration(context, item, bindingConfig); ExecBindingConfig config = new ExecBindingConfig(); config.itemType = item.getClass(); Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig); if (!matcher.matches()) { if (bindingConfig.startsWith("<") || bindingConfig.startsWith(">")) { throw new BindingConfigParseException("Exec binding legacy format cannot start with '<' or '>' "); } // backward compatibility for old format parseLegacyOutBindingConfig(item, bindingConfig, config); } else { matcher.reset(); while (matcher.find()) { String direction = matcher.group(1); String bindingConfigPart = matcher.group(2); if (direction.equals("<")) { config = parseInBindingConfig(item, bindingConfigPart, config); } else if (direction.equals(">")) { config = parseOutBindingConfig(item, bindingConfigPart, config); } else { throw new BindingConfigParseException( "Unknown command given! Configuration must start with '<' or '>' "); } } } addBindingConfig(item, config); }
From source file:org.xsystem.sql2.http.PageServlet2.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setHeader("Pragma", "No-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); //response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); String path = request.getPathInfo(); ErrorHandler errorHansdler = null; try (ServletOutputStream out = response.getOutputStream(); ServletInputStream input = request.getInputStream()) { try {/* ww w . j a v a2 s. co m*/ if (path == null) { loadRepository(); if (errorReport != null) { Map error = Auxilary.makeJsonError("Loading error-" + errorReport); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writeJson(error, out); } else { writeJson(Auxilary.makeJsonSuccess(), out); } return; } if (errorReport != null) { Map error = Auxilary.makeJsonError("Loading error-" + errorReport); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writeJson(error, out); return; } Config cofig = getConfig(); errorHansdler = cofig.getErrorHandler(); Matcher matcher = Pattern.compile("").matcher(path); List<ActionExecuter> lstActions = cofig.getActions(); Optional<ActionExecuter> opt = lstActions.stream() .filter(action -> matcher.reset().usePattern(action.getPattern()).find()).findFirst(); if (opt.isPresent()) { ActionExecuter action = opt.get(); List groups = HttpHelper.getGroups(matcher); Map params = Collections.emptyMap(); Object json = Collections.emptyMap(); Long skip = null; Integer total = null; if (action.isMultipart()) { json = HttpHelper.getMultipartJson(request); } else { params = HttpHelper.getParams(request); skip = HttpHelper.getParamSkip(request); total = HttpHelper.getParamTotal(request); if (!action.isForm()) { json = getJson(input); } } Map<String, Object> context = Auxilary.newMap("groups", groups, "params", params, "json", json, "request", request); Map<String, String> evals = action.getContextParams(); FileFormat fileFormat = action.getFileFormat(); int thumb = HttpHelper.getThumb(fileFormat, context); context = getContext(evals, context); if (skip != null) { context.put("skip", skip); } if (total != null) { context.put("total", total); } Object rezult = execute(request, cofig, action, context); if (fileFormat == null) { writeJson(Auxilary.makeJsonSuccess("data", rezult), out); } else { FileTransfer fileTransfer = HttpHelper.getFileTransfer(fileFormat, rezult, (format, data) -> { return getContent(format, data, "defualt"); }); if (fileTransfer == null && !fileFormat.isDownload() && !Auxilary.isEmptyOrNull(fileFormat.getNotfound())) { String fname = fileFormat.getNotfound(); if (fname.startsWith(FILEPRFX)) { fname = fname.substring(FILEPRFX.length()); fname = config.getServletContext().getRealPath(fname); File f = new File(fname); if (f.exists()) { fileTransfer = new FileTransfer(); String contentType = Files.probeContentType(Paths.get(fname)); String fileType = Auxilary.getFileExtention(fname); byte[] b = Auxilary.readBinaryFile(f); fileTransfer.setContentType(contentType); fileTransfer.setFileType(fileType); fileTransfer.setData(b); } } } if (fileTransfer == null) { Map error = Auxilary.makeJsonError("File not found "); response.setStatus(HttpServletResponse.SC_NOT_FOUND); writeJson(error, out); } else { boolean isDownload = fileFormat.isDownload(); HttpHelper.writeFile(fileTransfer, isDownload, thumb, request, response, out); } } } else { Map error = Auxilary.makeJsonError("Page not found [" + path + "]"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); writeJson(error, out); } } catch (Throwable err) { // response.setStatus(); if (errorHansdler == null) { error(err, out); } else { Object error = errorHansdler.handler(err); writeJson(error, out); } } } }
From source file:org.openhab.persistence.mysql.internal.MysqlPersistenceService.java
/** * Initialise the type array/* ww w . j a v a 2 s . c om*/ * If other Types like DOUBLE or INT needed for serialisation it can be set in openhab.cfg */ public void activate(final BundleContext bundleContext, final Map<String, Object> config) { sqlTypes.put("CALLITEM", "VARCHAR(200)"); sqlTypes.put("COLORITEM", "VARCHAR(70)"); sqlTypes.put("CONTACTITEM", "VARCHAR(6)"); sqlTypes.put("DATETIMEITEM", "DATETIME"); sqlTypes.put("DIMMERITEM", "TINYINT"); sqlTypes.put("LOCATIONITEM", "VARCHAR(30)"); sqlTypes.put("NUMBERITEM", "DOUBLE"); sqlTypes.put("ROLLERSHUTTERITEM", "TINYINT"); sqlTypes.put("STRINGITEM", "VARCHAR(20000)"); sqlTypes.put("SWITCHITEM", "CHAR(3)"); Iterator<String> keys = config.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { continue; } matcher.reset(); matcher.find(); if (!matcher.group(1).equals("sqltype")) continue; String itemType = matcher.group(2).toUpperCase() + "ITEM"; String value = (String) config.get(key); sqlTypes.put(itemType, value); } url = (String) config.get("url"); if (StringUtils.isBlank(url)) { logger.warn("The SQL database URL is missing - please configure the sql:url parameter in openhab.cfg"); } user = (String) config.get("user"); if (StringUtils.isBlank(user)) { logger.warn("The SQL user is missing - please configure the sql:user parameter in openhab.cfg"); } password = (String) config.get("password"); if (StringUtils.isBlank(password)) { logger.warn( "The SQL password is missing. Attempting to connect without password. To specify a password configure the sql:password parameter in openhab.cfg."); } String tmpString = (String) config.get("reconnectCnt"); if (StringUtils.isNotBlank(tmpString)) { errReconnectThreshold = Integer.parseInt(tmpString); } tmpString = (String) config.get("waitTimeout"); if (StringUtils.isNotBlank(tmpString)) { waitTimeout = Integer.parseInt(tmpString); } // reconnect to the database in case the configuration has changed. disconnectFromDatabase(); connectToDatabase(); // connection has been established ... initialization completed! initialized = true; logger.debug("mySQL configuration complete."); }
From source file:org.openhab.binding.http.internal.HttpBinding.java
/** * {@inheritDoc}/*from ww w. j a va2 s . c o m*/ */ @SuppressWarnings("rawtypes") public void updated(Dictionary config) throws ConfigurationException { synchronized (itemCacheLock) { // clear any existing cache item configs itemCache.clear(); if (config != null) { String timeoutString = (String) config.get(CONFIG_TIMEOUT); if (StringUtils.isNotBlank(timeoutString)) { timeout = Integer.parseInt(timeoutString); } String granularityString = (String) config.get(CONFIG_GRANULARITY); if (StringUtils.isNotBlank(granularityString)) { granularity = Integer.parseInt(granularityString); } // Parse page cache config @SuppressWarnings("unchecked") 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 (CONFIG_TIMEOUT.equals(key) || CONFIG_GRANULARITY.equals(key) || "service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_CACHE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("given config key '" + key + "' does not follow the expected pattern '<id>.<url|updateInterval>'"); continue; } matcher.reset(); matcher.find(); String cacheId = matcher.group(1); CacheConfig cacheConfig = itemCache.get(cacheId); if (cacheConfig == null) { cacheConfig = new CacheConfig(cacheId); itemCache.put(cacheId, cacheConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("url".equals(configKey)) { matcher = EXTRACT_CACHE_CONFIG_URL.matcher(value); if (!matcher.matches()) { throw new ConfigurationException(configKey, "given config url '" + configKey + "' does not follow the expected pattern '<id>.url[{<headers>}]'"); } cacheConfig.url = matcher.group(1); cacheConfig.headers = parseHttpHeaders(matcher.group(2)); } else if ("updateInterval".equals(configKey)) { cacheConfig.updateInterval = Integer.valueOf(value); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } } } }
From source file:org.openhab.binding.pulseaudio.internal.PulseaudioBinding.java
@SuppressWarnings("rawtypes") public void updated(Dictionary<String, ?> 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; }//ww w. j a va 2s.c o m Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given pulseaudio-config-key '" + key + "' does not follow the expected pattern '<serverId>.<host|port>'"); continue; } matcher.reset(); matcher.find(); String serverId = matcher.group(1); PulseaudioServerConfig serverConfig = serverConfigCache.get(serverId); if (serverConfig == null) { serverConfig = new PulseaudioServerConfig(); serverConfigCache.put(serverId, serverConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("host".equals(configKey)) { serverConfig.host = value; } else if ("port".equals(configKey)) { serverConfig.port = Integer.valueOf(value); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } connectAllPulseaudioServers(); } }
From source file:net.antoinecomte.regex.RegExTesterApplication.java
private void showResult(String regexValue, String textValue) { Matcher matcher; try {/* w ww . j a v a 2s. com*/ result.setVisible(!"".equals(regexValue)); Label match = new Label("no match"); match.addStyleName("h3 color"); result.removeAllComponents(); result.addComponent(match); matcher = Pattern.compile(regexValue).matcher(textValue); if (matcher.matches()) { if (matcher.groupCount() > 0) for (int i = 1; i <= matcher.groupCount(); i++) { Label g = new Label("group " + i + " = " + matcher.group(i)); g.addStyleName("h3 color"); g.setSizeUndefined(); result.addComponent(g); } match.setValue("match"); } matcher.reset(); if (matcher.find()) { Label findresult = new Label("find=true, start = " + matcher.start() + " end = " + matcher.end()); findresult.addStyleName("h3 color"); result.addComponent(findresult); } Label javaString = new Label("java string : \"" + StringEscapeUtils.escapeJava(regexValue) + "\""); javaString.addStyleName("small color"); result.addComponent(javaString); } catch (Exception e) { result.removeAllComponents(); Label error = new Label(e.getMessage()); error.addStyleName("error"); result.addComponent(error); } }
From source file:org.openhab.binding.plugwise.internal.PlugwiseBinding.java
@SuppressWarnings("rawtypes") @Override// w ww . j a va 2 s .c o m public void updated(Dictionary config) throws ConfigurationException { if (config != null) { // First of all make sure the Stick gets set up 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_PLUGWISE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("given plugwise-config-key '" + key + "' does not follow the expected pattern '<PlugwiseId>.<mac|port|interval>'"); continue; } matcher.reset(); matcher.find(); String plugwiseID = matcher.group(1); if (plugwiseID.equals("stick")) { if (stick == null) { String configKey = matcher.group(2); String value = (String) config.get(key); if ("port".equals(configKey)) { stick = new Stick(value, this); logger.info("Plugwise added Stick connected to serial port {}", value); } else if ("interval".equals(configKey)) { // do nothing for now. we will set in the second run } else if ("retries".equals(configKey)) { // do nothing for now. we will set in the second run } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } } } if (stick != null) { // re-run through the configuration and setup the remaining devices 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_PLUGWISE_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.error("given plugwise-config-key '" + key + "' does not follow the expected pattern '<PlugwiseId>.<mac|port>'"); continue; } matcher.reset(); matcher.find(); String plugwiseID = matcher.group(1); if (plugwiseID.equals("stick")) { String configKey = matcher.group(2); String value = (String) config.get(key); if ("interval".equals(configKey)) { stick.setInterval(Integer.valueOf(value)); logger.info("Setting the interval to send ZigBee PDUs to {} ms", value); } else if ("retries".equals(configKey)) { stick.setRetries(Integer.valueOf(value)); logger.info("Setting the maximum number of attempts to send a message to ", value); } else if ("port".equals(configKey)) { //ignore } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } PlugwiseDevice device = stick.getDeviceByName(plugwiseID); if (device == null && !plugwiseID.equals("stick")) { String configKey = matcher.group(2); String value = (String) config.get(key); String MAC = null; if ("mac".equals(configKey)) { MAC = value; } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } if (!MAC.equals("")) { if (plugwiseID.equals("circleplus")) { if (stick.getDeviceByMAC(MAC) == null) { device = new CirclePlus(MAC, stick); logger.info("Plugwise added Circle+ with MAC address: {}", MAC); } } else { if (stick.getDeviceByMAC(MAC) == null) { device = new Circle(MAC, stick, plugwiseID); logger.info("Plugwise added Circle with MAC address: {}", MAC); } } stick.plugwiseDeviceCache.add(device); } } } setProperlyConfigured(true); } else { logger.error("Plugwise needs at least one Stick in order to operate"); } } }
From source file:org.openhab.binding.epsonprojector.internal.EpsonProjectorBinding.java
/** * @{inheritDoc/*from w w w. j a va 2s .co m*/ */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Configuration updated, config {}", config != null ? true : false); if (config != null) { if (deviceConfigCache == null) { deviceConfigCache = new HashMap<String, DeviceConfig>(); } String granularityString = (String) config.get("granularity"); if (StringUtils.isNotBlank(granularityString)) { granularity = Integer.parseInt(granularityString); } 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_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.warn("given config key '" + key + "' does not follow the expected pattern '<id>.<host|port>'"); continue; } matcher.reset(); matcher.find(); String deviceId = matcher.group(1); DeviceConfig deviceConfig = deviceConfigCache.get(deviceId); if (deviceConfig == null) { logger.debug("Added new device {}", deviceId); deviceConfig = new DeviceConfig(deviceId); deviceConfigCache.put(deviceId, deviceConfig); } String configKey = matcher.group(2); String value = (String) config.get(key); if ("serialPort".equals(configKey)) { deviceConfig.serialPort = value; } else if ("host".equals(configKey)) { deviceConfig.host = value; } else if ("port".equals(configKey)) { deviceConfig.port = Integer.valueOf(value); } else { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } setProperlyConfigured(true); } }
From source file:com.novartis.opensource.yada.plugin.Gatekeeper.java
/** * Modifies the original query by appending a dynamic predicate * <p>Recall the {@link Service#engagePreprocess} method * will recall {@link QueryManager#endowQuery} to * reconform the code after this {@link Preprocess} * disengages.//from www.j a v a2s . co m * * * @throws YADASecurityException when token retrieval fails */ @Override public void applyContentPolicy() throws YADASecurityException { // TODO make it impossible to reset args and preargs dynamically if pl class implements SecurityPolicy // this will close an attack vector String SPACE = " "; StringBuilder contentPolicy = new StringBuilder(); Pattern rxInjection = Pattern.compile(RX_COL_INJECTION); String rawPolicy = getArgumentValue(CONTENT_POLICY_PREDICATE); Matcher m1 = rxInjection.matcher(rawPolicy); int start = 0; // field = getToken // field = getCookie(string) // field = getHeader(string) // field = getUser() // field = getRandom(string) if (!m1.find()) { String msg = "Unathorized. Injected method invocation failed."; throw new YADASecurityException(msg); } m1.reset(); while (m1.find()) { int rxStart = m1.start(); int rxEnd = m1.end(); contentPolicy.append(rawPolicy.substring(start, rxStart)); String frag = rawPolicy.substring(rxStart, rxEnd); String method = frag.substring(0, frag.indexOf('(')); String arg = frag.substring(frag.indexOf('(') + 1, frag.indexOf(')')); Object val = null; try { if (arg.equals("")) val = getClass().getMethod(method).invoke(this, new Object[] {}); else val = getClass().getMethod(method, new Class[] { java.lang.String.class }).invoke(this, new Object[] { arg }); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { String msg = "Unathorized. Injected method invocation failed."; throw new YADASecurityException(msg, e); } contentPolicy.append((String) val + SPACE); start = rxEnd; } Expression parsedContentPolicy; try { parsedContentPolicy = CCJSqlParserUtil.parseCondExpression(contentPolicy.toString()); } catch (JSQLParserException e) { String msg = "Unauthorized. Content policy is not valid."; throw new YADASecurityException(msg, e); } PlainSelect sql = (PlainSelect) ((Select) getYADAQuery().getStatement()).getSelectBody(); Expression where = sql.getWhere(); if (where != null) { AndExpression and = new AndExpression(where, parsedContentPolicy); sql.setWhere(and); } else { sql.setWhere(parsedContentPolicy); } try { CCJSqlParserManager parserManager = new CCJSqlParserManager(); sql = (PlainSelect) ((Select) parserManager.parse(new StringReader(sql.toString()))).getSelectBody(); } catch (JSQLParserException e) { String msg = "Unauthorized. Content policy is not valid."; throw new YADASecurityException(msg, e); } getYADAQuery().setCoreCode(sql.toString()); this.clearSecurityPolicy(); }
From source file:org.openhab.binding.modbus.internal.ModbusConfiguration.java
@Override @SuppressWarnings("rawtypes") public void updated(Dictionary config) throws ConfigurationException { // remove all known items if configuration changed Collections.synchronizedMap(modbusSlaves).clear(); 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 ww w . j av a 2 s . c om Matcher matcher = EXTRACT_MODBUS_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { if ("poll".equals(key)) { poll = 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 '" + key + "' does not follow the expected pattern 'poll' or '<slaveId>.<connection|id|start|length|type>'"); } continue; } matcher.reset(); matcher.find(); String slave = matcher.group(2); ModbusSlave modbusSlave = Collections.synchronizedMap(modbusSlaves).get(slave); if (modbusSlave == null) { if (matcher.group(1).equals(TCP_PREFIX)) { modbusSlave = new ModbusTcpSlave(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"); Collections.synchronizedMap(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 ModbusTcpSlave) { ((ModbusTcpSlave) modbusSlave).setHost(chunks[0]); if (chunks.length == 2) { ((ModbusTcpSlave) modbusSlave).setPort(Integer.valueOf(chunks[1])); } } else if (modbusSlave instanceof ModbusSerialSlave) { ((ModbusSerialSlave) modbusSlave).setPort(chunks[0]); if (chunks.length == 2) { ((ModbusSerialSlave) modbusSlave).setBaud(Integer.valueOf(chunks[1])); } } } 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 { throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown"); } } } // connect instances to modbus slaves for (ModbusSlave slave : Collections.synchronizedMap(modbusSlaves).values()) { slave.connect(); } }