List of usage examples for java.util.regex Matcher start
public int start()
From source file:com.nextep.datadesigner.sqlgen.impl.DBErrorsMarkerProvider.java
private synchronized void recompileAndLoadMarkers() { if (!isValidated()) { final ICoreFactory coreFactory = CorePlugin.getService(ICoreFactory.class); // Resetting markers markersMap = new MultiValueMap(); // Fetching for all connections final ITargetSet targetSet = VCSPlugin.getViewService().getCurrentViewTargets(); if (targetSet != null) { final ICaptureService captureService = SQLGenPlugin.getService(ICaptureService.class); final IConnectionService connectionService = SQLGenPlugin.getService(IConnectionService.class); final Collection<IConnection> connections = targetSet.getTarget(SQLGenUtil.getDefaultTargetType()); for (IConnection dbConn : connections) { Connection jdbcConn = null; Statement stmt = null; try { jdbcConn = connectionService.connect(dbConn); stmt = jdbcConn.createStatement(); // Recompiling first stmt.execute("BEGIN DBMS_UTILITY.COMPILE_SCHEMA(USER, FALSE); END;"); //$NON-NLS-1$ // Fetching errors } catch (SQLException e) { markersMap.put(dbConn, coreFactory.createMarker(dbConn, MarkerType.ERROR, "Connection failed: " + e.getMessage())); // Setting up a timeout before retrying validationTimeout = System.currentTimeMillis() + 120000; } finally { CaptureHelper.safeClose(null, stmt); if (jdbcConn != null) { try { jdbcConn.close(); } catch (SQLException e) { LOGGER.error("Unable to close connection", e); }//from w w w .j av a2 s. c om } } final Collection<ErrorInfo> errors = captureService.getErrorsFromDatabase(dbConn, new NullProgressMonitor()); // Hashing current view contents by name Map<String, ITypedObject> objMap = hashCurrentViewByName(); for (ErrorInfo i : errors) { final ITypedObject o = objMap.get(i.getObjectName()); IMarker m = coreFactory.createMarker(o, "ERROR".equals(i.getAttribute()) ? MarkerType.ERROR //$NON-NLS-1$ : MarkerType.WARNING, i.getErrorMessage()); m.setAttribute(IMarker.ATTR_LINE, i.getLine()); m.setAttribute(IMarker.ATTR_COL, i.getCol()); // Specific quick'n dirty fix for Triggers if (o != null && o.getType() == IElementType.getInstance(ITrigger.TYPE_ID)) { final ITrigger trg = (ITrigger) o; if (trg.isCustom()) { Pattern pat = Pattern.compile("(DECLARE|BEGIN)"); //$NON-NLS-1$ Matcher mat = pat.matcher(trg.getSql().toUpperCase()); if (mat.find()) { int index = mat.start(); pat = Pattern.compile("\n"); //$NON-NLS-1$ mat = pat.matcher(trg.getSql().substring(0, index)); int lineShift = 0; while (mat.find()) { lineShift++; } m.setAttribute(IMarker.ATTR_LINE, i.getLine() + lineShift); } } } m.setAttribute(IMarker.ATTR_EXTERNAL_TYPE, i.getObjectTypeName()); m.setAttribute(IMarker.ATTR_CONTEXT, dbConn); if (o instanceof IReferenceable) { markersMap.put(((IReferenceable) o).getReference(), m); } else { markersMap.put(o, m); } } } validated = true; } } }
From source file:h2weibo.utils.StatusImageExtractor.java
public byte[] extract(StringBuffer input) { if (input == null) return null; for (String key : simplePatterns.keySet()) { Pattern p = Pattern.compile(key); Matcher m = p.matcher(input); if (m.find()) { String mediaUrl = simplePatterns.get(key); mediaUrl = mediaUrl.replaceAll("_KEY_", m.group(1)); try { byte[] bytes = downloadUrl(mediaUrl); input.delete(m.start(), m.end()); // -1 for the space before return bytes; } catch (IOException e) { log.error("Not able to download image", e); }/*from w w w .j ava2 s .com*/ } } for (String key : jsonPatterns.keySet()) { Pattern p = Pattern.compile(key); Matcher m = p.matcher(input); if (m.find()) { String jsonUrl = jsonPatterns.get(key)[0]; jsonUrl = jsonUrl.replaceAll("_KEY_", m.group(1)); try { byte[] jsonData = downloadUrl(jsonUrl); JSONObject obj = new JSONObject(new String(jsonData)); String imageUrl = (String) obj.get(jsonPatterns.get(key)[1]); return downloadUrl(imageUrl); } catch (IOException e) { log.error("Not able to download image", e); } catch (JSONException e) { log.error("Not able to parse json", e); } } } return null; }
From source file:com.digitalpebble.stormcrawler.indexing.AbstractIndexerBolt.java
/** Returns a mapping field name / values for the metadata to index **/ protected Map<String, String[]> filterMetadata(Metadata meta) { Pattern indexValuePattern = Pattern.compile("\\[(\\d+)\\]"); Map<String, String[]> fieldVals = new HashMap<>(); Iterator<Entry<String, String>> iter = metadata2field.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> entry = iter.next(); // check whether we want a specific value or all of them? int index = -1; String key = entry.getKey(); Matcher match = indexValuePattern.matcher(key); if (match.find()) { index = Integer.parseInt(match.group(1)); key = key.substring(0, match.start()); }//from w w w.ja v a2 s .co m String[] values = meta.getValues(key); // not found if (values == null || values.length == 0) continue; // want a value index that it outside the range given if (index >= values.length) continue; // store all values available if (index == -1) fieldVals.put(entry.getValue(), values); // or only the one we want else fieldVals.put(entry.getValue(), new String[] { values[index] }); } return fieldVals; }
From source file:com.qcadoo.model.internal.ExpressionServiceImpl.java
private String translate(final String expression, final Locale locale) { if (locale == null) { return expression; }/*w w w.j a va2 s.c om*/ Matcher m = Pattern.compile("\\@([a-zA-Z0-9\\.]+)").matcher(expression); StringBuffer sb = new StringBuffer(); int i = 0; while (m.find()) { sb.append(expression.substring(i, m.start())); sb.append(translationService.translate(m.group(1), locale)); i = m.end(); } if (i == 0) { return expression; } sb.append(expression.substring(i, expression.length())); return sb.toString(); }
From source file:at.ac.tuwien.inso.subcat.utility.commentparser.Parser.java
License:asdf
private void parseGLibMessages(List<ContentNode<T>> ast, String commentFragment) { Matcher gm = pGLibMessages.matcher(commentFragment); int lastEnd = 0; while (gm.find()) { if (lastEnd != gm.start()) { parseParagraphs(ast, commentFragment.substring(lastEnd, gm.start())); }//from ww w .j a v a 2 s. c o m ast.add(new ArtefactNode<T>(gm.group(1))); lastEnd = gm.end(); } if (lastEnd != commentFragment.length()) { String frag = commentFragment.substring(lastEnd, commentFragment.length()); if (frag.trim().length() > 0) { parseParagraphs(ast, frag); } } }
From source file:us.pserver.revok.HttpConnector.java
/** * Set network address and port <code><address>:<port></code>. * @param addr <code>String</code>. * @return This modified <code>HttpConnector</code> instance. *///from ww w. ja v a 2 s. co m public HttpConnector setAddress(String addr) { if (addr == null) throw new IllegalArgumentException( "[HttpConnector.setAddress( String )] " + "Invalid address [" + addr + "]"); Pattern pt = Pattern.compile("[\\w]+://"); Matcher m = pt.matcher(addr); if (m.find()) { proto = addr.substring(m.start(), m.end()); addr = addr.substring(m.end()); } pt = Pattern.compile(":[\\d]+"); m = pt.matcher(addr); if (m.find()) { port = Integer.parseInt(addr.substring(m.start() + 1, m.end())); if (port <= 0 || port > 65535) throw new IllegalArgumentException("Port out of range 1-65535 {" + port + "}"); addr = addr.substring(0, m.start()).concat(addr.substring(m.end())); } pt = Pattern.compile("/[\\w]."); m = pt.matcher(addr); if (m.find()) { path = addr.substring(m.start()); addr = addr.substring(0, m.start()); } address = addr; return this; }
From source file:com.streamsets.pipeline.lib.parser.log.ExtendedFormatParser.java
@Override public Map<String, Field> parseLogLine(StringBuilder logLine) throws DataParserException { Map<String, Field> map = new HashMap<>(); // Parse headers Matcher m = HEADER_PATTERN.matcher(logLine); int counter = 0; int index = 0; int headerCount = 1; while (counter < headerCount && m.find()) { String val = logLine.substring(index, m.start()); if (counter == 0) { Field formatVersion = getExtFormatVersion(val); map.put(formatType.label + "Version", formatVersion); headerCount = getNumHeaderFields(formatType, formatVersion); } else {/* w w w . j a v a2 s.co m*/ map.put(getHeaderFieldName(counter), Field.create(val)); } index = m.end(); counter++; } if (counter < headerCount) { throw new DataParserException(Errors.LOG_PARSER_12, formatName, headerCount, counter); } // For LEEF 2.0, there is an optional field in the header, so we check for it, and // advance the index, if necessary, to get to the start of the extensions char attrSeparator = getExtensionAttrSeparator(m, index, logLine); if (!m.hitEnd()) { index = m.end(); } // Calls to trim() will strip off whitespace, but if format is LEEF 2.0 and a custom // delimiter is being used, we need to offset the start index of extension keys int offset = 0; if (!Character.isWhitespace(attrSeparator)) { offset = 1; } // Process extensions Map<String, Field> extMap = new HashMap<>(); Map<String, String> labelMap = new HashMap<>(); String ext = logLine.substring(index); m = EXT_PATTERN.matcher(ext); index = 0; String key = null; String value; while (m.find()) { if (key == null) { key = ext.substring(index, m.start()); index = m.end(); if (!m.find()) { break; } } // Regex will search for unescaped '=' character to find the split between keys // and values. We'll need to figure out where the separator is to determine the // end of the value, and then go back for the next KV pair value = ext.substring(index, m.start()); index = m.end(); int lastSepIndex = value.lastIndexOf(attrSeparator); if (lastSepIndex > 0) { String temp = value.substring(0, lastSepIndex).trim(); putLabelIntoAppropriateMap(labelMap, extMap, key, temp); key = value.substring(lastSepIndex + offset).trim(); } } value = ext.substring(index); // Build a map of Label extensions to apply later putLabelIntoAppropriateMap(labelMap, extMap, key, value); // Apply the labels to custom fields for (Map.Entry<String, String> label : labelMap.entrySet()) { if (extMap.containsKey(label.getKey())) { Field field = extMap.remove(label.getKey()); extMap.put(label.getValue(), field); } } map.put("extensions", Field.create(extMap)); return map; }
From source file:com.example.phonetic.KoelnerPhonetik.java
private List<String> getVariations(String str) { int position = 0; List<String> variations = new ArrayList<>(); variations.add(""); while (position < str.length()) { int i = 0; int substPos = -1; while (substPos < position && i < getPatterns().length) { Matcher m = variationsPatterns[i].matcher(str); while (substPos < position && m.find()) { substPos = m.start(); }//from www . ja v a2s. c o m i++; } if (substPos >= position) { i--; List<String> varNew = new ArrayList<>(); String prevPart = str.substring(position, substPos); for (int ii = 0; ii < variations.size(); ii++) { String tmp = variations.get(ii); varNew.add(tmp.concat(prevPart + getReplacements()[i])); variations.set(ii, variations.get(ii) + prevPart + getPatterns()[i]); } variations.addAll(varNew); position = substPos + getPatterns()[i].length(); } else { for (int ii = 0; ii < variations.size(); ii++) { variations.set(ii, variations.get(ii) + str.substring(position, str.length())); } position = str.length(); } } return variations; }
From source file:org.ops4j.pax.web.itest.jetty.WarJSFIntegrationTest.java
@Test public void testJSF() throws Exception { // needed to wait for fully initializing the container Thread.sleep(1000);//from www. j a v a 2s . c o m LOG.debug("Testing JSF workflow!"); String response = testClient.testWebPath("http://127.0.0.1:8181/war-jsf-sample", "Please enter your name"); LOG.debug("Found JSF starting page: {}", response); Pattern patternViewState = Pattern.compile("id=\\\"j_id_.*:javax.faces.ViewState:\\w\\\""); Matcher viewStateMatcher = patternViewState.matcher(response); if (!viewStateMatcher.find()) { fail("Didn't find required ViewState ID!"); } String viewStateID = response.substring(viewStateMatcher.start() + 4, viewStateMatcher.end() - 1); String substring = response.substring(viewStateMatcher.end() + 8); int indexOf = substring.indexOf("\""); String viewStateValue = substring.substring(0, indexOf); // int indexOf = // response.indexOf("id=\"javax.faces.ViewState\" value="); // String substring = response.substring(indexOf + 34); // indexOf = substring.indexOf("\""); // substring = substring.substring(0, indexOf); Pattern pattern = Pattern.compile("(input id=\"mainForm:j_id_\\w*)"); Matcher matcher = pattern.matcher(response); if (!matcher.find()) fail("Didn't find required input id!"); String inputID = response.substring(matcher.start(), matcher.end()); inputID = inputID.substring(inputID.indexOf('"') + 1); LOG.debug("Found ID: {}", inputID); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("mainForm:name", "Dummy-User")); nameValuePairs.add(new BasicNameValuePair(viewStateID, viewStateValue)); nameValuePairs.add(new BasicNameValuePair(inputID, "Press me")); nameValuePairs.add(new BasicNameValuePair("javax.faces.ViewState", viewStateValue)); // nameValuePairs.add(new BasicNameValuePair("mainForm", inputID)); nameValuePairs.add(new BasicNameValuePair("mainForm_SUBMIT", "1")); LOG.debug("Will send the following NameValuePairs: {}", nameValuePairs); testClient.testPost("http://127.0.0.1:8181/war-jsf-sample/faces/helloWorld.jsp", nameValuePairs, "Hello Dummy-User. We hope you enjoy Apache MyFaces", 200); }
From source file:org.shredzone.commons.view.manager.ViewPattern.java
/** * Compiles a view pattern. Generates a parameter list, a list of expressions for * building URLs to this view, and a regular expression for matching URLs against this * view pattern./*from w w w . ja v a 2 s.com*/ * * @param pstr * the view pattern * @param pattern * {@link StringBuilder} to assemble the regular expression in * @param expList * List of {@link Expression} to assemble expressions in * @param paramList * List to assemble parameters in */ private void compilePattern(String pstr, StringBuilder pattern, List<Expression> expList, List<String> paramList) { ExpressionParser parser = new SpelExpressionParser(); int previous = 0; Matcher m = PATH_PART.matcher(pstr); while (m.find()) { String fixedPart = pstr.substring(previous, m.start()); if (fixedPart.indexOf('\'') >= 0) { throw new IllegalArgumentException("path parameters must not contain \"'\""); } String expressionPart = m.group(1); pattern.append(Pattern.quote(fixedPart)); pattern.append("([^/]*)"); paramList.add(expressionPart); expList.add(parser.parseExpression('\'' + fixedPart + '\'')); expList.add(parser.parseExpression(expressionPart)); previous = m.end(); } String postPart = pstr.substring(previous); pattern.append(Pattern.quote(postPart)); expList.add(parser.parseExpression('\'' + postPart + '\'')); }