List of usage examples for java.util.regex PatternSyntaxException getMessage
public String getMessage()
From source file:com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.java
private Object doAction(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args, final int actionType) { // in a first time just improve replacement with a String (not a function) if (RA_REPLACE == actionType && args.length == 2 && (args[1] instanceof String)) { final String thisString = Context.toString(thisObj); String replacement = (String) args[1]; final Object arg0 = args[0]; if (arg0 instanceof String) { replacement = REPLACE_PATTERN.matcher(replacement).replaceAll("\\$"); // arg0 should *not* be interpreted as a RegExp return StringUtils.replaceOnce(thisString, (String) arg0, replacement); } else if (arg0 instanceof NativeRegExp) { try { final NativeRegExp regexp = (NativeRegExp) arg0; final RegExpData reData = new RegExpData(regexp); final String regex = reData.getJavaPattern(); final int flags = reData.getJavaFlags(); final Pattern pattern = Pattern.compile(regex, flags); final Matcher matcher = pattern.matcher(thisString); return doReplacement(thisString, replacement, matcher, reData.hasFlag('g')); } catch (final PatternSyntaxException e) { LOG.warn(e.getMessage(), e); }//from w w w . j a va2 s .c om } } else if (RA_MATCH == actionType || RA_SEARCH == actionType) { if (args.length == 0) { return null; } final Object arg0 = args[0]; final String thisString = Context.toString(thisObj); final RegExpData reData; if (arg0 instanceof NativeRegExp) { reData = new RegExpData((NativeRegExp) arg0); } else { reData = new RegExpData(Context.toString(arg0)); } final Pattern pattern = Pattern.compile(reData.getJavaPattern(), reData.getJavaFlags()); final Matcher matcher = pattern.matcher(thisString); final boolean found = matcher.find(); if (RA_SEARCH == actionType) { if (found) { setProperties(matcher, thisString, matcher.start(), matcher.end()); return matcher.start(); } return -1; } if (!found) { return null; } final int index = matcher.start(0); final List<Object> groups = new ArrayList<>(); if (reData.hasFlag('g')) { // has flag g groups.add(matcher.group(0)); setProperties(matcher, thisString, matcher.start(0), matcher.end(0)); while (matcher.find()) { groups.add(matcher.group(0)); setProperties(matcher, thisString, matcher.start(0), matcher.end(0)); } } else { for (int i = 0; i <= matcher.groupCount(); i++) { Object group = matcher.group(i); if (group == null) { group = Context.getUndefinedValue(); } groups.add(group); } setProperties(matcher, thisString, matcher.start(), matcher.end()); } final Scriptable response = cx.newArray(scope, groups.toArray()); // the additional properties (cf ECMA script reference 15.10.6.2 13) response.put("index", response, Integer.valueOf(index)); response.put("input", response, thisString); return response; } return wrappedAction(cx, scope, thisObj, args, actionType); }
From source file:io.wcm.caravan.commons.httpclient.impl.HttpClientConfigImpl.java
@Activate private void activate(Map<String, Object> config) { enabled = PropertiesUtil.toBoolean(config.get(ENABLED_PROPERTY), ENABLED_DEFAULT); connectTimeout = PropertiesUtil.toInteger(config.get(CONNECT_TIMEOUT_PROPERTY), HttpClientConfig.CONNECT_TIMEOUT_DEFAULT); socketTimeout = PropertiesUtil.toInteger(config.get(SOCKET_TIMEOUT_PROPERTY), HttpClientConfig.SOCKET_TIMEOUT_DEFAULT); maxConnectionsPerHost = PropertiesUtil.toInteger(config.get(MAX_CONNECTIONS_PER_HOST_PROPERTY), HttpClientConfig.MAX_CONNECTIONS_PER_HOST_DEFAULT); maxTotalConnections = PropertiesUtil.toInteger(config.get(MAX_TOTAL_CONNECTIONS_PROPERTY), HttpClientConfig.MAX_TOTAL_CONNECTIONS_DEFAULT); httpUser = PropertiesUtil.toString(config.get(HTTP_USER_PROPERTY), null); httpPassword = PropertiesUtil.toString(config.get(HTTP_PASSWORD_PROPERTY), null); proxyHost = PropertiesUtil.toString(config.get(PROXY_HOST_PROPERTY), null); proxyPort = PropertiesUtil.toInteger(config.get(PROXY_PORT_PROPERTY), 0); proxyUser = PropertiesUtil.toString(config.get(PROXY_USER_PROPERTY), null); proxyPassword = PropertiesUtil.toString(config.get(PROXY_PASSWORD_PROPERTY), null); hostPatterns = new HashSet<Pattern>(); String[] hostPatternsArray = PropertiesUtil.toStringArray(config.get(HOST_PATTERNS_PROPERTY), new String[0]); for (String hostPatternString : hostPatternsArray) { if (StringUtils.isNotBlank(hostPatternString)) { try { hostPatterns.add(Pattern.compile(hostPatternString)); } catch (PatternSyntaxException ex) { log.warn("Invalid host name pattern '" + hostPatternString + "': " + ex.getMessage(), ex); this.enabled = false; }//from w w w. j ava 2 s.c o m } } wsAddressingToUris = new HashSet<String>(); String[] wsAddressingToUrisArray = PropertiesUtil.toStringArray(config.get(WS_ADDRESSINGTO_URIS_PROPERTY), new String[0]); for (String wsAddressingToUriString : wsAddressingToUrisArray) { if (StringUtils.isNotBlank(wsAddressingToUriString)) { wsAddressingToUris.add(wsAddressingToUriString); } } sslContextType = PropertiesUtil.toString(config.get(SSL_CONTEXT_TYPE_PROPERTY), CertificateLoader.SSL_CONTEXT_TYPE_DEFAULT); keyManagerType = PropertiesUtil.toString(config.get(KEYMANAGER_TYPE_PROPERTY), CertificateLoader.KEY_MANAGER_TYPE_DEFAULT); keyStoreType = PropertiesUtil.toString(config.get(KEYSTORE_TYPE_PROPERTY), CertificateLoader.KEY_STORE_TYPE_DEFAULT); keyStorePath = PropertiesUtil.toString(config.get(KEYSTORE_PATH_PROPERTY), null); keyStorePassword = PropertiesUtil.toString(config.get(KEYSTORE_PASSWORD_PROPERTY), null); trustManagerType = PropertiesUtil.toString(config.get(TRUSTMANAGER_TYPE_PROPERTY), CertificateLoader.TRUST_MANAGER_TYPE_DEFAULT); trustStoreType = PropertiesUtil.toString(config.get(TRUSTSTORE_TYPE_PROPERTY), CertificateLoader.TRUST_STORE_TYPE_DEFAULT); trustStorePath = PropertiesUtil.toString(config.get(TRUSTSTORE_PATH_PROPERTY), null); trustStorePassword = PropertiesUtil.toString(config.get(TRUSTSTORE_PASSWORD_PROPERTY), null); }
From source file:com.clustercontrol.monitor.run.factory.RunMonitorStringValueType.java
/** * ????//from ww w .j av a2s . c om * <p> * ??????????? * ??????????????????? * * @see com.clustercontrol.monitor.run.ejb.entity.MonitorStringValueInfoBean#getOrder_no() * @see com.clustercontrol.monitor.run.bean.MonitorStringValueInfo */ @Override public int getCheckResult(boolean ret) { // -1 = ?-2 = ????? int result = -2; // ?? if (!ret) { result = -1; return result; } // ??? Pattern pattern = null; Matcher matcher = null; int orderNo = 0; // ?? for (MonitorJudgementInfo info : m_judgementInfoList.values()) { ++orderNo; if (m_log.isDebugEnabled()) { m_log.debug("getCheckResult() value = " + m_value + ", monitorId = " + info.getMonitorId() + ", orderNo = " + orderNo + ", pattern = " + info.getPattern()); } // ????? if (info != null && info.getValidFlg()) { try { String patternText = info.getPattern(); // ????? if (info.getCaseSensitivityFlg()) { pattern = Pattern.compile(patternText, Pattern.DOTALL | Pattern.CASE_INSENSITIVE); } // ??? else { pattern = Pattern.compile(patternText, Pattern.DOTALL); } if (m_value == null) { m_log.debug("getCheckResult(): monitorId=" + info.getMonitorId() + ", facilityId=" + m_facilityId + ", value=null"); result = -1; return result; } matcher = pattern.matcher(m_value); // ???? if (matcher.matches()) { result = orderNo; m_log.debug("getCheckResult() true : description=" + info.getDescription() + ", value=" + m_value); m_log.debug("getCheckResult() true : message=" + info.getMessage()); break; } } catch (PatternSyntaxException e) { m_log.info("getCheckResult(): PatternSyntax is not valid." + " description=" + info.getDescription() + ", patternSyntax=" + info.getPattern() + ", value=" + m_value + " : " + e.getClass().getSimpleName() + ", " + e.getMessage()); result = -1; } catch (Exception e) { m_log.warn("getCheckResult(): PatternSyntax is not valid." + " description=" + info.getDescription() + ", patternSyntax=" + info.getPattern() + ", value=" + m_value + " : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); result = -1; } } } return result; }
From source file:net.pandoragames.far.ui.UIBean.java
/** * {@inheritDoc}// w w w . j a v a 2s . c o m */ public void replace(ReplacementDescriptor criteriaForm, List<TargetFile> fileList) { if (criteriaForm == null) throw new NullPointerException("Replace criteria must not be null"); ReplacementDescriptor criteria = (ReplacementDescriptor) criteriaForm.clone(); wasAborted = false; int counter = 0; try { FileMatcher matcher = new FileMatcher(criteria.getContentPatternAsRegex()); matcher.setBaseDirectory(criteria.getBaseDirectory()); matcher.setDoBackup(criteria.isDoBackup()); if (criteria.isDoBackup()) matcher.setBackUpDirectory(criteria.getBackupDirectory()); int matchCounter = 0; int selectCounter = 0; for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).isSelected()) selectCounter++; } notifyStarted(OperationType.REPLACE); operationInProgress = OperationType.REPLACE; lastReplaceForm = (ReplaceForm) criteria.clone(); lastFileSet = new ArrayList<TargetFile>(); logger.info("Applying " + criteria.getContentPatternAsRegex().pattern() + " --> " + criteria.getReplacementString() + " on " + selectCounter + " files "); for (TargetFile file : fileList) { counter++; if ((!wasAborted) && file.isSelected()) { file.clear(); lastFileSet.add(file); try { matcher.setCharacterSet(file.getCharacterset()); // TODO: use file dependent line break // like so: // if( criteria.patternContainsLineBreak() ) { // String lb = findLineBreakUsed( file ); // } int numberOfMatches = matcher.apply(file.getFile(), criteria.getReplacementPattern(LINEBREAK)); file.setIncluded(numberOfMatches > 0); if (numberOfMatches > 0) { matchCounter++; file.info(localizer.localize("message.replacement-count", new Integer[] { numberOfMatches })); logger.debug("Replacement pattern applied to " + file.getFile().getName()); } } catch (Exception x) { logger.error(x.getClass().getName() + ": " + x.getMessage(), x); file.error(x.getMessage()); } } else { file.setIncluded(false); } notifyCount(counter, selectCounter, OperationType.REPLACE); } notifyTerminated(OperationType.REPLACE); logger.info(matchCounter + " files changed"); messageBox.info( localizer.localize("message.update-count", new Integer[] { Integer.valueOf(matchCounter) })); } catch (PatternSyntaxException px) { abort(); logger.error("PatternSyntaxException: " + px.getMessage(), px); messageBox.clear(); messageBox.error(localizer.localize("message.syntax-error", new Object[] { px.getMessage() })); } catch (Exception x) { abort(); logger.error(x.getClass().getName() + ": " + x.getMessage(), x); messageBox.clear(); messageBox.error(localizer.localize("message.file-processing-error", new Object[] { fileList.get(counter - 1).getName(), x.getMessage() })); } catch (OutOfMemoryError omu) { abort(); String message = "OutOfMemoryError: " + omu.getMessage(); logger.error(message, omu); messageBox.clear(); messageBox.error(localizer.localize("message.document-too-large-for-processing", new Object[] { fileList.get(counter - 1).getName(), omu.getMessage() })); } wasAborted = false; operationInProgress = OperationType.NONE; }
From source file:ch.entwine.weblounge.kernel.site.SiteManager.java
/** * Returns the site associated with the given server name. * <p>/*from w w w.j a va 2s. c om*/ * Note that the server name is expected to not end with a trailing slash, so * please pass in <code>www.entwinemedia.com</code> instead of * <code>www.entwinemedia.com/</code>. * * @param url * the site url, e.g. <code>http://www.entwinemedia.com</code> * @return the site */ public Site findSiteByURL(URL url) { String hostName = url.getHost(); Site site = sitesByServerName.get(hostName); if (site != null) return site; // There is obviously no direct match. Therefore, try to find a // wildcard match synchronized (sites) { for (Map.Entry<String, Site> e : sitesByServerName.entrySet()) { String siteUrl = e.getKey(); try { // convert the host wildcard (ex. *.domain.tld) to a valid regex (ex. // .*\.domain\.tld) String alias = siteUrl.replace(".", "\\."); alias = alias.replace("*", ".*"); if (hostName.matches(alias)) { site = e.getValue(); logger.info("Registering {} to site '{}', matching url {}", new Object[] { url, site.getIdentifier(), siteUrl }); sitesByServerName.put(hostName, site); return site; } } catch (PatternSyntaxException ex) { logger.warn("Error while trying to find a host wildcard match: ".concat(ex.getMessage())); } } } logger.debug("Lookup for {} did not match any site", url); return null; }
From source file:com.rapidminer.operator.preprocessing.transformation.aggregation.AggregationOperator.java
private Attribute[] getMatchingAttributes(Attributes attributes, String regex) throws OperatorException { Pattern pattern = null;/*from w w w . java2 s. com*/ try { pattern = Pattern.compile(regex); } catch (PatternSyntaxException e) { throw new UserError(this, 206, regex, e.getMessage()); } List<Attribute> attributeList = new LinkedList<>(); Iterator<Attribute> iterator = attributes.allAttributes(); while (iterator.hasNext()) { Attribute attribute = iterator.next(); if (pattern.matcher(attribute.getName()).matches()) { attributeList.add(attribute); } } // building array of attributes for faster access. Attribute[] attributesArray = new Attribute[attributeList.size()]; attributesArray = attributeList.toArray(attributesArray); return attributesArray; }
From source file:com.clustercontrol.process.factory.RunMonitorProcess.java
/** * ?????????<BR>// w w w .j a va2 s.c om * ?????? preCollect ????? * * @param facilityId ID * @return ???????true */ @Override public boolean collect(String facilityId) { if (m_log.isDebugEnabled()) m_log.debug("collect() : start." + " facilityId = " + m_facilityId + ", monitorId = " + m_monitorId + ", monitorType = " + m_monitorTypeId); // ?,??? int count = 0; // if (m_now != null) { m_nodeDate = m_now.getTime(); } m_value = 0; // m_messageOrg = MessageConstant.COMMAND.getMessage() + " : " + m_command + ", " + MessageConstant.PARAM.getMessage() + " : " + m_param; // ??? Pattern pCommand = null; Pattern pParam = null; try { // ????? if (m_process.getCaseSensitivityFlg()) { pCommand = Pattern.compile(m_command, Pattern.CASE_INSENSITIVE); pParam = Pattern.compile(m_param, Pattern.CASE_INSENSITIVE); } // ??? else { pCommand = Pattern.compile(m_command); pParam = Pattern.compile(m_param); } } catch (PatternSyntaxException e) { m_log.info("collect() command, parameter PatternSyntax error : " + e.getClass().getSimpleName() + ", " + e.getMessage()); m_message = MessageConstant.MESSAGE_PLEASE_SET_VALUE_WITH_REGEX.getMessage(); return false; } @SuppressWarnings("unchecked") List<ProcessInfo> procList = (List<ProcessInfo>) preCollectData; if (procList == null) { // TODO nagatsumas ???OK // ?????????????? return false; } else { // ?????????? for (ProcessInfo procInfo : procList) { if (pCommand.matcher(procInfo.command).matches()) { if (pParam.matcher(procInfo.param).matches()) { count++; // ?? m_nodeDate = procInfo.time; // ???? if (ProcessProperties.getProperties().isDetailedDisplay()) { m_messageOrg = m_messageOrg + "\n"; if (procInfo.pid != null) { // PID???????SNMP???? m_messageOrg = m_messageOrg + procInfo.pid + " : "; } m_messageOrg = m_messageOrg + procInfo.command + " " + procInfo.param; } } } } } // m_value = count; m_message = MessageConstant.PROCESS_NUMBER.getMessage() + " : " + NumberFormat.getNumberInstance().format(m_value); if (m_log.isDebugEnabled()) m_log.debug("collect() : end." + " facilityId = " + m_facilityId + ", monitorId = " + m_monitorId + ", monitorType = " + m_monitorTypeId + ", count = " + count); return true; // // ??????? // m_message = MessageConstant.MESSAGE_TIME_OUT.getMessage(); // return false; }
From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.CredentialsDescription.java
/** Constructor. Build the description from the ConfigParams. */ public CredentialsDescription(ConfigParams configData) throws ManifoldCFException { // Scan, looking for bin description nodes int i = 0;/* w w w. ja va2 s. c o m*/ while (i < configData.getChildCount()) { ConfigNode node = configData.getChild(i++); if (node.getType().equals(WebcrawlerConfig.NODE_ACCESSCREDENTIAL)) { // Get the url regexp String urlDescription = node.getAttributeValue(WebcrawlerConfig.ATTR_URLREGEXP); try { Pattern p; try { p = Pattern.compile(urlDescription, Pattern.UNICODE_CASE); } catch (java.util.regex.PatternSyntaxException e) { throw new ManifoldCFException("Access credential regular expression '" + urlDescription + "' is illegal: " + e.getMessage(), e); } CredentialsItem ti = new CredentialsItem(p); String type = node.getAttributeValue(WebcrawlerConfig.ATTR_TYPE); // These get used in two of the three types; no harm in fetching them up front. String userName = node.getAttributeValue(WebcrawlerConfig.ATTR_USERNAME); String password = node.getAttributeValue(WebcrawlerConfig.ATTR_PASSWORD); if (password != null) password = ManifoldCF.deobfuscate(password); if (type.equals(WebcrawlerConfig.ATTRVALUE_BASIC)) ti.setCredential(new BasicCredential(userName, password)); else if (type.equals(WebcrawlerConfig.ATTRVALUE_NTLM)) { String domain = node.getAttributeValue(WebcrawlerConfig.ATTR_DOMAIN); ti.setCredential(new NTLMCredential(domain, userName, password)); } else if (type.equals(WebcrawlerConfig.ATTRVALUE_SESSION)) { // This is a complex credential type that cannot be easily set up with just a constructor. // Use the url regexp as the sequence key; this works as well as anything, although I haven't thought through all the implications if it gets changed. SessionCredential sc = new SessionCredential(urlDescription); // Loop through child nodes; they describe the pages that belong to the login sequence. int j = 0; while (j < node.getChildCount()) { ConfigNode child = node.getChild(j++); if (child.getType().equals(WebcrawlerConfig.NODE_AUTHPAGE)) { String authPageRegexp = child.getAttributeValue(WebcrawlerConfig.ATTR_URLREGEXP); String pageType = child.getAttributeValue(WebcrawlerConfig.ATTR_TYPE); String matchRegexp = child.getAttributeValue(WebcrawlerConfig.ATTR_MATCHREGEXP); String overrideTargetURL = child .getAttributeValue(WebcrawlerConfig.ATTR_OVERRIDETARGETURL); if (overrideTargetURL != null && overrideTargetURL.length() == 0) overrideTargetURL = null; Pattern authPattern; try { authPattern = Pattern.compile(authPageRegexp, Pattern.UNICODE_CASE); } catch (java.util.regex.PatternSyntaxException e) { throw new ManifoldCFException("Authentication page regular expression '" + authPageRegexp + "' is illegal: " + e.getMessage(), e); } Pattern matchPattern; try { matchPattern = Pattern.compile(matchRegexp, Pattern.UNICODE_CASE); } catch (java.util.regex.PatternSyntaxException e) { throw new ManifoldCFException("Match regular expression '" + matchRegexp + "' is illegal: " + e.getMessage(), e); } if (pageType.equals(WebcrawlerConfig.ATTRVALUE_FORM)) { sc.addAuthPage(authPageRegexp, authPattern, overrideTargetURL, null, null, matchRegexp, matchPattern, null, null, null, null); } else if (pageType.equals(WebcrawlerConfig.ATTRVALUE_LINK)) { sc.addAuthPage(authPageRegexp, authPattern, overrideTargetURL, matchRegexp, matchPattern, null, null, null, null, null, null); } else if (pageType.equals(WebcrawlerConfig.ATTRVALUE_REDIRECTION)) { sc.addAuthPage(authPageRegexp, authPattern, overrideTargetURL, null, null, null, null, matchRegexp, matchPattern, null, null); } else if (pageType.equals(WebcrawlerConfig.ATTRVALUE_CONTENT)) { sc.addAuthPage(authPageRegexp, authPattern, overrideTargetURL, null, null, null, null, null, null, matchRegexp, matchPattern); } else throw new ManifoldCFException("Invalid page type: " + pageType); // Finally, walk through any specified parameters int k = 0; while (k < child.getChildCount()) { ConfigNode paramNode = child.getChild(k++); if (paramNode.getType().equals(WebcrawlerConfig.NODE_AUTHPARAMETER)) { String paramName = paramNode .getAttributeValue(WebcrawlerConfig.ATTR_NAMEREGEXP); Pattern paramNamePattern; try { paramNamePattern = Pattern.compile(paramName, Pattern.UNICODE_CASE); } catch (java.util.regex.PatternSyntaxException e) { throw new ManifoldCFException("Parameter name regular expression '" + paramName + "' is illegal: " + e.getMessage(), e); } String passwordValue = paramNode .getAttributeValue(WebcrawlerConfig.ATTR_PASSWORD); String paramValue = paramNode .getAttributeValue(WebcrawlerConfig.ATTR_VALUE); if (passwordValue != null) paramValue = ManifoldCF.deobfuscate(passwordValue); sc.addPageParameter(authPageRegexp, paramName, paramNamePattern, paramValue); } } } } ti.setCredential(sc); } else throw new ManifoldCFException("Illegal credential type: " + type); patternHash.put(urlDescription, ti); } catch (PatternSyntaxException e) { throw new ManifoldCFException("Bad pattern syntax in '" + urlDescription + "'", e); } } } }
From source file:ch.entwine.weblounge.kernel.site.SiteManager.java
/** * {@inheritDoc}/*from w ww. j a v a2 s . c om*/ * * @see ch.entwine.weblounge.dispatcher.SiteDispatcherService#addSite(ch.entwine.weblounge.common.site.Site, * org.osgi.framework.ServiceReference) */ void addSite(Site site, ServiceReference reference) { synchronized (sites) { sites.add(site); siteBundles.put(site, reference.getBundle()); // Make sure we have an environment Environment env = environment; if (env == null) { logger.warn("No environment has been defined. Assuming '{}'", Environment.Production.toString().toLowerCase()); env = Environment.Production; } // Register the site urls and make sure we don't double book try { site.initialize(env); } catch (Throwable t) { logger.error("Error loading site '{}': {}", site.getIdentifier(), t.getMessage()); return; } for (SiteURL url : site.getHostnames()) { if (!env.equals(url.getEnvironment())) continue; String hostName = url.getURL().getHost(); Site registeredFirst = sitesByServerName.get(hostName); if (registeredFirst != null && !site.equals(registeredFirst)) { // Maybe a wildcard site has taken too many urls. Make sure concrete // sites are able to take over boolean replace = false; for (SiteURL siteUrl : registeredFirst.getHostnames()) { if (siteUrl.toExternalForm().contains("*")) { try { // convert the host wildcard (ex. *.domain.tld) to a valid regex // (ex. // .*\.domain\.tld) String registeredAlias = siteUrl.getURL().getHost().replace(".", "\\."); registeredAlias = registeredAlias.replace("*", ".*"); if (hostName.matches(registeredAlias)) { logger.info("Replacing wildcard registration for {} with exact match '{}'", url, site); replace = true; break; } } catch (PatternSyntaxException ex) { logger.warn("Error while trying to find a host wildcard match: " .concat(ex.getMessage())); } } } // This is a real conflict if (!replace) { logger.error("Another site is already registered to {}. Site is not registered", url); continue; } } logger.info("Site '{}' will be reachable on host {}", site.getIdentifier(), hostName); sitesByServerName.put(hostName, site); } } logger.debug("Site '{}' registered", site); // Look for content repositories ContentRepository repository = repositoriesBySite.get(site.getIdentifier()); if (repository != null && site.getContentRepository() == null) { try { repository.connect(site); site.setContentRepository(repository); logger.info("Site '{}' connected to content repository at {}", site, repository); } catch (ContentRepositoryException e) { logger.warn("Error connecting content repository " + repository + " to site '" + site + "'", e); } } else { try { Configuration config = configurationAdmin .createFactoryConfiguration("ch.entwine.weblounge.contentrepository.factory", null); Dictionary<Object, Object> properties = new Hashtable<Object, Object>(); properties.put(Site.class.getName().toLowerCase(), site.getIdentifier()); for (String name : site.getOptionNames()) { String[] values = site.getOptionValues(name); if (values.length == 1) { properties.put(name, values[0]); } else { properties.put(name, values); } } config.update(properties); repositoryConfigurations.put(site.getIdentifier(), config); } catch (IOException e) { logger.error("Unable to create configuration for content repository of site '" + site + "'", e); } } // Inform site listeners synchronized (listeners) { for (SiteServiceListener listener : listeners) { try { listener.siteAppeared(site, reference); } catch (Throwable t) { logger.error("Error during notifaction of site '{}': {}", site.getIdentifier(), t.getMessage()); return; } } } // Start the site if (site.isStartedAutomatically()) { try { logger.debug("Starting site '{}'", site); // TODO: Make sure there is a *running* content repository for this site // Alternatively, have the site implementation use a reference to the // repository and start itself once the repository switches to "running" // state (requires a repository listener) site.start(); } catch (IllegalStateException e) { logger.error("Site '{}' could not be started: {}", e.getMessage(), e); } catch (SiteException e) { logger.error("Site '{}' could not be started: {}", e.getMessage(), e); } } }
From source file:hudson.scm.AbstractCvs.java
protected PollingResult compareRemoteRevisionWith(final AbstractProject<?, ?> project, final Launcher launcher, final TaskListener listener, final SCMRevisionState baseline, final CvsRepository[] repositories) throws IOException, InterruptedException { // No previous build? everything has changed if (null == project.getLastBuild()) { listener.getLogger().println("No previous build found, scheduling build"); return PollingResult.BUILD_NOW; }// w w w . j a v a 2 s. c o m final EnvVars envVars = project.getLastBuild().getEnvironment(listener); final Date currentPollDate = Calendar.getInstance().getTime(); /* * this flag will be used to check whether a build is needed (assuming * the local and remote states are comparable and no configuration has * changed between the last build and the current one) */ boolean changesPresent = false; // Schedule a new build if the baseline isn't valid if ((baseline == null || !(baseline instanceof CvsRevisionState))) { listener.getLogger().println("Invalid baseline detected, scheduling build"); return new PollingResult(baseline, new CvsRevisionState(new HashMap<CvsRepository, List<CvsFile>>()), PollingResult.Change.INCOMPARABLE); } // convert the baseline into a use-able form final Map<CvsRepository, List<CvsFile>> remoteState = new HashMap<CvsRepository, List<CvsFile>>( ((CvsRevisionState) baseline).getModuleFiles()); // Loops through every module and check if it has changed for (CvsRepository repository : repositories) { /* * this repository setting either didn't exist or has changed since * the last build so we'll force a new build now. */ if (!remoteState.containsKey(repository)) { listener.getLogger().println("Repository not found in workspace state, scheduling build"); return new PollingResult(baseline, new CvsRevisionState(new HashMap<CvsRepository, List<CvsFile>>()), PollingResult.Change.INCOMPARABLE); } // get the list of current changed files in this repository final List<CvsFile> changes = calculateRepositoryState(project.getLastCompletedBuild().getTime(), currentPollDate, repository, listener, envVars); final List<CvsFile> remoteFiles = remoteState.get(repository); // update the remote state with the changes we've just retrieved for (CvsFile changedFile : changes) { for (CvsFile existingFile : remoteFiles) { if (!changedFile.getName().equals(existingFile.getName())) { continue; } remoteFiles.remove(existingFile); if (!changedFile.isDead()) { remoteFiles.add(changedFile); } } } // set the updated files list back into the remote state remoteState.put(repository, remoteFiles); // convert the excluded regions into patterns so we can use them as // regular expressions final List<Pattern> excludePatterns = new ArrayList<Pattern>(); for (ExcludedRegion pattern : repository.getExcludedRegions()) { try { excludePatterns.add(Pattern.compile(pattern.getPattern())); } catch (PatternSyntaxException ex) { launcher.getListener().getLogger().println("Pattern could not be compiled: " + ex.getMessage()); } } // create a list of changes we can use to filter out excluded // regions final List<CvsFile> filteredChanges = new ArrayList<CvsFile>(changes); // filter out all changes in the exclude regions for (final Pattern excludePattern : excludePatterns) { for (Iterator<CvsFile> itr = filteredChanges.iterator(); itr.hasNext();) { CvsFile change = itr.next(); if (excludePattern.matcher(change.getName()).matches()) { itr.remove(); } } } // if our list of changes isn't empty then we want to note this as // we need a build changesPresent = changesPresent || !filteredChanges.isEmpty(); } // Return the new repository state and whether we require a new build return new PollingResult(baseline, new CvsRevisionState(remoteState), changesPresent ? PollingResult.Change.SIGNIFICANT : PollingResult.Change.NONE); }