Example usage for java.util.regex Matcher groupCount

List of usage examples for java.util.regex Matcher groupCount

Introduction

In this page you can find the example usage for java.util.regex Matcher groupCount.

Prototype

public int groupCount() 

Source Link

Document

Returns the number of capturing groups in this matcher's pattern.

Usage

From source file:hudson.plugins.clearcase.ClearToolExec.java

public List<Baseline> mkbl(String name, String viewTag, String comment, boolean fullBaseline, boolean identical,
        List<String> components, String dDependsOn, String aDependsOn)
        throws IOException, InterruptedException {
    Validate.notNull(viewTag);//www . j  a v  a  2 s .c  o m
    ArgumentListBuilder cmd = new ArgumentListBuilder();
    cmd.add("mkbl");
    if (identical) {
        cmd.add("-identical");
    }
    if (StringUtils.isNotBlank(comment)) {
        cmd.add("-comment", comment);
    }
    if (fullBaseline) {
        cmd.add("-full");
    } else {
        cmd.add("-incremental");
    }

    if (StringUtils.isNotEmpty(viewTag)) {
        cmd.add("-view", viewTag);
    }

    // Make baseline only for specified components
    if (CollectionUtils.isNotEmpty(components)) {
        cmd.add("-comp", StringUtils.join(components, ','));
    }

    if (StringUtils.isNotEmpty(dDependsOn)) {
        cmd.add("-ddepends_on", dDependsOn);
    }
    if (StringUtils.isNotEmpty(aDependsOn)) {
        cmd.add("-adepends_on", aDependsOn);
    }

    cmd.add(name);

    String output = runAndProcessOutput(cmd, null, null, false, null);
    if (output.contains("cleartool: Error")) {
        throw new IOException("Failed to make baseline, reason: " + output);
    }

    Pattern pattern = Pattern.compile("Created baseline \"(.+?)\" in component \"(.+?)\"");
    Matcher matcher = pattern.matcher(output);
    List<Baseline> createdBaselinesList = new ArrayList<Baseline>();
    while (matcher.find() && matcher.groupCount() == 2) {
        String baseline = matcher.group(1);
        String component = matcher.group(2);
        createdBaselinesList.add(new Baseline(baseline, component));
    }

    return createdBaselinesList;
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

/**
 * Look for a session and if it's completed or not found try 
 *                            re-validate existing security token
 *//*from w  w  w .j a  va  2s  .co m*/
@Override
public void validate(HttpServletRequest req, String stoken) throws WsSrvException {
    Session session = activeSessions.get(stoken);

    if (!(session == null || session.isFinished()))
        // Everything fine
        return;

    getLogger(req).debug("Local session validation faied." + " Sending POST request to validate SAML session");

    // Revalidate session
    PostMethod post = new PostMethod(_login);

    try {
        String ars = createAuthnRequest(getServiceLocation(req), getRefererUrl(req));
        post.setParameter("SAMLRequest", ars);
    } catch (MarshallingException | SignatureException | IOException e) {
        //-- 63
        throw new WsSrvException(63, e);
    }

    HttpClient hc = (new HttpClientBuilder()).buildClient();
    post.setRequestHeader("Cookie",
            (String) req.getSession().getServletContext().getAttribute("scookie_name") + "=" + stoken);

    int result;
    try {
        result = hc.executeMethod(post);
    } catch (IOException e) {
        //-- 66
        throw new WsSrvException(66, e);
    }

    // Expecting 200 if cookie valid and 302 if not, rest are errors
    if (result == HttpStatus.SC_OK) {
        // Extract end process SAML response from form
        String rb;
        try {
            rb = new String(post.getResponseBody());
        } catch (IOException e) {
            //-- 67
            throw new WsSrvException(67, e);
        }

        Matcher m = SAML_RESP.matcher(rb);

        if (m.matches() && m.groupCount() == 1) {
            String gs = m.group(1);

            // Convert hex decoded javascript variable
            String msg = "";
            int start = 0;
            Matcher m1 = HP.matcher(gs);

            while (m1.find()) {
                String dc = m1.group(1);
                int i = Integer.decode("#" + dc);

                int st = m1.start();
                int ed = m1.end();

                msg += gs.substring(start, st) + (char) i;
                start = ed;
            }

            try {
                procAuthnResponse(req, msg, stoken);
            } catch (Exception e) {
                //-- 62
                throw new WsSrvException(62, e);
            }
        }
    } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
        //-- 64
        throw new WsSrvException(64, "Redirect received");
    } else {
        //-- 65
        throw new WsSrvException(65, "Unexpected http return code " + result);
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * /*  w  w  w. jav a  2 s . c  om*/
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");

        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }

        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;

        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException(
                        "The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }

        String sessionID = httpServletRequest.getSession().getId();

        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName
                + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : "
                + extraPath + " ; sessionID : " + sessionID);

        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName,
                connectorName, null);

        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;

        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();

        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;

        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);

        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();

        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            Engine.logEngine.debug(
                    "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine
                        .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        targetPort);

                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }

            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }

        HttpMethod httpMethodProxyRequest;

        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;

        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);

        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);

        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest)
                    .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }

        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "="
                            + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")
                                    : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }

            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);

        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);

        HttpState httpState = getHttpState(proxyHttpConnector, context);

        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }

        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);

        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);

        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest,
                httpState);

        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no "
                        + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }

        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding")
                    && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }

        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }

        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }

        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();

        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }

        byte[] bytesDataResult;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);

        // String resourceUrl = projectName + targetPath;

        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);

        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
            // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }

        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");

        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");

        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector,
                bytesDataResult);

        String billingClassName = context.getConnector().getBillingClassName();
        if (billingClassName != null) {
            try {
                Engine.logContext.debug("Billing class name required: " + billingClassName);
                AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance();
                Engine.logContext.debug("Executing the biller");
                biller.insertBilling(context);
            } catch (Throwable e) {
                Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
        // }
        // else {
        // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " +
        // contentType);
        //            
        // // Determine if the resource has already been cached or not
        // CacheEntry cacheEntry =
        // proxyCacheManager.getCacheEntry(resourceUrl);
        // if (cacheEntry instanceof FileCacheEntry) {
        // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry;
        // File file = new File(fileCacheEntry.fileName);
        // if (!file.exists())
        // proxyCacheManager.removeCacheEntry(cacheEntry);
        // cacheEntry = null;
        // }
        // if (cacheEntry == null) {
        // bytesDataResult = handleStringReplacements(contentType,
        // proxyHttpConnector, bytesDataResult);
        //
        // if (intProxyResponseCode == 200) {
        // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: "
        // + resourceUrl);
        // cacheEntry = proxyCacheManager.storeResponse(resourceUrl,
        // bytesDataResult);
        // cacheEntry.contentLength = bytesDataResult.length;
        // cacheEntry.contentType = contentType;
        // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " +
        // cacheEntry);
        // }
        // }
        // }

        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }

        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos)
                    : new DeflaterOutputStream(baos,
                            new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }

        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);

        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}

From source file:tr.edu.gsu.nerwip.recognition.internal.modelless.subee.Subee.java

/**
 * Takes advantage of hyperlinks in the text, in order
 * to detect entities. Most of the time, in a Wikipedia
 * article, the hyperlink is defined only for the very 
 * first occurrence of the entity. For this reason,
 * an additional processing is required to find the possible
 * other occurrences (cf. {@link #processOccurrences(Article, List)}). 
 * /*  w  w w  .  j  a v a 2s .c o m*/
 * @param article
 *       Processed article.
 * @return
 *       The list of entities detected by this method.
 * 
 * @throws ParserException
 *       Problem while parsing the hyperlinks.
 * @throws ClientProtocolException
 *       Problem while accessing Freebase.
 * @throws ParseException
 *       Problem while accessing Freebase.
 * @throws IOException
 *       Problem while accessing Freebase.
 * @throws org.json.simple.parser.ParseException
 *       Problem while accessing Freebase.
 */
private List<AbstractEntity<?>> processHyperlinks(Article article) throws ParserException,
        ClientProtocolException, ParseException, IOException, org.json.simple.parser.ParseException {
    logger.increaseOffset();
    List<AbstractEntity<?>> result = new ArrayList<AbstractEntity<?>>();

    // parse linked text to automatically get hyperlink list
    logger.log("Get hyperlink list");
    String linkedText = article.getLinkedText();
    Parser parser = new Parser(TAG_PAR_START + linkedText + TAG_PAR_END);
    NodeList linkList = parser.parse(new TagNameFilter(TAG_LINK));
    int offset = TAG_PAR_START.length();

    // process each hyperlink
    logger.log("Process each hyperlink");
    logger.increaseOffset();
    for (int i = 0; i < linkList.size(); i++) {
        LinkTag linkTag = (LinkTag) linkList.elementAt(i);
        String valueStr = linkTag.getLinkText();
        int length = valueStr.length();
        String test = linkTag.toHtml();
        logger.log("Hyperlink '" + test + "'");

        // get type from Freebase
        EntityType type = null;
        // only process strings with uppercase initial
        if (StringTools.hasInitial(valueStr)) {
            String hyperlink = linkTag.getLink();
            String[] linkParts = hyperlink.split("/");
            String lastPart = linkParts[linkParts.length - 1];
            String wikipediaTitle = URLDecoder.decode(lastPart, "UTF-8"); //TODO we may take advantage of this to automatically detect the type
            String wikipediaTitleEscaped = FbCommonTools.escapeMqlKey(wikipediaTitle); //TODO or this
            logger.log("Wikipedia title: " + wikipediaTitle);
            logger.log("Escaped Wikipedia title: " + wikipediaTitleEscaped);
            // use only the notable type
            if (notableType) {
                String possibleType = FbTypeTools.getNotableType(wikipediaTitleEscaped);
                if (possibleType == null)
                    logger.log("No notable Freebase type found for \"" + valueStr + "\"");
                else {
                    List<String> possibleTypes = new ArrayList<String>();
                    possibleTypes.add(possibleType);
                    type = retrieveEntityType(possibleTypes);
                }
            }
            // use all available types
            if (type == null) {
                List<String> possibleTypes = FbTypeTools.getAllTypes(wikipediaTitleEscaped);
                logger.log("Possible types: " + possibleTypes.toString());
                if (possibleTypes.isEmpty())
                    logger.log("WARNING: no Freebase type found at all for \"" + valueStr + "\"");
                else
                    type = retrieveEntityType(possibleTypes);
            }
        }

        // set up the entity position
        int startPos = linkTag.getStartPosition() - offset;
        int endPos = startPos + length;
        offset = offset + test.length() - length;
        //debug                        
        //String text = article.getRawText();
        //String valueStr2 = text.substring(startPos,endPos);
        //boolean test2 = valueStr.equals(valueStr2);
        //if(!test2)
        //   System.out.println("ERROR: entity and article do not match (position problem)");

        // no type: we can't create the entity
        if (type == null) {
            logger.log("WARNING: no entity was created, because no type could be identified for \"" + valueStr
                    + "\"");
        }
        // otherwise, we try
        else { // ignore if purely numerical
            if (StringTools.hasNoLetter(valueStr))
                logger.log("The string is only numerical (no letters) so no entity is created for " + valueStr);

            // ignore if recognized as a location/organization but actually a demonym
            else if (discardDemonyms && (type == EntityType.LOCATION || type == EntityType.ORGANIZATION)
                    && DEMONYMS.contains(valueStr))
                logger.log("The string is in the demonym list, so no entity is created for " + valueStr);

            else {
                //debug
                //if(valueStr.equalsIgnoreCase("Irish"))
                //   System.out.print("");

                // possibly look for an acronym
                if (useAcronyms) { // only organization and locations have relevant acronyms
                                   // (for a person, acronyms usually correspond to titles or awards)
                    if (type == EntityType.ORGANIZATION || type == EntityType.LOCATION) { // check if there's an acronym inside the entity name itself
                        Pattern r = Pattern.compile("\\([^\\(a-z]+?\\)$"); // must be in uppercase
                        Matcher m = r.matcher(valueStr);
                        if (m.find()) { // create an additional entity (acronym) with the same type
                            int last = m.groupCount();
                            String acro = m.group(last);
                            int l = acro.length();
                            acro = acro.substring(1, l - 1);
                            int s = startPos + m.start(last) + 1;
                            int e = startPos + m.end(last) - 1;
                            if (!StringTools.hasNoLetter(acro)) {
                                //debug                        
                                //String valueStr3 = text.substring(s,e);
                                //boolean test3 = acro.equals(valueStr3);
                                //if(!test3)
                                //   System.out.println("ERROR: entity acronym and article do not match (position problem)");
                                AbstractEntity<?> entity = AbstractEntity.build(type, s, e,
                                        RecognizerName.SUBEE, acro);
                                result.add(entity);
                                logger.log("Creation of an extra entity (acronym) " + entity);
                            }
                            // remove the acronym from the original string
                            valueStr = valueStr.substring(0, valueStr.length() - l).trim();
                            endPos = startPos + valueStr.length();
                        }
                        // check if there's an acronym right after the entity 
                        else {
                            r = Pattern.compile("\\([^\\(a-z]+?\\)"); // must be in uppercase
                            m = r.matcher(linkedText);
                            if (m.find(linkTag.getEndTag().getEndPosition() - TAG_PAR_START.length())) { // possibly create an additional entity (acronym) with the same type
                                int last = m.groupCount();
                                String acro = m.group(last);
                                acro = acro.substring(1, acro.length() - 1);
                                int s = m.start(last) - 1 - (offset - TAG_PAR_END.length()) + 1; // actually <a/> and not <p/>, but same length...
                                // the acronym must be right after the original entity
                                if (s == endPos + 2 && !StringTools.hasNoLetter(acro)) {
                                    int e = m.end(last) - 1 - (offset - TAG_PAR_END.length()) - 1;
                                    //debug
                                    //String valueStr3 = text.substring(s,e);
                                    //boolean test3 = acro.equals(valueStr3);
                                    //if(!test3)
                                    //   System.out.println("ERROR: entity acronym and article do not match (position problem)");
                                    AbstractEntity<?> entity = AbstractEntity.build(type, s, e,
                                            RecognizerName.SUBEE, acro);
                                    result.add(entity);
                                    logger.log("Creation of an extra entity (acronym) " + entity);
                                }
                            }
                        }
                    }
                }

                // create the entity
                AbstractEntity<?> entity = AbstractEntity.build(type, startPos, endPos, RecognizerName.SUBEE,
                        valueStr);
                result.add(entity);
                logger.log("Creation of the entity " + entity);
            }
        }
    }
    logger.decreaseOffset();

    logger.decreaseOffset();
    return result;
}

From source file:net.sf.jabref.logic.msbib.MSBibEntry.java

private void addDate(Document document, Element parent, String date, String extra) {
    if (date == null) {
        return;/* w  w  w  .java 2  s .c om*/
    }

    Matcher matcher = DATE_PATTERN.matcher(date);
    if (matcher.matches() && (matcher.groupCount() > 3)) {
        addField(document, parent, "Month" + extra, matcher.group(1));
        addField(document, parent, "Day" + extra, matcher.group(2));
        addField(document, parent, "Year" + extra, matcher.group(3));
    }
}

From source file:cat.albirar.framework.sets.registry.impl.SetRegistryDefaultImpl.java

/**
 * {@inheritDoc}//from ww w  .  j  a  va  2s . com
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public int loadFromProperties(Properties properties) throws ClassNotFoundException {
    Iterator<String> it;
    String nom;
    String valor;
    Matcher matcher;
    INamedSet<?> namedSet;
    String className;
    Class<?> modelClass;
    int n;

    Assert.notNull(properties, "The properties argument are required!");
    if (logger.isTraceEnabled()) {
        logger.trace("Processing set registry from property file!");
    }
    it = properties.stringPropertyNames().iterator();
    while (it.hasNext()) {
        nom = it.next().trim();
        valor = properties.getProperty(nom).trim();
        if (StringUtils.hasText(valor)) {
            matcher = pattern.matcher(valor);
            if (matcher.matches()) {
                className = matcher.group(1);
                // Check if available
                modelClass = getClass().getClassLoader().loadClass(className);
                namedSet = new NamedSetDefaultImpl(modelClass, nom);
                // Process properties
                for (n = 2; n < matcher.groupCount(); n++) {
                    valor = matcher.group(n).trim();
                    if (valor.startsWith(",")) {
                        valor = valor.substring(1).trim();
                    }
                    namedSet.add(valor);
                }
                putSet(namedSet);
            } else {
                logger.error("Error on load from property file. Property '" + nom + "' have incorrect format: '"
                        + valor + "'");
                throw new IllegalArgumentException("When load from property file. The property '" + nom
                        + "' is not in the expected format (" + valor
                        + "). The format should to be compatible with " + REGEX_FORMAT);
            }
        } else {
            logger.error("Error on load from property file. Property '" + nom + "' have no value");
            throw new IllegalArgumentException("When load from property file. The property '" + nom
                    + "' have no value. The format should to be compatible with " + REGEX_FORMAT);
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace(String.format("Property file processed. %d sets added!", registry.size()));
    }
    return registry.size();
}

From source file:net.sf.jabref.logic.msbib.MSBibEntry.java

private void addAddress(Document document, Element parent, String address) {
    if (address == null) {
        return;/* w  w  w . j av  a2  s. c om*/
    }

    Matcher matcher = ADDRESS_PATTERN.matcher(address);
    if (matcher.matches() && (matcher.groupCount() > 3)) {
        addField(document, parent, "City", matcher.group(1));
        addField(document, parent, "StateProvince", matcher.group(2));
        addField(document, parent, "CountryRegion", matcher.group(3));
    } else {
        /* SM: 2010.10 generalized */
        addField(document, parent, "City", address);
    }
}

From source file:com.nextdoor.bender.operation.substitution.regex.RegexSubstitution.java

/**
 * Matches a regex against a field and extracts matching groups.
 * //w  w w  . j  a  v a 2 s .  com
 * @param devent
 * @param config
 * @return
 * @throws FieldNotFoundException
 */
private Pair<String, Map<String, Object>> getRegexMatches(DeserializedEvent devent)
        throws FieldNotFoundException {
    String foundSourceField = null;
    Matcher matcher = null;

    for (String sourceField : this.srcFields) {
        String sourceValue;
        try {
            sourceValue = devent.getFieldAsString(sourceField);
        } catch (FieldNotFoundException e) {
            continue;
        }

        matcher = pattern.matcher(sourceValue);

        if (matcher.find()) {
            /*
             * Keep track of the field name that we use so it can be removed later.
             */
            foundSourceField = sourceField;
            break;
        }
    }

    if (foundSourceField == null) {
        throw new FieldNotFoundException("unable to find field in: " + this.srcFields);
    }

    /*
     * Go through each match group in the field config and attempt to add that match group from the
     * regex match. If field type coercion does not succeed then field is skipped.
     */
    Map<String, Object> matchedGroups = new HashMap<String, Object>(matcher.groupCount());
    try {
        for (RegexSubField field : this.fields) {
            String matchStrVal = matcher.group(field.getRegexGroupName());

            if (matchStrVal == null) {
                continue;
            }

            switch (field.getType()) {
            case BOOLEAN:
                matchedGroups.put(field.getKey(), Boolean.parseBoolean(matchStrVal));
                break;
            case NUMBER:
                matchedGroups.put(field.getKey(), NumberUtils.createNumber(matchStrVal));
                break;
            case STRING:
                matchedGroups.put(field.getKey(), matchStrVal);
                break;
            default:
                matchedGroups.put(field.getKey(), matchStrVal);
                break;
            }
        }
    } catch (NumberFormatException e) {
        throw new FieldNotFoundException("matched field is not a number");
    }

    return new ImmutablePair<String, Map<String, Object>>(foundSourceField, matchedGroups);
}

From source file:fedora.test.api.TestRESTAPI.java

private String extractPid(String source) {
    Matcher m = Pattern.compile("^.*/([^/]+$)").matcher(source);
    String pid = null;//from   w w  w .j  a v  a2  s  .  c om
    if (m.find() && m.groupCount() == 1) {
        pid = m.group(1);
    }
    return pid;
}

From source file:gtu._work.ui.TextScanUI.java

private void jTextField2filterAgain(boolean resetGroupListModel) {
    try {//  ww w  . j  ava 2s.c  om
        Pattern pat = Pattern.compile(contentFilter.getText());
        Matcher matcher = null;
        DefaultListModel listModel = new DefaultListModel();
        Set<String> set = new HashSet<String>();
        boolean setGroupListModel = false;
        for (String str : contentSet) {
            matcher = pat.matcher(replaceNewLineChar(str));
            if (contextFilter.getSelectedItem().equals("All")) {
                if (matcher.find()) {
                    listModel.addElement(str);
                }
            } else if (contextFilter.getSelectedItem().equals("Match")) {
                List<String> mlist = new ArrayList<String>();
                while (matcher.find()) {
                    for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                        if (!resetGroupListModel) {
                            DefaultListModel model = (DefaultListModel) groupList.getModel();
                            for (Enumeration<?> enu = model.elements(); enu.hasMoreElements();) {
                                Integer gnum = (Integer) enu.nextElement();
                                if (gnum == ii) {
                                    mlist.add(matcher.group(ii));
                                }
                            }
                        } else {
                            mlist.add(matcher.group(ii));
                        }
                    }
                    if (resetGroupListModel && !setGroupListModel) {
                        resetGroupList(matcher.groupCount());
                    }
                }
                set.add(mlist.toString());
            }
        }
        if (contextFilter.getSelectedItem().equals("Match")) {
            List<String> ssset = new ArrayList<String>(set);
            Collections.sort(ssset);
            for (String str : ssset) {
                listModel.addElement(str);
            }
        }
        matchList.setModel(listModel);
        matchLabel.setText(String.valueOf(matchList.getModel().getSize()));
    } catch (Exception ex) {
    }
    sysinfo();
}