List of usage examples for java.util.regex Pattern quote
public static String quote(String s)
From source file:com.agapsys.web.toolkit.services.UploadService.java
/** * Process a request to receive files.//from w ww . ja va 2 s. com * * @param req HTTP request. * @param resp HTTP response. * @param persistReceivedFiles indicates if received files should be persisted. * @param onFormFieldListener listener called when a form field is received. * @throws IllegalArgumentException if given request if not multipart/form-data. * @return a list of received file by given request. */ public List<ReceivedFile> receiveFiles(HttpServletRequest req, HttpServletResponse resp, boolean persistReceivedFiles, OnFormFieldListener onFormFieldListener) throws IllegalArgumentException { __int(); if (persistReceivedFiles && resp == null) throw new IllegalArgumentException("In order to persist information, response cannot be null"); if (!ServletFileUpload.isMultipartContent(req)) throw new IllegalArgumentException("Request is not multipart/form-data"); try { List<ReceivedFile> recvFiles = new LinkedList<>(); List<FileItem> fileItems = uploadServlet.parseRequest(req); for (FileItem fi : fileItems) { if (fi.isFormField()) { if (onFormFieldListener != null) onFormFieldListener.onFormField(fi.getFieldName(), fi.getString(getFieldEncoding())); } else { boolean acceptRequest = getAllowedContentTypes().equals("*"); if (!acceptRequest) { String[] acceptedContentTypes = getAllowedContentTypes().split(Pattern.quote(",")); for (String acceptedContentType : acceptedContentTypes) { if (fi.getContentType().equals(acceptedContentType.trim())) { acceptRequest = true; break; } } } if (!acceptRequest) throw new IllegalArgumentException("Unsupported content-type: " + fi.getContentType()); File tmpFile = ((DiskFileItem) fi).getStoreLocation(); String filename = fi.getName(); ReceivedFile recvFile = new ReceivedFile(tmpFile, filename); recvFiles.add(recvFile); } } if (persistReceivedFiles) { List<ReceivedFile> sessionRecvFiles = getSessionFiles(req, resp); sessionRecvFiles.addAll(recvFiles); persistSessionFiles(req, resp, sessionRecvFiles); } return recvFiles; } catch (FileUploadException ex) { if (ex instanceof FileUploadBase.SizeLimitExceededException) throw new IllegalArgumentException("Size limit exceeded"); else throw new RuntimeException(ex); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
From source file:com.epam.ta.reportportal.database.dao.LaunchRepositoryCustomImpl.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*from w ww .j a va 2s . co m*/ public List<String> findDistinctValues(String projectName, String containsValue, String distinctBy) { Aggregation aggregation = newAggregation(match(where(PROJECT_ID_REFERENCE).is(projectName)), unwind(distinctBy), match(where(distinctBy).regex("(?i).*" + Pattern.quote(containsValue) + ".*")), group(distinctBy), limit(AUTOCOMPLETE_LIMITATION)); AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Launch.class, Map.class); List<String> tags = new ArrayList<>(result.getMappedResults().size()); for (Map<String, String> entry : result.getMappedResults()) { tags.add(entry.get("_id")); } return tags; }
From source file:py.una.pol.karaku.dao.search.SearchHelper.java
/** * Retorna la informacin relacionada a un Field definido por una propiedad * (con un formato separado por puntos). * <p>/*from www. j a va 2s. c o m*/ * Por ejemplo, si invocamos de la siguiente manera: * * <pre> * class Pais { * ... * Set{@literal <}Departamento> departamentos; * * ... * } * * class Departamento { * ... * Set{@literal <}Ciudad> ciudades; * * Set etnias; * * Pais pais; * ... * } * * class Ciudad { * ... * * Departamento departamento; * ... * } * * 1. Y invocamos de la siguiente manera: * * fi = getFieldInfo(Ciudad.class, "departamento.pais"); * fi.getField() ==> Pais.class * fi.isCollection() == > <code>false</code> * * 2. El siguiente ejemplo, es cuando se encuentra una {@link Collection} * * fi = getFieldInfo(Ciudad.class, "departamento.etnias"); * fi.getField() ==> Etnia.class * fi.isCollection() == > <code>true</code> * </pre> * * <p> * TODO ver para meter en una clase de utilidad * </p> * * @param root * {@link Class} que sirve de base para buscar la propiedad * @param property * cadena separada por <code>.</code> (puntos) que sirve para * recorrer a travs del objeto y obtener la propiedad deseada. * @return {@link FieldInfo} con la informacin posible que se ha * conseguido. * @throw {@link KarakuRuntimeException} si no encuentra el field o no es * accesible. */ public static FieldInfo getFieldInfo(@NotNull Class<?> root, @NotNull String property) { try { String[] splited = property.split(Pattern.quote(".")); String cProperty; Class<?> cClass = root; Field toRet = null; boolean collectionFound = false; for (String element : splited) { cProperty = element; toRet = ReflectionUtils.findField(cClass, cProperty); if (toRet == null) { throw new KarakuRuntimeException( "Field: " + cProperty + " not found. (Full path: " + property + ")"); } cClass = toRet.getType(); // Si tenemos una lista, buscar el tipo de la lista. if (Collection.class.isAssignableFrom(cClass)) { cClass = GenericCollectionTypeResolver.getCollectionFieldType(toRet); } // TODO add expansion if found a @Display in the last field // Ejemplo: pais.departamento, puede seguir siendo explotado // si departamento tiene un DisplayName } return new FieldInfo(toRet, collectionFound); } catch (SecurityException e) { throw new KarakuRuntimeException( "Field not accessible: " + property + " in class " + root.getSimpleName(), e); } }
From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java
private static boolean hostMatches(final String host, final String rule) { if (rule == null || host == null) return false; if (rule.startsWith(".")) return host.matches("(?i).*" + Pattern.quote(rule)); return host.equalsIgnoreCase(rule); }
From source file:com.epam.dlab.auth.dao.LdapUserDAO.java
public UserInfo enrichUserInfo(final UserInfo userInfo) throws Exception { log.debug("Enriching user info for user: {}", userInfo); String username = userInfo.getName(); UserInfo ui = userInfo.withToken("******"); try (DlabLdapConnection connection = getConnection(searchPool)) { final LdapConnection ldapConnection = connection.connect(); Map<String, Object> conextTree = new HashMap<>(); for (Request req : requests) { if (req.getName().equalsIgnoreCase(USER_LOOK_UP)) { addUserAttributes(username, ui, ldapConnection); }//www. j a v a2 s.c o m log.info("Request: {}", req.getName()); SearchResultProcessor proc = req.getSearchResultProcessor(); log.info("Putting user param {} : {} for user enriching", ldapSearchAttribute, username); SearchRequest sr = req .buildSearchRequest(Collections.singletonMap(Pattern.quote(ldapSearchAttribute), username)); String filter = sr.getFilter().toString(); Map<String, Object> contextMap = (useCache) ? LdapFilterCache.getInstance().getLdapFilterInfo(filter) : null; SearchResultToDictionaryMapper mapper = new SearchResultToDictionaryMapper(req.getName(), conextTree); if (contextMap == null) { log.debug("Retrieving new branch {} for {}", req.getName(), filter); try (SearchCursor cursor = ldapConnection.search(sr)) { contextMap = mapper.transformSearchResult(cursor); } if (req.isCache() && useCache) { LdapFilterCache.getInstance().save(filter, contextMap, req.getExpirationTimeMsec()); } } else { log.debug("Restoring old branch {} for {}: {}", req.getName(), filter, contextMap); mapper.getBranch().putAll(contextMap); } if (proc != null) { log.debug("Executing: {}", proc.getLanguage()); conextTree.put("key", ui.getKeys().get("dn")); ui = script.evalOnce(req.getName(), proc.getLanguage(), proc.getCode()).apply(ui, conextTree); } } } catch (Exception e) { log.error("LDAP enrichUserInfo authentication error for username '{}': {}", username, e.getMessage(), e); throw e; } return ui; }
From source file:com.webbfontaine.valuewebb.utils.TTMailUtils.java
public String replaceTextVariables(String text, HashMap<String, String> textVariables) { for (String key : textVariables.keySet()) { String replace = ""; if (textVariables.get(key) != null) { replace = textVariables.get(key); }/*from w ww .j a v a 2 s. c o m*/ text = text.replaceAll(Pattern.quote(key), replace); } return text; }
From source file:com.moss.appsnap.keeper.windows.MSWindowsAppHandler.java
private static File resolveFileFromPath(String name) { File result = null;/* w ww . j a v a 2 s .com*/ String[] paths = System.getenv("PATH").split(Pattern.quote(";")); for (String next : paths) { File f = new File(next, name); System.out.println("Examining " + f); if (f.exists()) { result = f; } } return result; }
From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java
@Override protected List<ConfigIssue> init() { if (disableValidation) { LOG.warn("JDBC Origin initialized with Validation Disabled."); }// w w w .ja v a2s .co m List<ConfigIssue> issues = new ArrayList<>(); Source.Context context = getContext(); errorRecordHandler = new DefaultErrorRecordHandler(context); issues = hikariConfigBean.validateConfigs(context, issues); if (queryIntervalMillis < 0) { issues.add(getContext().createConfigIssue(Groups.JDBC.name(), QUERY_INTERVAL_EL, JdbcErrors.JDBC_27)); } issues = commonSourceConfigBean.validateConfigs(context, issues); // Incremental mode have special requirements for the query form if (isIncrementalMode) { if (StringUtils.isEmpty(offsetColumn)) { issues.add(context.createConfigIssue(Groups.JDBC.name(), OFFSET_COLUMN, JdbcErrors.JDBC_51, "Can't be empty")); } if (StringUtils.isEmpty(initialOffset)) { issues.add(context.createConfigIssue(Groups.JDBC.name(), INITIAL_OFFSET, JdbcErrors.JDBC_51, "Can't be empty")); } final String formattedOffsetColumn = Pattern.quote(offsetColumn.toUpperCase()); Pattern offsetColumnInWhereAndOrderByClause = Pattern .compile(String.format("(?s).*\\bWHERE\\b.*(\\b%s\\b).*\\bORDER BY\\b.*\\b%s\\b.*", formattedOffsetColumn, formattedOffsetColumn)); if (!disableValidation) { String upperCaseQuery = query.toUpperCase(); boolean checkOffsetColumnInWhereOrder = true; if (!upperCaseQuery.contains("WHERE")) { issues.add(context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_38, "WHERE")); checkOffsetColumnInWhereOrder = false; } if (!upperCaseQuery.contains("ORDER BY")) { issues.add( context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_38, "ORDER BY")); checkOffsetColumnInWhereOrder = false; } if (checkOffsetColumnInWhereOrder && !offsetColumnInWhereAndOrderByClause.matcher(upperCaseQuery).matches()) { issues.add( context.createConfigIssue(Groups.JDBC.name(), QUERY, JdbcErrors.JDBC_29, offsetColumn)); } } } if (txnMaxSize < 0) { issues.add(context.createConfigIssue(Groups.ADVANCED.name(), TXN_MAX_SIZE, JdbcErrors.JDBC_10, txnMaxSize, 0)); } if (createJDBCNsHeaders && !jdbcNsHeaderPrefix.endsWith(".")) { issues.add( context.createConfigIssue(Groups.ADVANCED.name(), JDBC_NS_HEADER_PREFIX, JdbcErrors.JDBC_15)); } Properties driverProps = new Properties(); try { driverProps = hikariConfigBean.getDriverProperties(); if (null == dataSource) { dataSource = jdbcUtil.createDataSourceForRead(hikariConfigBean); } } catch (StageException e) { LOG.error(JdbcErrors.JDBC_00.getMessage(), e.toString(), e); issues.add(context.createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, JdbcErrors.JDBC_00, e.toString())); } // Don't proceed with validation query if there are issues or if validation is disabled if (!issues.isEmpty() || disableValidation) { return issues; } try (Connection validationConnection = dataSource.getConnection()) { // NOSONAR DatabaseMetaData dbMetadata = validationConnection.getMetaData(); // If CDC is enabled, scrollable cursors must be supported by JDBC driver. supportsScrollableCursor(issues, context, dbMetadata); try (Statement statement = validationConnection.createStatement()) { statement.setFetchSize(1); statement.setMaxRows(1); final String preparedQuery = prepareQuery(query, initialOffset); executeValidationQuery(issues, context, statement, preparedQuery); } } catch (SQLException e) { String formattedError = jdbcUtil.formatSqlException(e); LOG.error(formattedError); LOG.debug(formattedError, e); issues.add(context.createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, JdbcErrors.JDBC_00, formattedError)); } LineageEvent event = getContext().createLineageEvent(LineageEventType.ENTITY_READ); // TODO: add the per-event specific details here. event.setSpecificAttribute(LineageSpecificAttribute.DESCRIPTION, query); event.setSpecificAttribute(LineageSpecificAttribute.ENDPOINT_TYPE, EndPointType.JDBC.name()); Map<String, String> props = new HashMap<>(); props.put("Connection String", hikariConfigBean.getConnectionString()); props.put("Offset Column", offsetColumn); props.put("Is Incremental Mode", isIncrementalMode ? "true" : "false"); if (!StringUtils.isEmpty(tableNames)) { event.setSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME, hikariConfigBean.getConnectionString() + " " + tableNames); props.put("Table Names", tableNames); } else { event.setSpecificAttribute(LineageSpecificAttribute.ENTITY_NAME, hikariConfigBean.getConnectionString()); } for (final String n : driverProps.stringPropertyNames()) { props.put(n, driverProps.getProperty(n)); } event.setProperties(props); getContext().publishLineageEvent(event); shouldFire = true; firstTime = true; return issues; }
From source file:com.jkoolcloud.tnt4j.streams.utils.WmqUtils.java
/** * This method applies custom handling for setting field values. This method will construct the signature to use for * the message from the specified value, which is assumed to be a string containing the inputs required for the * message signature calculation, with each input separated by the delimiter specified using parameter * {@code sigDelim}./* w w w . ja v a 2 s .c o m*/ * * @param value * value object to retrieve signature fields data * @param sigDelim * signature delimiter * @param logger * logger to log result trace messages * @return unique message signature, or {@code null} if <tt>value</tt> contained signature calculation items are * empty * * @see #computeSignature(Object...) */ public static Object computeSignature(Object value, String sigDelim, EventSink logger) { Object[] sigItems = null; if (value instanceof Object[]) { sigItems = (Object[]) value; } else if (value instanceof String) { String sigStr = (String) value; if (sigStr.contains(sigDelim)) { sigItems = sigStr.split(Pattern.quote(sigDelim)); } } if (Utils.isEmptyContent(sigItems)) { logger.log(OpLevel.DEBUG, StreamsResources.getBundle(WmqStreamConstants.RESOURCE_BUNDLE_NAME), "WmqUtils.msg.signature.null.elements"); return null; } if (isEmptyItems(sigItems)) { logger.log(OpLevel.DEBUG, StreamsResources.getBundle(WmqStreamConstants.RESOURCE_BUNDLE_NAME), "WmqUtils.msg.signature.empty.elements", sigItems); return null; } value = computeSignature(sigItems); logger.log(OpLevel.TRACE, StreamsResources.getBundle(WmqStreamConstants.RESOURCE_BUNDLE_NAME), "WmqUtils.msg.signature", value, sigItems.length, Utils.toStringDeep(sigItems)); if ("1B2M2Y8AsgTpgAmY7PhCfg==".equals(value)) { // NON-NLS logger.log(OpLevel.DEBUG, StreamsResources.getBundle(WmqStreamConstants.RESOURCE_BUNDLE_NAME), "WmqUtils.msg.signature.md5.default.value", value); return null; } return value; }
From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv3Reader.java
/** * Iterate through lines and create span annotations accordingly. For * multiple span annotation, based on the position of the annotation in the * line, update only the end position of the annotation *//* w w w . jav a 2 s.c o m*/ private void setAnnotations(JCas aJCas, InputStream aIs, String aEncoding) throws IOException { // getting header information LineIterator lineIterator = IOUtils.lineIterator(aIs, aEncoding); int sentBegin = -1, sentEnd = 0; int prevSentEnd = 0; StringBuilder sentLineSb = new StringBuilder(); String lastSent = ""; while (lineIterator.hasNext()) { String line = lineIterator.next(); if (line.startsWith("#T_")) { setLayerAndFeature(aJCas, line); continue; } if (line.startsWith("#Text=")) { if (sentLineSb.toString().isEmpty()) { sentLineSb.append(line.substring(line.indexOf("=") + 1)); } else { sentLineSb.append(LF + line.substring(line.indexOf("=") + 1)); } lastSent = sentLineSb.toString(); continue; } if (line.startsWith("#FORMAT=")) { continue; } if (line.trim().isEmpty()) { if (!sentLineSb.toString().isEmpty()) { createSentence(aJCas, sentLineSb.toString(), sentBegin, sentEnd, prevSentEnd); prevSentEnd = sentEnd; sentBegin = -1;// reset for next sentence begin sentLineSb = new StringBuilder(); } continue; } line = line.trim(); int count = StringUtils.countMatches(line, "\t"); if (columns != count) { throw new IOException(fileName + " This is not a valid TSV File. check this line: " + line); } String regex = "(?<!\\\\)*" + Pattern.quote(TAB); String[] lines = line.split(regex); int begin = Integer.parseInt(lines[1].split("-")[0]); int end = Integer.parseInt(lines[1].split("-")[1]); if (sentBegin == -1) { sentBegin = begin; } sentEnd = end; AnnotationUnit unit = createTokens(aJCas, lines, begin, end); int ind = 3; setAnnosPerTypePerUnit(lines, unit, ind); } // the last sentence if (!lastSent.isEmpty()) { createSentence(aJCas, lastSent, sentBegin, sentEnd, prevSentEnd); } Map<Type, Map<AnnotationUnit, List<AnnotationFS>>> annosPerTypePerUnit = new HashMap<>(); setAnnosPerUnit(aJCas, annosPerTypePerUnit); addAnnotations(aJCas, annosPerTypePerUnit); addChainAnnotations(aJCas); }