Example usage for java.util.regex Matcher reset

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

Introduction

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

Prototype

public Matcher reset(CharSequence input) 

Source Link

Document

Resets this matcher with a new input sequence.

Usage

From source file:mitm.application.djigzo.james.matchers.SubjectTrigger.java

private String removePatternFromSubject(String subject, Matcher matcher, int level) {
    subject = matcher.replaceAll("");

    /*//from  w ww.  ja  va  2  s. c  om
     * We need to check if the new subject does not contain the pattern again.
     */
    matcher.reset(subject);

    if (matcher.find()) {
        if (level < MAX_SUBJECT_RECURSIVE_DEPTH) {
            /*
             * Recusively remove pattern
             */
            subject = removePatternFromSubject(subject, matcher, ++level);
        } else {
            logger.warn(MAX_SUBJECT_RECURSIVE_DEPTH_REACHED);

            subject = MAX_SUBJECT_RECURSIVE_DEPTH_REACHED;
        }
    }

    return subject;
}

From source file:com.google.wireless.speed.speedometer.test.UtilTest.java

public void testPingOutputPatternMatching() {
    String patternStr = "icmp_seq=([0-9]+)\\s.* time=([0-9]+(\\.[0-9]+)?)";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(
            "64 bytes from pz-in-f105.1e100.net (74.125.127.105): " + "icmp_seq=10 ttl=51 time=104 ms");

    assertEquals(matcher.find(), true);//  w w w  .jav  a2 s.com
    assertEquals(matcher.group(1), "10");
    assertEquals(matcher.group(2), "104");

    matcher.reset(
            "64 bytes from pz-in-f105.1e100.net (74.125.127.105): " + "icmp_seq=10 ttl=51 time=104.34 ms");

    assertEquals(matcher.find(), true);
    assertEquals(matcher.group(1), "10");
    assertEquals(matcher.group(2), "104.34");

    pattern = Pattern.compile("([0-9]+)\\spackets.*\\s([0-9]+)\\sreceived");
    matcher = pattern.matcher("16 packets transmitted, 12 received, 0% packet loss, time 9011ms");

    assertEquals(matcher.find(), true);
    assertEquals(matcher.group(1), "16");
    assertEquals(matcher.group(2), "12");
}

From source file:com.krawler.common.util.BaseStringUtil.java

/**
 * Substitutes all occurrences of the specified values into a template. Keys
 * for the values are specified in the template as <code>${KEY_NAME}</code>.
 * //from w w w  . j  av a2 s.  c  o  m
 * @param template
 *            the template
 * @param vars
 *            a <code>Map</code> filled with keys and values. The keys must
 *            be <code>String</code>s.
 * @return the template with substituted values
 */
public static String fillTemplate(String template, Map vars) {
    if (template == null) {
        return null;
    }

    String line = template;
    Matcher matcher = templatePattern.matcher(line);

    // Substitute multiple variables per line
    while (matcher.matches()) {
        String key = matcher.group(2);
        Object value = vars.get(key);
        if (value == null) {
            LOG.info("fillTemplate(): could not find key '" + key + "'");
            value = "";
        }
        line = matcher.group(1) + value + matcher.group(3);
        matcher.reset(line);
    }
    return line;
}

From source file:sorcer.core.provider.logger.RemoteLoggerManager.java

public String getLogComments(String filename) {
    Pattern p = null;//w w  w.j a  va  2  s . c  o  m
    try {
        // The following pattern lets this extract multiline comments that
        // appear on a single line (e.g., /* same line */) and single-line
        // comments (e.g., // some line). Furthermore, the comment may
        // appear anywhere on the line.
        p = Pattern.compile(".*/\\*.*\\*/|.*//.*$");
    } catch (PatternSyntaxException e) {
        System.err.println("Regex syntax error: " + e.getMessage());
        System.err.println("Error description: " + e.getDescription());
        System.err.println("Error index: " + e.getIndex());
        System.err.println("Erroneous pattern: " + e.getPattern());
    }
    BufferedReader br = null;
    StringBuffer bw = new StringBuffer();
    try {
        FileReader fr = new FileReader(filename);
        br = new BufferedReader(fr);
        Matcher m = p.matcher("");
        String line;
        while ((line = br.readLine()) != null) {
            m.reset(line);
            if (m.matches()) /* entire line must match */
            {
                bw.append(line + "\n");
            }
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } finally // Close file.
    {
        try {
            if (br != null)
                br.close();
        } catch (IOException e) {
        }
    }
    return bw.toString();
}

From source file:org.structr.web.servlet.UploadServlet.java

@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    try (final Tx tx = StructrApp.getInstance().tx(false, false, false)) {

        final String uuid = PathHelper.getName(request.getPathInfo());

        if (uuid == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream().write("URL path doesn't end with UUID.\n".getBytes("UTF-8"));
            return;
        }//from  www. j  ava  2  s.co  m

        Matcher matcher = threadLocalUUIDMatcher.get();
        matcher.reset(uuid);

        if (!matcher.matches()) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getOutputStream()
                    .write("ERROR (400): URL path doesn't end with UUID.\n".getBytes("UTF-8"));
            return;
        }

        final SecurityContext securityContext = getConfig().getAuthenticator()
                .initializeAndExamineRequest(request, response);

        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);

        request.setCharacterEncoding("UTF-8");

        // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
        response.setCharacterEncoding("UTF-8");

        // don't continue on redirects
        if (response.getStatus() == 302) {
            return;
        }

        uploader.setFileSizeMax(MEGABYTE
                * Long.parseLong(StructrApp.getConfigurationValue("UploadServlet.maxFileSize", MAX_FILE_SIZE)));
        uploader.setSizeMax(MEGABYTE * Long
                .parseLong(StructrApp.getConfigurationValue("UploadServlet.maxRequestSize", MAX_REQUEST_SIZE)));

        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

        while (fileItemsIterator.hasNext()) {

            final FileItem fileItem = fileItemsIterator.next();

            try {

                final GraphObject node = StructrApp.getInstance().getNodeById(uuid);

                if (node == null) {

                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    response.getOutputStream().write("ERROR (404): File not found.\n".getBytes("UTF-8"));

                }

                if (node instanceof org.structr.web.entity.AbstractFile) {

                    final org.structr.dynamic.File file = (org.structr.dynamic.File) node;
                    if (file.isGranted(Permission.write, securityContext)) {

                        FileHelper.writeToFile(file, fileItem.getInputStream());
                        file.increaseVersion();

                        // upload trigger
                        file.notifyUploadCompletion();

                    } else {

                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        response.getOutputStream()
                                .write("ERROR (403): Write access forbidden.\n".getBytes("UTF-8"));

                    }
                }

            } catch (IOException ex) {
                logger.log(Level.WARNING, "Could not write to file", ex);
            }

        }

        tx.success();

    } catch (FrameworkException | IOException | FileUploadException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

From source file:de.escidoc.core.aa.shibboleth.ShibbolethAuthenticationFilter.java

/**
 * See Interface for functional description.
 *//*ww  w . j  av a2 s  .co m*/
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final String shibSessionId = ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_SESSION_ID);
    if (shibSessionId != null && shibSessionId.length() != 0) {
        final ShibbolethDetails details = new ShibbolethDetails(null,
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_ASSERTION_COUNT),
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_AUTHENTICATION_METHOD),
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_AUTHENTICATION_INSTANT),
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_AUTHNCONTEXT_CLASS),
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_AUTHNCONTEXT_DECL),
                ((HttpServletRequest) request).getHeader(ShibbolethDetails.SHIB_IDENTITY_PROVIDER),
                shibSessionId);

        final ShibbolethUser user = new ShibbolethUser();
        final String cnAttribute = EscidocConfiguration.getInstance()
                .get(EscidocConfiguration.ESCIDOC_CORE_AA_COMMON_NAME_ATTRIBUTE_NAME);
        final String uidAttribute = EscidocConfiguration.getInstance()
                .get(EscidocConfiguration.ESCIDOC_CORE_AA_PERSISTENT_ID_ATTRIBUTE_NAME);

        // get origin
        final String origin = StringUtils.isNotEmpty(details.getShibIdentityProvider())
                ? details.getShibIdentityProvider()
                : shibSessionId;

        // get name
        final String name = StringUtils.isNotEmpty(cnAttribute)
                && StringUtils.isNotEmpty(((HttpServletRequest) request).getHeader(cnAttribute))
                        ? ((HttpServletRequest) request).getHeader(cnAttribute)
                        : shibSessionId;

        // get loginname
        final String loginname = StringUtils.isNotEmpty(uidAttribute)
                && StringUtils.isNotEmpty(((HttpServletRequest) request).getHeader(uidAttribute))
                        ? ((HttpServletRequest) request).getHeader(uidAttribute).replaceAll("\\s", "")
                        : name.replaceAll("\\s", "_") + '@' + origin;

        user.setLoginName(loginname);
        user.setName(name);

        final Matcher disposableHeaderMatcher = ShibbolethUser.DISPOSABLE_HEADER_PATTERN.matcher("");
        final Enumeration<String> enu = ((HttpServletRequest) request).getHeaderNames();
        while (enu.hasMoreElements()) {
            final String headerName = enu.nextElement();
            disposableHeaderMatcher.reset(headerName);
            if (!disposableHeaderMatcher.matches()
                    && StringUtils.isNotEmpty(((HttpServletRequest) request).getHeader(headerName))) {
                final Enumeration<String> en = ((HttpServletRequest) request).getHeaders(headerName);
                while (en.hasMoreElements()) {
                    final String header = en.nextElement();
                    final String[] parts = header.split(";");
                    if (parts != null) {
                        for (final String part : parts) {
                            user.addStringAttribute(headerName, part);
                        }
                    }
                }
            }
        }

        final ShibbolethToken authentication = new ShibbolethToken(user, null);
        authentication.setDetails(details);
        if (user.getLoginName() != null) {
            authentication.setAuthenticated(true);
        }

        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    filterChain.doFilter(request, response);
}

From source file:esg.common.util.ESGIni.java

public ESGIni loadFile(File f) {
    System.out.println("ESGIni, Loading File:  " + f.getAbsolutePath());
    BufferedReader buff = null;/*from www .  j a v  a2  s. c o  m*/
    try {
        buff = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
        String line = null;
        Matcher begin = beginPat.matcher("");
        Matcher end = endPat.matcher("");
        Matcher entry = entryPat.matcher("");
        boolean in = false;
        while ((line = buff.readLine()) != null) {
            //System.out.println("buff -> "+line);
            begin.reset(line);
            if (begin.find()) {
                in = true;
                continue;
            }
            if (in) {
                //System.out.println("IN -> "+line);
                entry.reset(line);
                if (entry.find()) {
                    String mountPoint = entry.group(1).trim();
                    String localpath = entry.group(2);
                    if (localpath.startsWith("|"))
                        localpath = localpath.substring(1).trim();
                    //System.out.println("Entry = m:["+mountPoint+"] -> l:["+localpath+"]");
                    if (!mountPoint.isEmpty() && !localpath.isEmpty()) {
                        System.out.println("Mount Point: [" + mountPoint + "] --> [" + localpath + "]");
                        mountPoints.put(mountPoint, localpath);
                    }
                } else {
                    in = false;
                    break;
                }
            }
            end.reset(line);
            if (end.find() && in) {
                in = false;
                break;
            }
        }
    } catch (java.io.IOException e) {
        e.printStackTrace();
    } finally {
        try {
            buff.close();
        } catch (Throwable t) {
        }
    }
    return this;
}

From source file:nl.mpi.lamus.archive.implementation.LamusArchiveFileHelper.java

/**
 * @see ArchiveFileHelper#correctPathElement(java.lang.String, java.lang.String) 
 *//*ww w.jav  a2s. c  o m*/
@Override
public String correctPathElement(String pathElement, String reason) {
    String temp = pathElement.replaceAll("\\&[^;]+;", "_"); // replace xml variables
    // 20..2c: space ! " # $ % &amp;  ' ( ) * +   3a..40: : ; &lt; = > ? @
    // 5b..60: [ \\ ] ^ _    7b..7f: { | } ~
    // temp=temp.replaceAll("[\\x00-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\xFF]", "_"); // replace special chars
    // temp=temp.replaceAll("[\\u0100-\\uffff]", "_"); // replace special chars
    // safe minimal MPI names may only contain [A-Za-z0-9._-], but URI can also contain
    // ! ~ * ' ( ) "unreserved" and : @ &amp; = + $ , "reserved minus ; / ?" at many
    // places. Reserved ; / ? : @ &amp; = + $ , have special meaning, see RFC2396.
    // Whitespace  is never allowed in URI, but %nn hex escapes can often be used.
    temp = temp.replaceAll("[^A-Za-z0-9._-]", "_"); // replace all except known good chars

    String result = temp;

    // in case the pathElement already contained "__" (without any invalid characters), it should stay unchanged
    if (!temp.equals(pathElement)) {
        Pattern pat = Pattern.compile("__"); // shorten double replacements
        Matcher mat = pat.matcher(temp);
        while (mat.find(0))
            mat.reset(mat.replaceFirst("_"));
        result = mat.replaceFirst("_");
    }

    if (result.length() > maxDirectoryNameLength) { // truncate but try to keep extension
        int dot = result.lastIndexOf('.');
        String suffix = "...";
        if (dot >= 0 && (result.length() - dot) <= 7) // at most '.123456'
            suffix += result.substring(dot); // otherwise: no extension to preserve!
        // archivable files all have (2) / 3 / 4 char extensions, '.class' has 5 chars
        result = result.substring(0, maxDirectoryNameLength - suffix.length()) + suffix; // suffix.length: 3..10
    }
    if (!result.equals(pathElement)) {
        if ("getFileTitle".equals(reason)) { // log noise reduction ;-)
            logger.info("correctPathElement: " + reason + ": " + pathElement + " -> " + result);
        } else {
            logger.warn("correctPathElement: " + reason + ": " + pathElement + " -> " + result);
        }
    }
    return result;

}

From source file:org.bireme.interop.toJson.File2Json.java

private void getFiles(final File filePath, final Matcher fileNameMat, final boolean recursive,
        final List<File> out) throws IOException {
    assert filePath != null;
    assert fileNameMat != null;
    assert out != null;

    if (filePath.exists()) {
        if (filePath.isFile()) { // regular file
            final String path = filePath.getName();

            if (fileNameMat.reset(path).matches()) {
                out.add(filePath);/*w  ww.  jav a  2s  . co m*/
            }
        } else { // directory
            if (recursive) {
                final File[] xfiles = filePath.listFiles();
                if (xfiles != null) {
                    for (File file : filePath.listFiles()) {
                        getFiles(file, fileNameMat, recursive, out);
                    }
                }
            }
        }
    }
}

From source file:com.hdfs.concat.crush.CrushReducer.java

/**
 * Returns the index into {@link #inputRegexList} of first pattern that matches the argument.
 *//*from   ww w  . jav  a 2 s  .c om*/
int findMatcher(String dir) {

    String outputNameWithPlaceholders = null;

    for (int i = 0; i < inputRegexList.size() && outputNameWithPlaceholders == null; i++) {
        Matcher matcher = inputRegexList.get(i);

        matcher.reset(dir);

        if (matcher.matches()) {
            return i;
        }
    }

    throw new IllegalArgumentException("No matching input regex: " + dir);
}