All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cucumber.runtime.MethodFormat Maven / Gradle / Ivy

There is a newer version: 1.2.6
Show newest version
package cucumber.runtime;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper class for formatting a method signature to a shorter form.
 */
public class MethodFormat {
    private static final Pattern METHOD_PATTERN = Pattern.compile("((?:static\\s|public\\s)+)([^\\s]*)\\s\\.?(.*)\\.([^\\(]*)\\(([^\\)]*)\\)(?: throws )?(.*)");
    private static final String PACKAGE_PATTERN = "[^,]*\\.";
    private final MessageFormat format;

    public static final MethodFormat SHORT = new MethodFormat("%c.%m(%a)");
    public static final MethodFormat FULL = new MethodFormat("%qc.%m(%a) in %s");

    /**
     * @param format the format string to use. There are several pattern tokens that can be used:
     *               
    *
  • %M: Modifiers
  • *
  • %qr: Qualified return type
  • *
  • %r: Unqualified return type
  • *
  • %qc: Qualified class
  • *
  • %c: Unqualified class
  • *
  • %m: Method name
  • *
  • %qa: Qualified arguments
  • *
  • %a: Unqualified arguments
  • *
  • %qe: Qualified exceptions
  • *
  • %e: Unqualified exceptions
  • *
  • %s: Code source
  • *
*/ public MethodFormat(String format) { String pattern = format .replaceAll("%M", "{0}") .replaceAll("%r", "{1}") .replaceAll("%qc", "{2}") .replaceAll("%m", "{3}") .replaceAll("%qa", "{4}") .replaceAll("%qe", "{5}") .replaceAll("%c", "{6}") .replaceAll("%a", "{7}") .replaceAll("%e", "{8}") .replaceAll("%s", "{9}"); this.format = new MessageFormat(pattern); } public String format(Method method) { String signature = method.toGenericString(); Matcher matcher = METHOD_PATTERN.matcher(signature); if (matcher.find()) { String M = matcher.group(1); String r = matcher.group(2); String qc = matcher.group(3); String m = matcher.group(4); String qa = matcher.group(5); String qe = matcher.group(6); String c = qc.replaceAll(PACKAGE_PATTERN, ""); String a = qa.replaceAll(PACKAGE_PATTERN, ""); String e = qe.replaceAll(PACKAGE_PATTERN, ""); String s = method.getDeclaringClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm(); return format.format(new Object[]{ M, r, qc, m, qa, qe, c, a, e, s }); } else { throw new CucumberException("Cucumber bug: Couldn't format " + signature); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy