repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
sourcepole/jasperreports-wms-component
jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/ComponentsExtensionsRegistryFactory.java
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/fill/WmsMapFillFactory.java // public class WmsMapFillFactory implements ComponentFillFactory { // // @Override // public FillComponent toFillComponent(Component component, // JRFillObjectFactory factory) { // WmsMapComponent map = (WmsMapComponent) component; // return new WmsMapFillComponent(map, factory); // } // // @Override // public FillComponent cloneFillComponent(FillComponent component, // JRFillCloneFactory factory) { // WmsMapFillComponent fillMap = (WmsMapFillComponent) component; // return new WmsMapFillComponent(fillMap.getMap()); // } // // }
import java.util.Collections; import java.util.HashMap; import java.util.List; import net.sf.jasperreports.engine.JRPropertiesMap; import net.sf.jasperreports.engine.component.ComponentManager; import net.sf.jasperreports.engine.component.ComponentsBundle; import net.sf.jasperreports.engine.component.DefaultComponentXmlParser; import net.sf.jasperreports.engine.component.DefaultComponentsBundle; import net.sf.jasperreports.engine.export.GenericElementHandler; import net.sf.jasperreports.engine.export.GenericElementHandlerBundle; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JRGraphics2DExporter; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXhtmlExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.oasis.JROdsExporter; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter; import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; import net.sf.jasperreports.extensions.ExtensionsRegistry; import net.sf.jasperreports.extensions.ExtensionsRegistryFactory; import com.sourcepole.jasperreports.wmsmap.fill.WmsMapFillFactory;
else if (JRPptxExporter.PPTX_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementPptxHandler.getInstance(); } else if (JRRtfExporter.RTF_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementRtfHandler.getInstance(); } else if (JROdtExporter.ODT_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementOdtHandler.getInstance(); } else if (JROdsExporter.ODS_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementOdsHandler.getInstance(); } } return null; } }; private static final DefaultComponentsBundle COMPONENTS_BUNDLE = new DefaultComponentsBundle(); static { DefaultComponentXmlParser parser = new DefaultComponentXmlParser(); parser.setNamespace(NAMESPACE); parser.setPublicSchemaLocation(XSD_LOCATION); parser.setInternalSchemaResource(XSD_RESOURCE); parser.setDigesterConfigurer(new WmsMapComponentsXmlDigesterConfigurer()); COMPONENTS_BUNDLE.setXmlParser(parser); WmsMapComponentManager wmsMapManager = new WmsMapComponentManager(); wmsMapManager.setDesignConverter(WmsMapDesignConverter.getInstance()); wmsMapManager.setComponentCompiler(new WmsMapCompiler());
// Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/fill/WmsMapFillFactory.java // public class WmsMapFillFactory implements ComponentFillFactory { // // @Override // public FillComponent toFillComponent(Component component, // JRFillObjectFactory factory) { // WmsMapComponent map = (WmsMapComponent) component; // return new WmsMapFillComponent(map, factory); // } // // @Override // public FillComponent cloneFillComponent(FillComponent component, // JRFillCloneFactory factory) { // WmsMapFillComponent fillMap = (WmsMapFillComponent) component; // return new WmsMapFillComponent(fillMap.getMap()); // } // // } // Path: jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/ComponentsExtensionsRegistryFactory.java import java.util.Collections; import java.util.HashMap; import java.util.List; import net.sf.jasperreports.engine.JRPropertiesMap; import net.sf.jasperreports.engine.component.ComponentManager; import net.sf.jasperreports.engine.component.ComponentsBundle; import net.sf.jasperreports.engine.component.DefaultComponentXmlParser; import net.sf.jasperreports.engine.component.DefaultComponentsBundle; import net.sf.jasperreports.engine.export.GenericElementHandler; import net.sf.jasperreports.engine.export.GenericElementHandlerBundle; import net.sf.jasperreports.engine.export.JExcelApiExporter; import net.sf.jasperreports.engine.export.JRGraphics2DExporter; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.JRXhtmlExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.oasis.JROdsExporter; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter; import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter; import net.sf.jasperreports.extensions.ExtensionsRegistry; import net.sf.jasperreports.extensions.ExtensionsRegistryFactory; import com.sourcepole.jasperreports.wmsmap.fill.WmsMapFillFactory; else if (JRPptxExporter.PPTX_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementPptxHandler.getInstance(); } else if (JRRtfExporter.RTF_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementRtfHandler.getInstance(); } else if (JROdtExporter.ODT_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementOdtHandler.getInstance(); } else if (JROdsExporter.ODS_EXPORTER_KEY.equals(exporterKey)) { return WmsMapElementOdsHandler.getInstance(); } } return null; } }; private static final DefaultComponentsBundle COMPONENTS_BUNDLE = new DefaultComponentsBundle(); static { DefaultComponentXmlParser parser = new DefaultComponentXmlParser(); parser.setNamespace(NAMESPACE); parser.setPublicSchemaLocation(XSD_LOCATION); parser.setInternalSchemaResource(XSD_RESOURCE); parser.setDigesterConfigurer(new WmsMapComponentsXmlDigesterConfigurer()); COMPONENTS_BUNDLE.setXmlParser(parser); WmsMapComponentManager wmsMapManager = new WmsMapComponentManager(); wmsMapManager.setDesignConverter(WmsMapDesignConverter.getInstance()); wmsMapManager.setComponentCompiler(new WmsMapCompiler());
wmsMapManager.setComponentFillFactory(new WmsMapFillFactory());
mfornos/humanize
humanize-emoji/src/test/java/humanize/emoji/TestEmoji.java
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java // public enum Vendor // { // DOCOMO("DoCoMo"), // KDDI("KDDI"), // SOFT_BANK("SoftBank"); // // private final String name; // // private Vendor(String name) // { // this.name = name; // } // // public String getName() // { // return name; // } // }
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import humanize.emoji.EmojiChar.Vendor; import java.util.Collection; import org.testng.annotations.Test;
EmojiChar japanFlag = Emoji.findByCodePoint(UTF16_COMPOUND_CP); assertNotNull(japanFlag, "Japan flag was not found"); } @Test public void testCodePointToRaw() { assertEquals(Emoji.codePointToString("2639"), SIMPLE_CP, "Simple face"); assertEquals(Emoji.codePointToString("1F536"), UTF16_CP, "Orange diamond"); assertEquals(Emoji.codePointsToString("0037", "20E3"), COMPOUND_CP, "7 keyboard"); assertEquals(Emoji.codePointsToString("1F1EF", "1F1F5"), UTF16_COMPOUND_CP, "Japan flag"); assertEquals(Emoji.codePointToString(""), "", "Empty"); assertNull(Emoji.codePointToString(null)); try { Emoji.codePointToString("whatever"); fail("Bad data"); } catch (NumberFormatException ex) { // } } @Test public void testVendorCodePoint() { String tradeMark = "™";
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java // public enum Vendor // { // DOCOMO("DoCoMo"), // KDDI("KDDI"), // SOFT_BANK("SoftBank"); // // private final String name; // // private Vendor(String name) // { // this.name = name; // } // // public String getName() // { // return name; // } // } // Path: humanize-emoji/src/test/java/humanize/emoji/TestEmoji.java import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.fail; import humanize.emoji.EmojiChar.Vendor; import java.util.Collection; import org.testng.annotations.Test; EmojiChar japanFlag = Emoji.findByCodePoint(UTF16_COMPOUND_CP); assertNotNull(japanFlag, "Japan flag was not found"); } @Test public void testCodePointToRaw() { assertEquals(Emoji.codePointToString("2639"), SIMPLE_CP, "Simple face"); assertEquals(Emoji.codePointToString("1F536"), UTF16_CP, "Orange diamond"); assertEquals(Emoji.codePointsToString("0037", "20E3"), COMPOUND_CP, "7 keyboard"); assertEquals(Emoji.codePointsToString("1F1EF", "1F1F5"), UTF16_COMPOUND_CP, "Japan flag"); assertEquals(Emoji.codePointToString(""), "", "Empty"); assertNull(Emoji.codePointToString(null)); try { Emoji.codePointToString("whatever"); fail("Bad data"); } catch (NumberFormatException ex) { // } } @Test public void testVendorCodePoint() { String tradeMark = "™";
EmojiChar echar = Emoji.findByVendorCodePoint(Vendor.DOCOMO, "\uF9D7");
mfornos/humanize
humanize-slim/src/main/java/humanize/util/Parameters.java
// Path: humanize-slim/src/main/java/humanize/util/Constants.java // public static final String DEFAULT_SLUG_SEPARATOR = "-"; // // Path: humanize-slim/src/main/java/humanize/time/TimeMillis.java // public enum TimeMillis // { // SECOND(1000L), // MINUTE(60000L), // HOUR(3600000L), // DAY(86400000L), // WEEK(604800000L), // // ideal months // MONTH(2628000000L); // // private long millis; // // TimeMillis(long millis) // { // this.millis = millis; // } // // public String key() // { // return this.name().toLowerCase(); // } // // public long millis() // { // return this.millis; // } // }
import static humanize.util.Constants.DEFAULT_SLUG_SEPARATOR; import humanize.time.TimeMillis; import com.google.common.base.Preconditions;
/** * The interval of the pace in milliseconds. * * @see TimeMillis */ public long interval; private PaceParameters() { // } public void checkArguments() { Preconditions.checkArgument(plural != null, "Plural parameters are required"); } public PaceParameters exts(Object... exts) { this.plural.exts(exts); return this; } public PaceParameters interval(long interval) { this.interval = interval; return this; }
// Path: humanize-slim/src/main/java/humanize/util/Constants.java // public static final String DEFAULT_SLUG_SEPARATOR = "-"; // // Path: humanize-slim/src/main/java/humanize/time/TimeMillis.java // public enum TimeMillis // { // SECOND(1000L), // MINUTE(60000L), // HOUR(3600000L), // DAY(86400000L), // WEEK(604800000L), // // ideal months // MONTH(2628000000L); // // private long millis; // // TimeMillis(long millis) // { // this.millis = millis; // } // // public String key() // { // return this.name().toLowerCase(); // } // // public long millis() // { // return this.millis; // } // } // Path: humanize-slim/src/main/java/humanize/util/Parameters.java import static humanize.util.Constants.DEFAULT_SLUG_SEPARATOR; import humanize.time.TimeMillis; import com.google.common.base.Preconditions; /** * The interval of the pace in milliseconds. * * @see TimeMillis */ public long interval; private PaceParameters() { // } public void checkArguments() { Preconditions.checkArgument(plural != null, "Plural parameters are required"); } public PaceParameters exts(Object... exts) { this.plural.exts(exts); return this; } public PaceParameters interval(long interval) { this.interval = interval; return this; }
public PaceParameters interval(TimeMillis interval)
mfornos/humanize
humanize-slim/src/main/java/humanize/util/Parameters.java
// Path: humanize-slim/src/main/java/humanize/util/Constants.java // public static final String DEFAULT_SLUG_SEPARATOR = "-"; // // Path: humanize-slim/src/main/java/humanize/time/TimeMillis.java // public enum TimeMillis // { // SECOND(1000L), // MINUTE(60000L), // HOUR(3600000L), // DAY(86400000L), // WEEK(604800000L), // // ideal months // MONTH(2628000000L); // // private long millis; // // TimeMillis(long millis) // { // this.millis = millis; // } // // public String key() // { // return this.name().toLowerCase(); // } // // public long millis() // { // return this.millis; // } // }
import static humanize.util.Constants.DEFAULT_SLUG_SEPARATOR; import humanize.time.TimeMillis; import com.google.common.base.Preconditions;
} /** * Parameterization for slugify calls. * */ public final static class SlugifyParams { /** * Builder method. * * @return a new slugify parameters instance */ public static SlugifyParams begin() { return new SlugifyParams(); } /** * Separator slug */ public String separator; /** * Controls the transformation to lowercase */ public boolean isToLowerCase; private SlugifyParams() {
// Path: humanize-slim/src/main/java/humanize/util/Constants.java // public static final String DEFAULT_SLUG_SEPARATOR = "-"; // // Path: humanize-slim/src/main/java/humanize/time/TimeMillis.java // public enum TimeMillis // { // SECOND(1000L), // MINUTE(60000L), // HOUR(3600000L), // DAY(86400000L), // WEEK(604800000L), // // ideal months // MONTH(2628000000L); // // private long millis; // // TimeMillis(long millis) // { // this.millis = millis; // } // // public String key() // { // return this.name().toLowerCase(); // } // // public long millis() // { // return this.millis; // } // } // Path: humanize-slim/src/main/java/humanize/util/Parameters.java import static humanize.util.Constants.DEFAULT_SLUG_SEPARATOR; import humanize.time.TimeMillis; import com.google.common.base.Preconditions; } /** * Parameterization for slugify calls. * */ public final static class SlugifyParams { /** * Builder method. * * @return a new slugify parameters instance */ public static SlugifyParams begin() { return new SlugifyParams(); } /** * Separator slug */ public String separator; /** * Controls the transformation to lowercase */ public boolean isToLowerCase; private SlugifyParams() {
this.separator = DEFAULT_SLUG_SEPARATOR;
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings;
package humanize.emoji; /** * <p> * Sexy and easy text interpolation of Unicode emoji code points and aliases. * </p> * <h5>Examples:</h5> * * <pre> * EmojiInterpolator.interpolateAlias(&quot;&lt;img src=\&quot;imgs/{0}.png\&quot; title=\&quot;{1}\&quot; /&gt;&quot;, &quot;Hi :sparkles:!&quot;); * // == &quot;Hi &lt;img src=\&quot;imgs/2728.png\&quot; title=\&quot;sparkles\&quot; /&gt;!&quot; * * EmojiInterpolator.interpolateUnicode(&quot;&lt;img src=\&quot;imgs/{0}.png\&quot; /&gt;&quot;, * &quot;Lorem ipsum \u2639 dolorem\uD83D\uDD36 and dolorem sit amet&quot;); * // == * // &quot;Lorem ipsum &lt;img src=\&quot;imgs/2639.png\&quot; /&gt; dolorem&lt;img src=\&quot;imgs/1f536.png\&quot; /&gt; and dolorem sit amet&quot; * * </pre> * * @see Emoji * */ public final class EmojiInterpolator { private static final Pattern EMOJI_ALIAS = Pattern.compile(":([\\w\\s-]+):");
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings; package humanize.emoji; /** * <p> * Sexy and easy text interpolation of Unicode emoji code points and aliases. * </p> * <h5>Examples:</h5> * * <pre> * EmojiInterpolator.interpolateAlias(&quot;&lt;img src=\&quot;imgs/{0}.png\&quot; title=\&quot;{1}\&quot; /&gt;&quot;, &quot;Hi :sparkles:!&quot;); * // == &quot;Hi &lt;img src=\&quot;imgs/2728.png\&quot; title=\&quot;sparkles\&quot; /&gt;!&quot; * * EmojiInterpolator.interpolateUnicode(&quot;&lt;img src=\&quot;imgs/{0}.png\&quot; /&gt;&quot;, * &quot;Lorem ipsum \u2639 dolorem\uD83D\uDD36 and dolorem sit amet&quot;); * // == * // &quot;Lorem ipsum &lt;img src=\&quot;imgs/2639.png\&quot; /&gt; dolorem&lt;img src=\&quot;imgs/1f536.png\&quot; /&gt; and dolorem sit amet&quot; * * </pre> * * @see Emoji * */ public final class EmojiInterpolator { private static final Pattern EMOJI_ALIAS = Pattern.compile(":([\\w\\s-]+):");
public static UnicodeInterpolator createEmojiInterpolator(String pattern)
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings;
super(pattern); } @Override public String replace(String alias) { // TODO better by 'de facto' standard aliases for compatibility? EmojiChar echar = Emoji.singleByAnnotations(alias); String code = echar == null ? Strings.nullToEmpty(alias) : echar.getCode().toLowerCase(); return msgFormat.render(code, alias); } } private final static class EmojiCodePointReplacer extends MessageFormatReplacer { public EmojiCodePointReplacer(String pattern) { super(pattern); } @Override public String replace(String code) { EmojiChar echar = Emoji.findByHexCode(Strings.nullToEmpty(code)); Preconditions.checkArgument(echar != null, "Code point not found [%s]", code); return msgFormat.render(code, echar.getName()); } }
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings; super(pattern); } @Override public String replace(String alias) { // TODO better by 'de facto' standard aliases for compatibility? EmojiChar echar = Emoji.singleByAnnotations(alias); String code = echar == null ? Strings.nullToEmpty(alias) : echar.getCode().toLowerCase(); return msgFormat.render(code, alias); } } private final static class EmojiCodePointReplacer extends MessageFormatReplacer { public EmojiCodePointReplacer(String pattern) { super(pattern); } @Override public String replace(String code) { EmojiChar echar = Emoji.findByHexCode(Strings.nullToEmpty(code)); Preconditions.checkArgument(echar != null, "Code point not found [%s]", code); return msgFormat.render(code, echar.getName()); } }
private static class MessageFormatReplacer implements Replacer
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings;
@Override public String replace(String alias) { // TODO better by 'de facto' standard aliases for compatibility? EmojiChar echar = Emoji.singleByAnnotations(alias); String code = echar == null ? Strings.nullToEmpty(alias) : echar.getCode().toLowerCase(); return msgFormat.render(code, alias); } } private final static class EmojiCodePointReplacer extends MessageFormatReplacer { public EmojiCodePointReplacer(String pattern) { super(pattern); } @Override public String replace(String code) { EmojiChar echar = Emoji.findByHexCode(Strings.nullToEmpty(code)); Preconditions.checkArgument(echar != null, "Code point not found [%s]", code); return msgFormat.render(code, echar.getName()); } } private static class MessageFormatReplacer implements Replacer {
// Path: humanize-slim/src/main/java/humanize/text/util/InterpolationHelper.java // public static String interpolate(String text, Pattern pattern, Replacer replacer) // { // // Matcher matcher = pattern.matcher(text); // StringBuffer sb = new StringBuffer(); // // while (matcher.find()) // { // String replacement = replacer.replace(matcher.group(1)); // matcher.appendReplacement(sb, Strings.nullToEmpty(replacement)); // } // // matcher.appendTail(sb); // // return (sb.length() > 0) ? sb.toString() : text; // } // // Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // // Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java import static humanize.text.util.InterpolationHelper.interpolate; import humanize.spi.MessageFormat; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.google.common.base.Strings; @Override public String replace(String alias) { // TODO better by 'de facto' standard aliases for compatibility? EmojiChar echar = Emoji.singleByAnnotations(alias); String code = echar == null ? Strings.nullToEmpty(alias) : echar.getCode().toLowerCase(); return msgFormat.render(code, alias); } } private final static class EmojiCodePointReplacer extends MessageFormatReplacer { public EmojiCodePointReplacer(String pattern) { super(pattern); } @Override public String replace(String code) { EmojiChar echar = Emoji.findByHexCode(Strings.nullToEmpty(code)); Preconditions.checkArgument(echar != null, "Code point not found [%s]", code); return msgFormat.render(code, echar.getName()); } } private static class MessageFormatReplacer implements Replacer {
protected final MessageFormat msgFormat;
mfornos/humanize
humanize-taglib/src/main/java/org/apache/taglibs/standard/tag/common/fmt/NumberCallSupport.java
// Path: humanize-taglib/src/main/java/humanize/taglibs/util/Convert.java // public static Number asNumber(Object input) throws JspException // { // // if (input instanceof String) // { // try // { // String istr = (String) input; // return (istr.indexOf('.') != -1) ? Double.valueOf(istr) : Long.valueOf(istr); // } catch (NumberFormatException nfe) // { // throw new JspException(Resources.getMessage("FORMAT_NUMBER_PARSE_ERROR", input), nfe); // } // } // // return (Number) input; // // }
import static humanize.taglibs.util.Convert.asNumber; import javax.servlet.jsp.JspException;
package org.apache.taglibs.standard.tag.common.fmt; public abstract class NumberCallSupport extends HumanizeSupport { private static final long serialVersionUID = 4926940370084394075L; private Object value; protected Number input; public void setValue(Object value) { this.value = value; } @Override protected void begin() throws JspException { Object tmp = value == null ? inputFromBody() : value;
// Path: humanize-taglib/src/main/java/humanize/taglibs/util/Convert.java // public static Number asNumber(Object input) throws JspException // { // // if (input instanceof String) // { // try // { // String istr = (String) input; // return (istr.indexOf('.') != -1) ? Double.valueOf(istr) : Long.valueOf(istr); // } catch (NumberFormatException nfe) // { // throw new JspException(Resources.getMessage("FORMAT_NUMBER_PARSE_ERROR", input), nfe); // } // } // // return (Number) input; // // } // Path: humanize-taglib/src/main/java/org/apache/taglibs/standard/tag/common/fmt/NumberCallSupport.java import static humanize.taglibs.util.Convert.asNumber; import javax.servlet.jsp.JspException; package org.apache.taglibs.standard.tag.common.fmt; public abstract class NumberCallSupport extends HumanizeSupport { private static final long serialVersionUID = 4926940370084394075L; private Object value; protected Number input; public void setValue(Object value) { this.value = value; } @Override protected void begin() throws JspException { Object tmp = value == null ? inputFromBody() : value;
this.input = asNumber(tmp);
mfornos/humanize
humanize-ucum/src/main/java/humanize/measure/MeasureFormatProvider.java
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // }
import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.text.Format; import java.text.NumberFormat; import java.util.Locale; import javax.measure.MeasureFormat; import javax.measure.unit.UnitFormat;
package humanize.measure; /** * <p> * Provides a JSR-275 measure formatter. Supports "standard" sub-format. * </p> * * Examples: * * <pre> * * // == &quot;100 kg&quot; * Humanize.format(&quot;{0, measure}&quot;, Measure.valueOf(100, SI.GRAM.times(1000))); * * Humanize.format(&quot;{0, measure, standard}&quot;, measure); * * // With a locale * * MessageFormat esFormat = Humanize.messageFormatInstance(&quot;{0, measure}&quot;, new Locale(&quot;es&quot;)); * esFormat.render(Measure.valueOf(1000, SI.GRAM.times(1000))); * * </pre> * */ public class MeasureFormatProvider implements FormatProvider { @Override
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // } // Path: humanize-ucum/src/main/java/humanize/measure/MeasureFormatProvider.java import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.text.Format; import java.text.NumberFormat; import java.util.Locale; import javax.measure.MeasureFormat; import javax.measure.unit.UnitFormat; package humanize.measure; /** * <p> * Provides a JSR-275 measure formatter. Supports "standard" sub-format. * </p> * * Examples: * * <pre> * * // == &quot;100 kg&quot; * Humanize.format(&quot;{0, measure}&quot;, Measure.valueOf(100, SI.GRAM.times(1000))); * * Humanize.format(&quot;{0, measure, standard}&quot;, measure); * * // With a locale * * MessageFormat esFormat = Humanize.messageFormatInstance(&quot;{0, measure}&quot;, new Locale(&quot;es&quot;)); * esFormat.render(Measure.valueOf(1000, SI.GRAM.times(1000))); * * </pre> * */ public class MeasureFormatProvider implements FormatProvider { @Override
public FormatFactory getFactory()
mfornos/humanize
humanize-icu/src/main/java/humanize/icu/spi/context/ICUContextFactory.java
// Path: humanize-slim/src/main/java/humanize/spi/context/Context.java // public interface Context // { // // String digitStrings(int index); // // String formatDate(int style, Date value); // // String formatDateTime(Date date); // // String formatDateTime(int dateStyle, int timeStyle, Date date); // // String formatDecimal(Number value); // // String formatMessage(String key, Object... args); // // ResourceBundle getBundle(); // // Locale getLocale(); // // MaskFormat getMaskFormat(); // // String getMessage(String key); // // void setLocale(Locale locale); // // } // // Path: humanize-slim/src/main/java/humanize/spi/context/ContextFactory.java // public interface ContextFactory // { // // Context createContext(); // // }
import humanize.spi.context.Context; import humanize.spi.context.ContextFactory;
package humanize.icu.spi.context; /** * Default implementation of {@link ContextFactory}. Creates * {@link DefaultICUContext} instances. * * @author michaux * */ public class ICUContextFactory implements ContextFactory { @Override
// Path: humanize-slim/src/main/java/humanize/spi/context/Context.java // public interface Context // { // // String digitStrings(int index); // // String formatDate(int style, Date value); // // String formatDateTime(Date date); // // String formatDateTime(int dateStyle, int timeStyle, Date date); // // String formatDecimal(Number value); // // String formatMessage(String key, Object... args); // // ResourceBundle getBundle(); // // Locale getLocale(); // // MaskFormat getMaskFormat(); // // String getMessage(String key); // // void setLocale(Locale locale); // // } // // Path: humanize-slim/src/main/java/humanize/spi/context/ContextFactory.java // public interface ContextFactory // { // // Context createContext(); // // } // Path: humanize-icu/src/main/java/humanize/icu/spi/context/ICUContextFactory.java import humanize.spi.context.Context; import humanize.spi.context.ContextFactory; package humanize.icu.spi.context; /** * Default implementation of {@link ContextFactory}. Creates * {@link DefaultICUContext} instances. * * @author michaux * */ public class ICUContextFactory implements ContextFactory { @Override
public Context createContext()
mfornos/humanize
humanize-slim/src/test/java/humanize/text/TestMaskFormat.java
// Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // }
import humanize.spi.MessageFormat; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import org.testng.Assert; import org.testng.annotations.Test;
} @Test public void maskParseTest() throws ParseException { Assert.assertEquals(MaskFormat.parse("", "hi"), "hi"); Assert.assertEquals(MaskFormat.parse((String) null, (String) null), null); Assert.assertEquals(MaskFormat.parse("____ ____ __", "1234 5678 90"), "1234567890"); Assert.assertEquals(MaskFormat.parse("____-__-__", "2008-11-28"), "20081128"); Assert.assertEquals(MaskFormat.parse("__\\___", "10_10"), "1010"); Assert.assertEquals(MaskFormat.parse("$$_$$", "10_10", '$'), "1010"); Assert.assertEquals(MaskFormat.parse("1bla_bla__bla bla bla 12", "1bla0bla10bla bla bla 12"), "010"); try { MaskFormat.parse("helo", "123"); Assert.fail(); } catch (ParseException ex) { // } } @Test public void messageFmtTest() {
// Path: humanize-slim/src/main/java/humanize/spi/MessageFormat.java // public class MessageFormat extends ExtendedMessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // private final static Map<String, FormatFactory> formatFactories = loadFormatFactories(); // // private static Map<String, FormatFactory> loadFormatFactories() // { // // Map<String, FormatFactory> factories = new HashMap<String, FormatFactory>(); // ServiceLoader<FormatProvider> ldr = ServiceLoader.load(FormatProvider.class); // // for (FormatProvider provider : ldr) // { // registerProvider(factories, provider); // } // // return factories; // // } // // private static void registerProvider(Map<String, FormatFactory> factories, FormatProvider provider) // { // // String formatName = provider.getFormatName(); // FormatFactory factory = provider.getFactory(); // // if (formatName.indexOf('|') > -1) // { // String[] names = formatName.split("\\|"); // for (String name : names) // { // factories.put(name, factory); // } // } else // { // factories.put(formatName, factory); // } // // } // // public MessageFormat(String pattern) // { // // super(pattern, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale, formatFactories); // // } // // public MessageFormat(String pattern, Locale locale, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, locale, registry); // // } // // public MessageFormat(String pattern, Map<String, ? extends FormatFactory> registry) // { // // super(pattern, registry); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param arguments // * The formatting arguments // * @return Formatted message // */ // public String render(Object... arguments) // { // // return format(arguments); // // } // // /** // * Formats the current pattern with the given arguments. // * // * @param buffer // * The StringBuffer // * @param arguments // * The formatting arguments // * @return StringBuffer with the formatted message // */ // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // Path: humanize-slim/src/test/java/humanize/text/TestMaskFormat.java import humanize.spi.MessageFormat; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import org.testng.Assert; import org.testng.annotations.Test; } @Test public void maskParseTest() throws ParseException { Assert.assertEquals(MaskFormat.parse("", "hi"), "hi"); Assert.assertEquals(MaskFormat.parse((String) null, (String) null), null); Assert.assertEquals(MaskFormat.parse("____ ____ __", "1234 5678 90"), "1234567890"); Assert.assertEquals(MaskFormat.parse("____-__-__", "2008-11-28"), "20081128"); Assert.assertEquals(MaskFormat.parse("__\\___", "10_10"), "1010"); Assert.assertEquals(MaskFormat.parse("$$_$$", "10_10", '$'), "1010"); Assert.assertEquals(MaskFormat.parse("1bla_bla__bla bla bla 12", "1bla0bla10bla bla bla 12"), "010"); try { MaskFormat.parse("helo", "123"); Assert.fail(); } catch (ParseException ex) { // } } @Test public void messageFmtTest() {
MessageFormat msg = new MessageFormat("Hello {0}");
mfornos/humanize
humanize-slim/src/test/java/humanize/text/UnicodeInterpolatorTest.java
// Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static org.testng.Assert.assertEquals; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import org.testng.annotations.Test;
package humanize.text; public class UnicodeInterpolatorTest { @Test public void replaceTest() {
// Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-slim/src/test/java/humanize/text/UnicodeInterpolatorTest.java import static org.testng.Assert.assertEquals; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import org.testng.annotations.Test; package humanize.text; public class UnicodeInterpolatorTest { @Test public void replaceTest() {
UnicodeInterpolator interpol = new UnicodeInterpolator(createTestReplacer());
mfornos/humanize
humanize-slim/src/test/java/humanize/text/UnicodeInterpolatorTest.java
// Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static org.testng.Assert.assertEquals; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import org.testng.annotations.Test;
package humanize.text; public class UnicodeInterpolatorTest { @Test public void replaceTest() { UnicodeInterpolator interpol = new UnicodeInterpolator(createTestReplacer()); interpol.addRange(0x20a0, 0x32ff); assertEquals(interpol.escape("♦♦ Alakazam 123 ♦♦"), "xx Alakazam 123 xx"); }
// Path: humanize-slim/src/main/java/humanize/text/util/Replacer.java // public interface Replacer // { // // String replace(String replacement); // // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-slim/src/test/java/humanize/text/UnicodeInterpolatorTest.java import static org.testng.Assert.assertEquals; import humanize.text.util.Replacer; import humanize.text.util.UnicodeInterpolator; import org.testng.annotations.Test; package humanize.text; public class UnicodeInterpolatorTest { @Test public void replaceTest() { UnicodeInterpolator interpol = new UnicodeInterpolator(createTestReplacer()); interpol.addRange(0x20a0, 0x32ff); assertEquals(interpol.escape("♦♦ Alakazam 123 ♦♦"), "xx Alakazam 123 xx"); }
private Replacer createTestReplacer()
mfornos/humanize
humanize-joda/src/main/java/humanize/time/joda/FormatTables.java
// Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaDateTimeFormat extends JodaBaseFormat<DateTimeFormatter> // { // // private static final long serialVersionUID = -7080564879531103796L; // // public JodaDateTimeFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((DateTime) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parseDateTime(source); // } // // public Format withLocale(Locale locale) // { // format = get().withLocale(locale); // return this; // } // // } // // Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaPeriodFormat extends JodaBaseFormat<PeriodFormatter> // { // // private static final long serialVersionUID = 7075580918316147610L; // // private Locale locale; // // public JodaPeriodFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((Period) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parsePeriod(source); // } // // public synchronized Format withLocale(Locale locale) // { // this.locale = locale; // this.format = get(); // return this; // } // // @Override // protected PeriodFormatter invoke() throws IllegalAccessException, InvocationTargetException // { // return (PeriodFormatter) method.invoke(null, locale); // } // // }
import humanize.time.joda.JodaTimeFormatProvider.JodaDateTimeFormat; import humanize.time.joda.JodaTimeFormatProvider.JodaPeriodFormat; import java.text.Format; import java.util.HashMap; import java.util.Map; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat;
package humanize.time.joda; /** * Table to find Joda time format variants by name. */ public final class FormatTables implements FormatNames { private static FormatTables instance; /** * Retrieves a variants map for a given format name. * * @param name * The format name * @return a mutable map of variants */ public static Map<String, Format> get(String name) { return instance().methods.get(name); } public static synchronized FormatTables instance() { if (instance == null) { instance = new FormatTables(); } return instance; } private final Map<String, Map<String, Format>> methods = new HashMap<String, Map<String, Format>>(); private FormatTables() { initialize(); } private void initialize() { Map<String, Format> jtm = new HashMap<String, Format>();
// Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaDateTimeFormat extends JodaBaseFormat<DateTimeFormatter> // { // // private static final long serialVersionUID = -7080564879531103796L; // // public JodaDateTimeFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((DateTime) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parseDateTime(source); // } // // public Format withLocale(Locale locale) // { // format = get().withLocale(locale); // return this; // } // // } // // Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaPeriodFormat extends JodaBaseFormat<PeriodFormatter> // { // // private static final long serialVersionUID = 7075580918316147610L; // // private Locale locale; // // public JodaPeriodFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((Period) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parsePeriod(source); // } // // public synchronized Format withLocale(Locale locale) // { // this.locale = locale; // this.format = get(); // return this; // } // // @Override // protected PeriodFormatter invoke() throws IllegalAccessException, InvocationTargetException // { // return (PeriodFormatter) method.invoke(null, locale); // } // // } // Path: humanize-joda/src/main/java/humanize/time/joda/FormatTables.java import humanize.time.joda.JodaTimeFormatProvider.JodaDateTimeFormat; import humanize.time.joda.JodaTimeFormatProvider.JodaPeriodFormat; import java.text.Format; import java.util.HashMap; import java.util.Map; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat; package humanize.time.joda; /** * Table to find Joda time format variants by name. */ public final class FormatTables implements FormatNames { private static FormatTables instance; /** * Retrieves a variants map for a given format name. * * @param name * The format name * @return a mutable map of variants */ public static Map<String, Format> get(String name) { return instance().methods.get(name); } public static synchronized FormatTables instance() { if (instance == null) { instance = new FormatTables(); } return instance; } private final Map<String, Map<String, Format>> methods = new HashMap<String, Map<String, Format>>(); private FormatTables() { initialize(); } private void initialize() { Map<String, Format> jtm = new HashMap<String, Format>();
JodaDateTimeFormat shortDate = newDateTimeFormat("shortDate");
mfornos/humanize
humanize-joda/src/main/java/humanize/time/joda/FormatTables.java
// Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaDateTimeFormat extends JodaBaseFormat<DateTimeFormatter> // { // // private static final long serialVersionUID = -7080564879531103796L; // // public JodaDateTimeFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((DateTime) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parseDateTime(source); // } // // public Format withLocale(Locale locale) // { // format = get().withLocale(locale); // return this; // } // // } // // Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaPeriodFormat extends JodaBaseFormat<PeriodFormatter> // { // // private static final long serialVersionUID = 7075580918316147610L; // // private Locale locale; // // public JodaPeriodFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((Period) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parsePeriod(source); // } // // public synchronized Format withLocale(Locale locale) // { // this.locale = locale; // this.format = get(); // return this; // } // // @Override // protected PeriodFormatter invoke() throws IllegalAccessException, InvocationTargetException // { // return (PeriodFormatter) method.invoke(null, locale); // } // // }
import humanize.time.joda.JodaTimeFormatProvider.JodaDateTimeFormat; import humanize.time.joda.JodaTimeFormatProvider.JodaPeriodFormat; import java.text.Format; import java.util.HashMap; import java.util.Map; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat;
ipm.put(ISO_PERIOD_ALTERNATE, newISOPeriodFormat(ISO_PERIOD_ALTERNATE)); ipm.put(ISO_PERIOD_ALTERNATE_EXTENDED, newISOPeriodFormat("alternateExtended")); ipm.put(ISO_PERIOD_ALTERNATE_WITH_WEEKS, newISOPeriodFormat("alternateWithWeeks")); ipm.put(ISO_PERIOD_ALTERNATE_EXTENDED_WITH_WEEKS, newISOPeriodFormat("alternateExtendedWithWeeks")); methods.put(FORMAT_JODA_ISO_PERIOD, ipm); } private JodaDateTimeFormat newDateTimeFormat(Class<?> clazz, String name) { try { return new JodaDateTimeFormat(clazz.getMethod(name)); } catch (Exception e) { throw new RuntimeException(e); } } private JodaDateTimeFormat newDateTimeFormat(String name) { return newDateTimeFormat(DateTimeFormat.class, name); } private JodaDateTimeFormat newISODateTimeFormat(String name) { return newDateTimeFormat(ISODateTimeFormat.class, name); }
// Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaDateTimeFormat extends JodaBaseFormat<DateTimeFormatter> // { // // private static final long serialVersionUID = -7080564879531103796L; // // public JodaDateTimeFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((DateTime) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parseDateTime(source); // } // // public Format withLocale(Locale locale) // { // format = get().withLocale(locale); // return this; // } // // } // // Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java // public static class JodaPeriodFormat extends JodaBaseFormat<PeriodFormatter> // { // // private static final long serialVersionUID = 7075580918316147610L; // // private Locale locale; // // public JodaPeriodFormat(Method method) // { // super(method); // } // // @Override // public StringBuffer format(Object param, StringBuffer appendTo, FieldPosition pos) // { // return appendTo.append(((Period) param).toString(get())); // } // // public Object parse(String source) throws ParseException // { // return format.parsePeriod(source); // } // // public synchronized Format withLocale(Locale locale) // { // this.locale = locale; // this.format = get(); // return this; // } // // @Override // protected PeriodFormatter invoke() throws IllegalAccessException, InvocationTargetException // { // return (PeriodFormatter) method.invoke(null, locale); // } // // } // Path: humanize-joda/src/main/java/humanize/time/joda/FormatTables.java import humanize.time.joda.JodaTimeFormatProvider.JodaDateTimeFormat; import humanize.time.joda.JodaTimeFormatProvider.JodaPeriodFormat; import java.text.Format; import java.util.HashMap; import java.util.Map; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISOPeriodFormat; ipm.put(ISO_PERIOD_ALTERNATE, newISOPeriodFormat(ISO_PERIOD_ALTERNATE)); ipm.put(ISO_PERIOD_ALTERNATE_EXTENDED, newISOPeriodFormat("alternateExtended")); ipm.put(ISO_PERIOD_ALTERNATE_WITH_WEEKS, newISOPeriodFormat("alternateWithWeeks")); ipm.put(ISO_PERIOD_ALTERNATE_EXTENDED_WITH_WEEKS, newISOPeriodFormat("alternateExtendedWithWeeks")); methods.put(FORMAT_JODA_ISO_PERIOD, ipm); } private JodaDateTimeFormat newDateTimeFormat(Class<?> clazz, String name) { try { return new JodaDateTimeFormat(clazz.getMethod(name)); } catch (Exception e) { throw new RuntimeException(e); } } private JodaDateTimeFormat newDateTimeFormat(String name) { return newDateTimeFormat(DateTimeFormat.class, name); } private JodaDateTimeFormat newISODateTimeFormat(String name) { return newDateTimeFormat(ISODateTimeFormat.class, name); }
private JodaPeriodFormat newISOPeriodFormat(String name)
mfornos/humanize
humanize-icu/src/main/java/humanize/icu/spi/context/ICUContext.java
// Path: humanize-icu/src/main/java/humanize/icu/spi/MessageFormat.java // public class MessageFormat extends com.ibm.icu.text.MessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // public MessageFormat(String pattern) // { // // super(pattern); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale); // // } // // public String render(Object... arguments) // { // // return format(arguments); // // } // // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // }
import humanize.icu.spi.MessageFormat; import com.ibm.icu.text.CompactDecimalFormat.CompactStyle; import com.ibm.icu.text.DateFormat; import com.ibm.icu.text.DecimalFormat; import com.ibm.icu.text.DurationFormat; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.util.ULocale;
package humanize.icu.spi.context; public interface ICUContext { String getBestPattern(String skeleton); NumberFormat getCompactDecimalFormat(); NumberFormat getCompactDecimalFormat(CompactStyle style); DecimalFormat getCurrencyFormat(); DateFormat getDateFormat(int style); DateFormat getDateTimeFormat(); DateFormat getDateTimeFormat(int dateStyle, int timeStyle); DecimalFormat getDecimalFormat(); DurationFormat getDurationFormat(); NumberFormat getNumberFormat(); DecimalFormat getPercentFormat(); DecimalFormat getPluralCurrencyFormat(); NumberFormat getRuleBasedNumberFormat(int type); ULocale getULocale();
// Path: humanize-icu/src/main/java/humanize/icu/spi/MessageFormat.java // public class MessageFormat extends com.ibm.icu.text.MessageFormat // { // // private static final long serialVersionUID = -5384364921909539710L; // // public MessageFormat(String pattern) // { // // super(pattern); // // } // // public MessageFormat(String pattern, Locale locale) // { // // super(pattern, locale); // // } // // public String render(Object... arguments) // { // // return format(arguments); // // } // // public StringBuffer render(StringBuffer buffer, Object... arguments) // { // // return format(arguments, buffer, null); // // } // // } // Path: humanize-icu/src/main/java/humanize/icu/spi/context/ICUContext.java import humanize.icu.spi.MessageFormat; import com.ibm.icu.text.CompactDecimalFormat.CompactStyle; import com.ibm.icu.text.DateFormat; import com.ibm.icu.text.DecimalFormat; import com.ibm.icu.text.DurationFormat; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.util.ULocale; package humanize.icu.spi.context; public interface ICUContext { String getBestPattern(String skeleton); NumberFormat getCompactDecimalFormat(); NumberFormat getCompactDecimalFormat(CompactStyle style); DecimalFormat getCurrencyFormat(); DateFormat getDateFormat(int style); DateFormat getDateTimeFormat(); DateFormat getDateTimeFormat(int dateStyle, int timeStyle); DecimalFormat getDecimalFormat(); DurationFormat getDurationFormat(); NumberFormat getNumberFormat(); DecimalFormat getPercentFormat(); DecimalFormat getPluralCurrencyFormat(); NumberFormat getRuleBasedNumberFormat(int type); ULocale getULocale();
MessageFormat getMessageFormat();
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/Emoji.java
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java // public enum Vendor // { // DOCOMO("DoCoMo"), // KDDI("KDDI"), // SOFT_BANK("SoftBank"); // // private final String name; // // private Vendor(String name) // { // this.name = name; // } // // public String getName() // { // return name; // } // }
import humanize.emoji.EmojiChar.Vendor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.google.common.io.CharStreams; import com.google.common.io.LineProcessor;
* @param code * the Unicode code point * @return the corresponding emoji character or null if not found */ public static EmojiChar findByCodePoint(String code) { return getInstance()._findByCodePoint(code); } /** * Finds an emoji character by hexadecimal code. * * @param hex * the hexadecimal code * @return the corresponding emoji character or null if not found */ public static EmojiChar findByHexCode(String hex) { return getInstance()._findByHexCode(hex.toUpperCase()); } /** * Finds an emoji character by vendor code point. * * @param vendor * the vendor * @param point * the raw character for the code point in the vendor space * @return the corresponding emoji character or null if not found */
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiChar.java // public enum Vendor // { // DOCOMO("DoCoMo"), // KDDI("KDDI"), // SOFT_BANK("SoftBank"); // // private final String name; // // private Vendor(String name) // { // this.name = name; // } // // public String getName() // { // return name; // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/Emoji.java import humanize.emoji.EmojiChar.Vendor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.google.common.io.CharStreams; import com.google.common.io.LineProcessor; * @param code * the Unicode code point * @return the corresponding emoji character or null if not found */ public static EmojiChar findByCodePoint(String code) { return getInstance()._findByCodePoint(code); } /** * Finds an emoji character by hexadecimal code. * * @param hex * the hexadecimal code * @return the corresponding emoji character or null if not found */ public static EmojiChar findByHexCode(String hex) { return getInstance()._findByHexCode(hex.toUpperCase()); } /** * Finds an emoji character by vendor code point. * * @param vendor * the vendor * @param point * the raw character for the code point in the vendor space * @return the corresponding emoji character or null if not found */
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point)
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java // public static UnicodeInterpolator createEmojiInterpolator(String pattern) // { // UnicodeInterpolator ui = new UnicodeInterpolator(new EmojiCodePointReplacer(pattern)); // ui.addRange(0x20a0, 0x32ff); // ui.addRange(0x1f000, 0x1ffff); // ui.addRange(0xfe4e5, 0xfe4ee); // return ui; // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static humanize.emoji.EmojiInterpolator.createEmojiInterpolator; import humanize.text.util.UnicodeInterpolator; import java.net.URL; import java.util.List; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings;
* * @param text * The text to be interpolated * @return the text with all the Emoji characters replaced by its HTML image * tag */ public static String replaceUnicodeWithImages(String text) { return getInstance().interpolate(text); } /** * Finds matching Emoji character by its annotated metadata. * * @param annotations * The annotation tags to be matched * @return A list containing the instances of the marching characters */ public static List<EmojiChar> search(String... annotations) { return Emoji.findByAnnotations(SPACE_JOINER.join(annotations)); } private static EmojiApi getInstance() { return LazyHolder.INSTANCE; } private String tagFormat;
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java // public static UnicodeInterpolator createEmojiInterpolator(String pattern) // { // UnicodeInterpolator ui = new UnicodeInterpolator(new EmojiCodePointReplacer(pattern)); // ui.addRange(0x20a0, 0x32ff); // ui.addRange(0x1f000, 0x1ffff); // ui.addRange(0xfe4e5, 0xfe4ee); // return ui; // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java import static humanize.emoji.EmojiInterpolator.createEmojiInterpolator; import humanize.text.util.UnicodeInterpolator; import java.net.URL; import java.util.List; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; * * @param text * The text to be interpolated * @return the text with all the Emoji characters replaced by its HTML image * tag */ public static String replaceUnicodeWithImages(String text) { return getInstance().interpolate(text); } /** * Finds matching Emoji character by its annotated metadata. * * @param annotations * The annotation tags to be matched * @return A list containing the instances of the marching characters */ public static List<EmojiChar> search(String... annotations) { return Emoji.findByAnnotations(SPACE_JOINER.join(annotations)); } private static EmojiApi getInstance() { return LazyHolder.INSTANCE; } private String tagFormat;
private UnicodeInterpolator interpolator;
mfornos/humanize
humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java // public static UnicodeInterpolator createEmojiInterpolator(String pattern) // { // UnicodeInterpolator ui = new UnicodeInterpolator(new EmojiCodePointReplacer(pattern)); // ui.addRange(0x20a0, 0x32ff); // ui.addRange(0x1f000, 0x1ffff); // ui.addRange(0xfe4e5, 0xfe4ee); // return ui; // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // }
import static humanize.emoji.EmojiInterpolator.createEmojiInterpolator; import humanize.text.util.UnicodeInterpolator; import java.net.URL; import java.util.List; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings;
} /** * Configures the extension for image interpolation methods. * * @param imageExt * The image extension. Defaults: "png" * @return the underlying EmojiApi instance for further chainning */ public EmojiApi imageExtension(String imageExt) { this.imageExt = imageExt; return reset(); } private String getImageFormat(String assetsURL) { String base = removeTrailingSlashes(assetsURL); return String.format(tagFormat, base, imageExt); } private UnicodeInterpolator getInterpolator() { Preconditions.checkArgument(!Strings.isNullOrEmpty(assetsURL), "Please, specify an assets URL using" + " EmojiApi.getConfiguration().assetsURL() method." + "Example: api.assetsURL(\"http://localhost:8000/imgs\")"); if (interpolator == null) {
// Path: humanize-emoji/src/main/java/humanize/emoji/EmojiInterpolator.java // public static UnicodeInterpolator createEmojiInterpolator(String pattern) // { // UnicodeInterpolator ui = new UnicodeInterpolator(new EmojiCodePointReplacer(pattern)); // ui.addRange(0x20a0, 0x32ff); // ui.addRange(0x1f000, 0x1ffff); // ui.addRange(0xfe4e5, 0xfe4ee); // return ui; // } // // Path: humanize-slim/src/main/java/humanize/text/util/UnicodeInterpolator.java // public class UnicodeInterpolator extends UnicodeEscaper // { // private final Replacer replacer; // private final Collection<Range<Integer>> ranges; // // public UnicodeInterpolator(Replacer replacer) // { // this.replacer = replacer; // this.ranges = new ArrayList<Range<Integer>>(); // } // // public void addRange(int lower, int upper) // { // addRange(Range.closed(lower, upper)); // } // // public void addRange(Range<Integer> range) // { // ranges.add(range); // } // // @Override // protected char[] escape(int codePoint) // { // for (Range<Integer> range : ranges) // { // if (range.contains(codePoint)) // { // return Strings.nullToEmpty(replacer.replace(Integer.toHexString(codePoint))).toCharArray(); // } // } // // return Character.toChars(codePoint); // } // } // Path: humanize-emoji/src/main/java/humanize/emoji/EmojiApi.java import static humanize.emoji.EmojiInterpolator.createEmojiInterpolator; import humanize.text.util.UnicodeInterpolator; import java.net.URL; import java.util.List; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Strings; } /** * Configures the extension for image interpolation methods. * * @param imageExt * The image extension. Defaults: "png" * @return the underlying EmojiApi instance for further chainning */ public EmojiApi imageExtension(String imageExt) { this.imageExt = imageExt; return reset(); } private String getImageFormat(String assetsURL) { String base = removeTrailingSlashes(assetsURL); return String.format(tagFormat, base, imageExt); } private UnicodeInterpolator getInterpolator() { Preconditions.checkArgument(!Strings.isNullOrEmpty(assetsURL), "Please, specify an assets URL using" + " EmojiApi.getConfiguration().assetsURL() method." + "Example: api.assetsURL(\"http://localhost:8000/imgs\")"); if (interpolator == null) {
interpolator = createEmojiInterpolator(getImageFormat(assetsURL));
mfornos/humanize
humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // }
import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.io.IOException; import java.io.ObjectInputStream; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.Date; import java.util.List; import java.util.Locale; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables;
package humanize.time; /** * {@link Format} implementation for {@link PrettyTime}. * */ public class PrettyTimeFormat extends Format implements FormatProvider { private static final long serialVersionUID = -1398312177396430967L;
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // } // Path: humanize-slim/src/main/java/humanize/time/PrettyTimeFormat.java import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.io.IOException; import java.io.ObjectInputStream; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.Date; import java.util.List; import java.util.Locale; import org.ocpsoft.prettytime.Duration; import org.ocpsoft.prettytime.PrettyTime; import org.ocpsoft.prettytime.TimeFormat; import org.ocpsoft.prettytime.TimeUnit; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; package humanize.time; /** * {@link Format} implementation for {@link PrettyTime}. * */ public class PrettyTimeFormat extends Format implements FormatProvider { private static final long serialVersionUID = -1398312177396430967L;
public static FormatFactory factory()
mfornos/humanize
humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // }
import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.util.Locale; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.PeriodFormatter; import com.google.common.base.Preconditions;
package humanize.time.joda; /** * {@link FormatProvider} for Joda time. * */ public class JodaTimeFormatProvider implements FormatProvider { /** * Creates a factory for the specified format. * * @return FormatFactory instance */
// Path: humanize-slim/src/main/java/humanize/spi/FormatProvider.java // public interface FormatProvider // { // // /** // * Gets the format factory. // * // * @return a {@link FormatFactory} instance // */ // FormatFactory getFactory(); // // /** // * Gets the format name that will be registered. If you want to register // * multiple names for a format then return a String with the names // * concatenated by a vertical bar character '|'. // * // * @return the format name // */ // String getFormatName(); // // } // // Path: humanize-slim/src/main/java/humanize/text/FormatFactory.java // public interface FormatFactory // { // // /** // * Creates a {@link Format} instance for the given parameters. The format // * will be accessible as '{0, name, args}'. // * // * @param name // * The format name // * @param args // * The format arguments // * @param locale // * Target locale // * @return a new {@link Format} instance // * @see MessageFormat // */ // Format getFormat(String name, String args, Locale locale); // // } // Path: humanize-joda/src/main/java/humanize/time/joda/JodaTimeFormatProvider.java import humanize.spi.FormatProvider; import humanize.text.FormatFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.util.Locale; import java.util.Map; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.PeriodFormatter; import com.google.common.base.Preconditions; package humanize.time.joda; /** * {@link FormatProvider} for Joda time. * */ public class JodaTimeFormatProvider implements FormatProvider { /** * Creates a factory for the specified format. * * @return FormatFactory instance */
public static FormatFactory factory()
mfornos/humanize
humanize-slim/src/main/java/humanize/spi/cache/GuavaCacheProvider.java
// Path: humanize-slim/src/main/java/humanize/config/ConfigLoader.java // public class ConfigLoader // { // // private static final Properties DEFAULTS = new Properties(); // public static final String CACHE_BUILDER_SPEC = "cache.builder.spec"; // // static // { // DEFAULTS.setProperty(CACHE_BUILDER_SPEC, "expireAfterAccess=1h"); // } // // public static Properties loadProperties() // { // // String path = System.getProperty("humanize.config"); // return loadProperties(path == null ? "humanize.properties" : path); // // } // // public static Properties loadProperties(final String path) // { // // Properties properties = new Properties(DEFAULTS); // // URL url = locateConfig(path); // // if (url != null) // { // try // { // URLConnection connection = url.openConnection(); // properties.load(connection.getInputStream()); // } catch (IOException e) // { // throw new RuntimeException(e); // } // } // // return properties; // // } // // public static URL locateConfig(final String path) // { // // URL url = asFile(path); // if (url == null) // { // url = asURL(path); // } // if (url == null) // { // url = asResource(path); // } // return url; // // } // // private static URL asFile(final String path) // { // URL url = null; // // File file = new File(path); // // if (file.exists()) // { // try // { // url = file.toURI().toURL(); // } catch (MalformedURLException e) // { // // // } // } // // return url; // // } // // private static final URL asResource(final String path) // { // // URL url = null; // // try // { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (contextClassLoader != null) // { // url = contextClassLoader.getResource(path); // } // if (url == null) // { // ClassLoader classLoader = ConfigLoader.class.getClassLoader(); // Preconditions.checkNotNull(classLoader, "Class Loader Not Found! :("); // url = classLoader.getResource(path); // } // } catch (Exception e) // { // // assume not found // } // // return url; // // } // // private static URL asURL(final String path) // { // // URL url = null; // // try // { // url = new URL(path); // } catch (MalformedURLException e) // { // // // } // // return url; // // } // // }
import humanize.config.ConfigLoader; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilderSpec; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache;
package humanize.spi.cache; /** * {@link CacheProvider} implementation that uses Guava caches as in memory * storage. * * @author mfornos * */ public class GuavaCacheProvider implements CacheProvider { private static final CacheBuilderSpec spec = initSpec(); private static CacheBuilderSpec initSpec() {
// Path: humanize-slim/src/main/java/humanize/config/ConfigLoader.java // public class ConfigLoader // { // // private static final Properties DEFAULTS = new Properties(); // public static final String CACHE_BUILDER_SPEC = "cache.builder.spec"; // // static // { // DEFAULTS.setProperty(CACHE_BUILDER_SPEC, "expireAfterAccess=1h"); // } // // public static Properties loadProperties() // { // // String path = System.getProperty("humanize.config"); // return loadProperties(path == null ? "humanize.properties" : path); // // } // // public static Properties loadProperties(final String path) // { // // Properties properties = new Properties(DEFAULTS); // // URL url = locateConfig(path); // // if (url != null) // { // try // { // URLConnection connection = url.openConnection(); // properties.load(connection.getInputStream()); // } catch (IOException e) // { // throw new RuntimeException(e); // } // } // // return properties; // // } // // public static URL locateConfig(final String path) // { // // URL url = asFile(path); // if (url == null) // { // url = asURL(path); // } // if (url == null) // { // url = asResource(path); // } // return url; // // } // // private static URL asFile(final String path) // { // URL url = null; // // File file = new File(path); // // if (file.exists()) // { // try // { // url = file.toURI().toURL(); // } catch (MalformedURLException e) // { // // // } // } // // return url; // // } // // private static final URL asResource(final String path) // { // // URL url = null; // // try // { // ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // if (contextClassLoader != null) // { // url = contextClassLoader.getResource(path); // } // if (url == null) // { // ClassLoader classLoader = ConfigLoader.class.getClassLoader(); // Preconditions.checkNotNull(classLoader, "Class Loader Not Found! :("); // url = classLoader.getResource(path); // } // } catch (Exception e) // { // // assume not found // } // // return url; // // } // // private static URL asURL(final String path) // { // // URL url = null; // // try // { // url = new URL(path); // } catch (MalformedURLException e) // { // // // } // // return url; // // } // // } // Path: humanize-slim/src/main/java/humanize/spi/cache/GuavaCacheProvider.java import humanize.config.ConfigLoader; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilderSpec; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; package humanize.spi.cache; /** * {@link CacheProvider} implementation that uses Guava caches as in memory * storage. * * @author mfornos * */ public class GuavaCacheProvider implements CacheProvider { private static final CacheBuilderSpec spec = initSpec(); private static CacheBuilderSpec initSpec() {
final Properties properties = ConfigLoader.loadProperties();
jawher/immanix
src/test/java/immanix/NamedStartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/NamedStartElementMatcherTest.java import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
mustSucceed(new NamedStartElementMatcher("42"), Arrays.asList(se("42"), c("hi")));
jawher/immanix
src/test/java/immanix/NamedStartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/NamedStartElementMatcherTest.java import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
mustSucceed(new NamedStartElementMatcher("42"), Arrays.asList(se("42"), c("hi")));
jawher/immanix
src/test/java/immanix/NamedStartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/NamedStartElementMatcherTest.java import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class NamedStartElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
mustSucceed(new NamedStartElementMatcher("42"), Arrays.asList(se("42"), c("hi")));
jawher/immanix
src/test/java/immanix/NamedStartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
} @Test public void testFailureMatchBecauseOfNameWithNoNsXml() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(se("42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNameWithNsXml() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(se(NS, "42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNoNsXml() throws Exception { mustFail(new NamedStartElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(se("elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNsXml() throws Exception { String ns2 = NS + "x"; mustFail(new NamedStartElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(se(ns2, "elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentType() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(c("chars"), se("42"))); } private void mustFail(NamedStartElementMatcher m, List<XMLEvent> events) throws Exception {
// Path: src/main/java/immanix/matchers/NamedStartElementMatcher.java // public class NamedStartElementMatcher extends BaseEventMatcher<StartElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the start element's namespace uri // * @param name the start element's name to match // */ // public NamedStartElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isStartElement()) { // QName qName = e.asStartElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "<" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/NamedStartElementMatcherTest.java import immanix.matchers.NamedStartElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; } @Test public void testFailureMatchBecauseOfNameWithNoNsXml() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(se("42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNameWithNsXml() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(se(NS, "42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNoNsXml() throws Exception { mustFail(new NamedStartElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(se("elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNsXml() throws Exception { String ns2 = NS + "x"; mustFail(new NamedStartElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(se(ns2, "elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentType() throws Exception { mustFail(new NamedStartElementMatcher("elem"), Arrays.<XMLEvent>asList(c("chars"), se("42"))); } private void mustFail(NamedStartElementMatcher m, List<XMLEvent> events) throws Exception {
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/StartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se;
package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/StartElementMatcherTest.java import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception {
StartElementMatcher m = new StartElementMatcher();
jawher/immanix
src/test/java/immanix/StartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se;
package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher();
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/StartElementMatcherTest.java import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher();
List<XMLEvent> events = Arrays.asList(se("42"), c("hi"));
jawher/immanix
src/test/java/immanix/StartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se;
package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher();
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/StartElementMatcherTest.java import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher();
List<XMLEvent> events = Arrays.asList(se("42"), c("hi"));
jawher/immanix
src/test/java/immanix/StartElementMatcherTest.java
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se;
package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher(); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"));
// Path: src/main/java/immanix/matchers/StartElementMatcher.java // public class StartElementMatcher extends BaseEventMatcher<StartElement> { // // @Override // protected boolean accept(XMLEvent e) { // if (!e.isStartElement()) { // //System.out.println("failed to match <"); // } // return e.isStartElement(); // } // // @Override // protected StartElement process(XMLEvent e) { // return e.asStartElement(); // } // // @Override // protected String expects() { // return "Start of any element"; // } // // @Override // public String toString() { // return "Start of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/StartElementMatcherTest.java import org.junit.Test; import immanix.matchers.StartElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; package immanix; public class StartElementMatcherTest { @Test public void testSuccessMatch() throws Exception { StartElementMatcher m = new StartElementMatcher(); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/UntilMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/UntilMatcherTest.java import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception {
UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
jawher/immanix
src/test/java/immanix/UntilMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/UntilMatcherTest.java import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception {
UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
jawher/immanix
src/test/java/immanix/UntilMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/UntilMatcherTest.java import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
jawher/immanix
src/test/java/immanix/UntilMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/UntilMatcherTest.java import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2));
List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
jawher/immanix
src/test/java/immanix/UntilMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // }
import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*;
package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2)); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
// Path: src/main/java/immanix/matchers/UntilMatcher.java // public class UntilMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public UntilMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext()) { // reader.next(); // } else { // return MatcherResult.failure(reader, // res.errorMessage+"\n"+ // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // } // return res; // } // // @Override // public String toString() { // return "(Until " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // Path: src/test/java/immanix/UntilMatcherTest.java import immanix.matchers.UntilMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static immanix.utils.XMLEventsUtils.se; import static org.junit.Assert.*; package immanix; public class UntilMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilMatcher<Object> m = new UntilMatcher<Object>(new LatentPacman(2)); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/AtLeastButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception {
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtLeastButFiniteMatcherTest.java import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception {
StaxMatcher< Object> delegateMatcher = new FullPacman(6);
jawher/immanix
src/test/java/immanix/AtLeastButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher);
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtLeastButFiniteMatcherTest.java import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher);
AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4);
jawher/immanix
src/test/java/immanix/AtLeastButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtLeastButFiniteMatcherTest.java import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
StaxMatcher<Object> delegateMatcher = new HungryPacman(3);
jawher/immanix
src/test/java/immanix/AtLeastButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(delegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m);
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtLeastButFiniteMatcherTest.java import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(delegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m);
List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
jawher/immanix
src/test/java/immanix/AtLeastButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(delegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
// Path: src/main/java/immanix/matchers/AtLeastButFiniteMatcher.java // public class AtLeastButFiniteMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtLeastButFiniteMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // partialRes.errorMessage + "\n" + // toString() + " failed as its delegate matcher failed to match after " + (i + 1) + " iterations with the previous error"); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // MatcherResult<T> partialRes = null; // while (!(partialRes = delegate.match(reader)).isFailure()) { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } // // @Override // public String toString() { // return "(AtLeastButFinite(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtLeastButFiniteMatcherTest.java import org.junit.Test; import immanix.matchers.AtLeastButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtLeastButFiniteMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher< Object> delegateMatcher = new FullPacman(6); StaxMatcher<Object> spyDelegateMatcher = spy(delegateMatcher); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(spyDelegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); sm.match(null); verify(spyDelegateMatcher, times(7)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtLeastButFiniteMatcher<Object> m = new AtLeastButFiniteMatcher<Object>(delegateMatcher, 4); AtLeastButFiniteMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/NamedEndElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedEndElementMatcher.java // public class NamedEndElementMatcher extends BaseEventMatcher<EndElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the end element's namespace uri // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isEndElement()) { // QName qName = e.asEndElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "</" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import immanix.matchers.NamedEndElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*;
package immanix; public class NamedEndElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
// Path: src/main/java/immanix/matchers/NamedEndElementMatcher.java // public class NamedEndElementMatcher extends BaseEventMatcher<EndElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the end element's namespace uri // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isEndElement()) { // QName qName = e.asEndElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "</" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/NamedEndElementMatcherTest.java import immanix.matchers.NamedEndElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*; package immanix; public class NamedEndElementMatcherTest { public static final String NS = "http://immanix.net/ns"; @Test public void testSuccessMatchOnLocalPartWithNoNsXml() throws Exception {
mustSucceed(new NamedEndElementMatcher("42"), Arrays.asList(ee("42"), c("hi")));
jawher/immanix
src/test/java/immanix/NamedEndElementMatcherTest.java
// Path: src/main/java/immanix/matchers/NamedEndElementMatcher.java // public class NamedEndElementMatcher extends BaseEventMatcher<EndElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the end element's namespace uri // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isEndElement()) { // QName qName = e.asEndElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "</" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import immanix.matchers.NamedEndElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*;
@Test public void testFailureMatchBecauseOfDifferentNameWithNoNsXml() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(ee("42"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentNameWithNsXml() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(ee(NS, "42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNoNsXml() throws Exception { mustFail(new NamedEndElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(ee("elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNsXml() throws Exception { mustFail(new NamedEndElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(ee(NS + "x", "elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentType() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(c("chars"), ee("42"))); } private void mustFail(NamedEndElementMatcher m, List<XMLEvent> events) throws Exception {
// Path: src/main/java/immanix/matchers/NamedEndElementMatcher.java // public class NamedEndElementMatcher extends BaseEventMatcher<EndElement> { // private final String namespaceURI; // private final String name; // // /** // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String name) { // this.name = name; // this.namespaceURI = null; // } // // /** // * @param namespaceURI the end element's namespace uri // * @param name the end element's name to match // */ // public NamedEndElementMatcher(String namespaceURI, String name) { // this.name = name; // this.namespaceURI = namespaceURI; // } // // @Override // protected boolean accept(XMLEvent e) { // if (e.isEndElement()) { // QName qName = e.asEndElement().getName(); // return name.equals(qName.getLocalPart()) && (namespaceURI == null || namespaceURI.equals // (qName.getNamespaceURI())); // } // return false; // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return toString(); // } // // @Override // public String toString() { // return "</" + (namespaceURI == null ? "" : "{" + namespaceURI + "}") + name + ">"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/NamedEndElementMatcherTest.java import immanix.matchers.NamedEndElementMatcher; import immanix.readers.ReplayEventReader; import org.junit.Test; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*; @Test public void testFailureMatchBecauseOfDifferentNameWithNoNsXml() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(ee("42"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentNameWithNsXml() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(ee(NS, "42"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNoNsXml() throws Exception { mustFail(new NamedEndElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(ee("elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfNsWithNsXml() throws Exception { mustFail(new NamedEndElementMatcher(NS, "elem"), Arrays.<XMLEvent>asList(ee(NS + "x", "elem"), c("chars"))); } @Test public void testFailureMatchBecauseOfDifferentType() throws Exception { mustFail(new NamedEndElementMatcher("elem"), Arrays.<XMLEvent>asList(c("chars"), ee("42"))); } private void mustFail(NamedEndElementMatcher m, List<XMLEvent> events) throws Exception {
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/CharsMatcherTest.java
// Path: src/main/java/immanix/matchers/CharsMatcher.java // public class CharsMatcher extends BaseEventMatcher<String> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isCharacters(); // } // // @Override // protected String process(XMLEvent e) { // return e.asCharacters().getData(); // } // // @Override // protected String expects() { // return "Characters"; // } // // @Override // public String toString() { // return "Characters"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import org.junit.Test; import immanix.matchers.CharsMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*;
package immanix; public class CharsMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/CharsMatcher.java // public class CharsMatcher extends BaseEventMatcher<String> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isCharacters(); // } // // @Override // protected String process(XMLEvent e) { // return e.asCharacters().getData(); // } // // @Override // protected String expects() { // return "Characters"; // } // // @Override // public String toString() { // return "Characters"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/CharsMatcherTest.java import org.junit.Test; import immanix.matchers.CharsMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*; package immanix; public class CharsMatcherTest { @Test public void testSuccessMatch() throws Exception {
CharsMatcher m = new CharsMatcher();
jawher/immanix
src/test/java/immanix/CharsMatcherTest.java
// Path: src/main/java/immanix/matchers/CharsMatcher.java // public class CharsMatcher extends BaseEventMatcher<String> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isCharacters(); // } // // @Override // protected String process(XMLEvent e) { // return e.asCharacters().getData(); // } // // @Override // protected String expects() { // return "Characters"; // } // // @Override // public String toString() { // return "Characters"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import org.junit.Test; import immanix.matchers.CharsMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*;
package immanix; public class CharsMatcherTest { @Test public void testSuccessMatch() throws Exception { CharsMatcher m = new CharsMatcher(); CharsMatcher sm = spy(m); List<XMLEvent> events = Arrays.asList(c("hi"), se("42"));
// Path: src/main/java/immanix/matchers/CharsMatcher.java // public class CharsMatcher extends BaseEventMatcher<String> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isCharacters(); // } // // @Override // protected String process(XMLEvent e) { // return e.asCharacters().getData(); // } // // @Override // protected String expects() { // return "Characters"; // } // // @Override // public String toString() { // return "Characters"; // } // // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/CharsMatcherTest.java import org.junit.Test; import immanix.matchers.CharsMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*; package immanix; public class CharsMatcherTest { @Test public void testSuccessMatch() throws Exception { CharsMatcher m = new CharsMatcher(); CharsMatcher sm = spy(m); List<XMLEvent> events = Arrays.asList(c("hi"), se("42"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/UntilButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*;
package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/UntilButFiniteMatcherTest.java import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*; package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception {
UntilButFiniteMatcher<Object> m = new UntilButFiniteMatcher<Object>(new LatentPacman(2), 10);
jawher/immanix
src/test/java/immanix/UntilButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*;
package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/UntilButFiniteMatcherTest.java import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*; package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception {
UntilButFiniteMatcher<Object> m = new UntilButFiniteMatcher<Object>(new LatentPacman(2), 10);
jawher/immanix
src/test/java/immanix/UntilButFiniteMatcherTest.java
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*;
package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilButFiniteMatcher<Object> m = new UntilButFiniteMatcher<Object>(new LatentPacman(2), 10); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
// Path: src/main/java/immanix/matchers/UntilButFiniteMatcher.java // public class UntilButFiniteMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // private final int giveUpBarrier; // // public UntilButFiniteMatcher(StaxMatcher<T> delegate, int giveUpBarrier) { // this.delegate = delegate; // this.giveUpBarrier = giveUpBarrier; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = null; // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // while ((res = delegate.match(reader)).isFailure()) { // reader = res.reader.unwrap(); // if (reader.hasNext() && consumedEvents.size() < giveUpBarrier) { // consumedEvents.add(reader.next()); // } else { // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, reader), // toString() + " failed: the stream was consumed without the delegate matcher '" + delegate + // "' matching"); // } // // } // consumedEvents.addAll(res.consumedEvents); // return MatcherResult.success(res.data, res.reader, consumedEvents); // } // // // @Override // public String toString() { // return "(UntilButFinite " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/LatentPacman.java // public class LatentPacman extends StaxMatcher<Object> { // int count; // // public LatentPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- <= 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, ""); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/UntilButFiniteMatcherTest.java import immanix.matchers.UntilButFiniteMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.LatentPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static immanix.utils.XMLEventsUtils.*; import static org.junit.Assert.*; package immanix; public class UntilButFiniteMatcherTest { @Test public void testSuccessMatch() throws Exception { UntilButFiniteMatcher<Object> m = new UntilButFiniteMatcher<Object>(new LatentPacman(2), 10); List<XMLEvent> events = Arrays.asList(se("42"), c("hi"), se("remains"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/EndElementMatcherTest.java
// Path: src/main/java/immanix/matchers/EndElementMatcher.java // public class EndElementMatcher extends BaseEventMatcher<EndElement> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isEndElement(); // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return "End of any element"; // } // // @Override // public String toString() { // return "End of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import org.junit.Test; import immanix.matchers.EndElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*;
package immanix; public class EndElementMatcherTest { @Test public void testSuccessMatch() throws Exception {
// Path: src/main/java/immanix/matchers/EndElementMatcher.java // public class EndElementMatcher extends BaseEventMatcher<EndElement> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isEndElement(); // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return "End of any element"; // } // // @Override // public String toString() { // return "End of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/EndElementMatcherTest.java import org.junit.Test; import immanix.matchers.EndElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*; package immanix; public class EndElementMatcherTest { @Test public void testSuccessMatch() throws Exception {
EndElementMatcher m = new EndElementMatcher();
jawher/immanix
src/test/java/immanix/EndElementMatcherTest.java
// Path: src/main/java/immanix/matchers/EndElementMatcher.java // public class EndElementMatcher extends BaseEventMatcher<EndElement> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isEndElement(); // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return "End of any element"; // } // // @Override // public String toString() { // return "End of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // }
import org.junit.Test; import immanix.matchers.EndElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*;
package immanix; public class EndElementMatcherTest { @Test public void testSuccessMatch() throws Exception { EndElementMatcher m = new EndElementMatcher(); EndElementMatcher sm = spy(m); List<XMLEvent> events = Arrays.asList(ee("42"), c("hi"));
// Path: src/main/java/immanix/matchers/EndElementMatcher.java // public class EndElementMatcher extends BaseEventMatcher<EndElement> { // // @Override // protected boolean accept(XMLEvent e) { // return e.isEndElement(); // } // // @Override // protected EndElement process(XMLEvent e) { // return e.asEndElement(); // } // // @Override // protected String expects() { // return "End of any element"; // } // // @Override // public String toString() { // return "End of any element"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public class XMLEventsUtils { // private static XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // // public static XMLEvent a(String name, String val) { // return eventFactory.createAttribute(name, val); // } // // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // // public static XMLEvent se(String name) { // return eventFactory.createStartElement(new QName(name), null, null); // } // // public static XMLEvent se(String namespaceURI, String name) { // return eventFactory.createStartElement(new QName(namespaceURI, name), null, null); // } // // public static XMLEvent ee(String name) { // return eventFactory.createEndElement(new QName(name), null); // } // // public static XMLEvent ee(String namespaceURI, String name) { // return eventFactory.createEndElement(new QName(namespaceURI, name), null); // } // // public static List<XMLEvent> evts(XMLEvent... items) { // return Arrays.asList(items); // } // // public static List<XMLEvent> close(List<XMLEvent> start) { // List<XMLEvent> res = new ArrayList<XMLEvent>(); // for (int i = start.size() - 1; i >= 0; i--) { // if (start.get(i).isStartElement()) { // res.add(ee(start.get(i).asStartElement().getName() // .getLocalPart())); // } // } // return res; // } // } // Path: src/test/java/immanix/EndElementMatcherTest.java import org.junit.Test; import immanix.matchers.EndElementMatcher; import immanix.readers.ReplayEventReader; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import static immanix.utils.XMLEventsUtils.*; package immanix; public class EndElementMatcherTest { @Test public void testSuccessMatch() throws Exception { EndElementMatcher m = new EndElementMatcher(); EndElementMatcher sm = spy(m); List<XMLEvent> events = Arrays.asList(ee("42"), c("hi"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/NTimesMatcherTest.java
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST));
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/NTimesMatcherTest.java import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST));
NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4);
jawher/immanix
src/test/java/immanix/NTimesMatcherTest.java
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/NTimesMatcherTest.java import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
StaxMatcher<Object> delegateMatcher = new HungryPacman(4);
jawher/immanix
src/test/java/immanix/NTimesMatcherTest.java
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m);
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/NTimesMatcherTest.java import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m);
List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
jawher/immanix
src/test/java/immanix/NTimesMatcherTest.java
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/NTimesMatcherTest.java import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class NTimesMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, null, Collections.EMPTY_LIST)); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 4); NTimesMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/NTimesMatcherTest.java
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("_1"), res.reader.next()); } @Test public void testReaderStateInCaseOfSuccess() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("d"), res.reader.next()); } @Test public void testSuccessWhenWantedNumberOfMatchingsIsReached() throws Exception {
// Path: src/main/java/immanix/matchers/NTimesMatcher.java // public class NTimesMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private int n; // // public NTimesMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // MatcherResult<List<T>> res = new AtMostMatcher<T>(delegate, n).match(reader); // if (res.isFailure()) { // return MatcherResult.failure(res.reader, res.errorMessage + "\n" + toString() + " failed due to the previous error"); // } else { // if (res.data.size() < n) { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader), // toString() + " failed as the delegate matcher matched only " + res.data.size() + " time(s) instead of " + n); // } else { // return res; // } // } // } // // @Override // public String toString() { // return "(Times(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/NTimesMatcherTest.java import org.junit.Test; import immanix.matchers.NTimesMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("_1"), res.reader.next()); } @Test public void testReaderStateInCaseOfSuccess() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); NTimesMatcher<Object> m = new NTimesMatcher<Object>(delegateMatcher, 3); NTimesMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("d"), res.reader.next()); } @Test public void testSuccessWhenWantedNumberOfMatchingsIsReached() throws Exception {
StaxMatcher<Object> delegateMatcher = new FullPacman(4);
jawher/immanix
src/test/java/immanix/CondMatcherTest.java
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*;
package immanix; public class CondMatcherTest { @Test public void testDelegateMatcherIsCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList();
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/CondMatcherTest.java import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*; package immanix; public class CondMatcherTest { @Test public void testDelegateMatcherIsCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList();
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/CondMatcherTest.java
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*;
package immanix; public class CondMatcherTest { @Test public void testDelegateMatcherIsCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList(); ReplayEventReader reader = new ReplayEventReader(events); StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, reader, Collections.EMPTY_LIST));
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/CondMatcherTest.java import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*; package immanix; public class CondMatcherTest { @Test public void testDelegateMatcherIsCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList(); ReplayEventReader reader = new ReplayEventReader(events); StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success(null, reader, Collections.EMPTY_LIST));
CondMatcher<Object> m = new CondMatcher<Object>(delegateMatcher) {
jawher/immanix
src/test/java/immanix/CondMatcherTest.java
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*;
assertTrue(sm.match(null).isFailure()); } @Test public void testSuccessWhenValidateReturnsTrueCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList(); ReplayEventReader reader = new ReplayEventReader(events); StaxMatcher<String> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success("magic !", reader, Collections.EMPTY_LIST)); CondMatcher<String> m = new CondMatcher<String>(delegateMatcher) { @Override public boolean validate(String data) { return true; } @Override public String conditionInEnglish() { return "Nothing"; } }; CondMatcher<String> sm = spy(m); assertFalse(sm.match(null).isFailure()); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/CondMatcherTest.java import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*; assertTrue(sm.match(null).isFailure()); } @Test public void testSuccessWhenValidateReturnsTrueCalled() throws Exception { List<XMLEvent> events = Arrays.<XMLEvent>asList(); ReplayEventReader reader = new ReplayEventReader(events); StaxMatcher<String> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.success("magic !", reader, Collections.EMPTY_LIST)); CondMatcher<String> m = new CondMatcher<String>(delegateMatcher) { @Override public boolean validate(String data) { return true; } @Override public String conditionInEnglish() { return "Nothing"; } }; CondMatcher<String> sm = spy(m); assertFalse(sm.match(null).isFailure()); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
StaxMatcher<Object> delegateMatcher = new HungryPacman(4);
jawher/immanix
src/test/java/immanix/CondMatcherTest.java
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*;
public boolean validate(String data) { return true; } @Override public String conditionInEnglish() { return "Nothing"; } }; CondMatcher<String> sm = spy(m); assertFalse(sm.match(null).isFailure()); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); CondMatcher<Object> m = new CondMatcher<Object>(delegateMatcher) { @Override public boolean validate(Object data) { return false; } @Override public String conditionInEnglish() { return "Nothing"; } };
// Path: src/main/java/immanix/matchers/CondMatcher.java // public abstract class CondMatcher<T> extends StaxMatcher<T> { // private final StaxMatcher<T> delegate; // // public CondMatcher(StaxMatcher<T> delegate) { // this.delegate = delegate; // } // // @Override // public MatcherResult<T> match(EventReader reader) throws XMLStreamException { // MatcherResult<T> res = delegate.match(reader); // if (res.isFailure()) { // return res; // } else { // if (validate(res.data)) { // return res; // } else { // return MatcherResult.failure(new BacktrackEventReader(res.consumedEvents, res.reader.unwrap()), // toString() + " failed as the delegate matcher's '" + delegate.toString() + // "' result didn't satisfy the condition '" + conditionInEnglish() + // "'"); // } // } // } // // /** // * @param data the delgate matcher's result // * @return whether to accept this result or not // */ // public abstract boolean validate(T data); // // public abstract String conditionInEnglish(); // // @Override // public String toString() { // return "(cond " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/CondMatcherTest.java import immanix.matchers.CondMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.HungryPacman; import org.junit.Test; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static immanix.utils.XMLEventsUtils.c; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public boolean validate(String data) { return true; } @Override public String conditionInEnglish() { return "Nothing"; } }; CondMatcher<String> sm = spy(m); assertFalse(sm.match(null).isFailure()); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); CondMatcher<Object> m = new CondMatcher<Object>(delegateMatcher) { @Override public boolean validate(Object data) { return false; } @Override public String conditionInEnglish() { return "Nothing"; } };
List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
jawher/immanix
src/test/java/immanix/AtMostMatcherTest.java
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST));
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtMostMatcherTest.java import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST));
AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4);
jawher/immanix
src/test/java/immanix/AtMostMatcherTest.java
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtMostMatcherTest.java import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception {
StaxMatcher<Object> delegateMatcher = new HungryPacman(4);
jawher/immanix
src/test/java/immanix/AtMostMatcherTest.java
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m);
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtMostMatcherTest.java import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m);
List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
jawher/immanix
src/test/java/immanix/AtMostMatcherTest.java
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtMostMatcherTest.java import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; package immanix; public class AtMostMatcherTest { @Test public void testDelegateMatcherIsCalledCorrectly() throws Exception { StaxMatcher<Object> delegateMatcher = mock(StaxMatcher.class); when(delegateMatcher.match(null)).thenReturn(MatcherResult.<Object>success("S", null, Collections.EMPTY_LIST)); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); sm.match(null); verify(delegateMatcher, times(5)).match(null); } @Test public void testReaderIsRestoredInCaseOfFailure() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(4); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f"));
ReplayEventReader reader = new ReplayEventReader(events);
jawher/immanix
src/test/java/immanix/AtMostMatcherTest.java
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // }
import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c;
AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("_1"), res.reader.next()); } @Test public void testReaderStateInCaseOfSuccess() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("d"), res.reader.next()); } @Test public void testSuccessWhenWantedNumberOfMatchingsIsReached() throws Exception {
// Path: src/main/java/immanix/matchers/AtMostMatcher.java // public class AtMostMatcher<T> extends StaxMatcher<List<T>> { // private final StaxMatcher<T> delegate; // private final int n; // // public AtMostMatcher(StaxMatcher<T> delegate, int n) { // this.delegate = delegate; // this.n = n; // } // // @Override // public MatcherResult<List<T>> match(EventReader reader) throws XMLStreamException { // List<T> res = new ArrayList<T>(); // List<XMLEvent> consumedEvents = new ArrayList<XMLEvent>(); // // for (int i = 0; i < n; i++) { // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // res.add(partialRes.data); // consumedEvents.addAll(partialRes.consumedEvents); // reader = partialRes.reader; // } // } // // MatcherResult<T> partialRes = delegate.match(reader); // if (partialRes.isFailure()) { // return MatcherResult.success(res, partialRes.reader, consumedEvents); // } else { // consumedEvents.addAll(partialRes.consumedEvents); // return MatcherResult.failure(new BacktrackEventReader(consumedEvents, partialRes.reader), // toString() + " failed as it delegate matcher matched for " + (n + 1) + " times"); // } // } // // @Override // public String toString() { // return "(AtMost(" + n + ") " + delegate + ")"; // } // } // // Path: src/main/java/immanix/readers/ReplayEventReader.java // @SuppressWarnings("restriction") // public class ReplayEventReader implements EventReader { // // private Iterator<? extends XMLEvent> events; // // public ReplayEventReader(List<? extends XMLEvent> events) { // super(); // this.events = new ArrayList(events).iterator(); // } // // public boolean hasNext() { // return events.hasNext(); // } // // public XMLEvent next() throws XMLStreamException { // return events.next(); // } // // public EventReader unwrap() { // return this; // } // // @Override // public String toString() { // return "Replayer"; // } // } // // Path: src/test/java/immanix/utils/FullPacman.java // public class FullPacman extends StaxMatcher<Object> { // int count; // // public FullPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Collections.EMPTY_LIST); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/HungryPacman.java // public class HungryPacman extends StaxMatcher<Object> { // int count; // // public HungryPacman(int count) { // this.count = count; // } // // @Override // public MatcherResult<Object> match(EventReader reader) throws XMLStreamException { // if (count-- > 0) { // return MatcherResult.<Object>success("S", reader, Arrays.asList(reader.next())); // } else { // return MatcherResult.failure(reader, "Pacman is full"); // } // } // } // // Path: src/test/java/immanix/utils/XMLEventsUtils.java // public static XMLEvent c(String val) { // return eventFactory.createCharacters(val); // } // Path: src/test/java/immanix/AtMostMatcherTest.java import org.junit.Test; import immanix.matchers.AtMostMatcher; import immanix.readers.ReplayEventReader; import immanix.utils.FullPacman; import immanix.utils.HungryPacman; import javax.xml.stream.events.XMLEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static immanix.utils.XMLEventsUtils.c; AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 3); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("_1"), res.reader.next()); } @Test public void testReaderStateInCaseOfSuccess() throws Exception { StaxMatcher<Object> delegateMatcher = new HungryPacman(3); AtMostMatcher<Object> m = new AtMostMatcher<Object>(delegateMatcher, 4); AtMostMatcher<Object> sm = spy(m); List<XMLEvent> events = Arrays.<XMLEvent>asList(c("_1"), c("_2"), c("c"), c("d"), c("e"), c("f")); ReplayEventReader reader = new ReplayEventReader(events); MatcherResult<List<Object>> res = sm.match(reader); assertTrue(res.reader.hasNext()); assertEquals(c("d"), res.reader.next()); } @Test public void testSuccessWhenWantedNumberOfMatchingsIsReached() throws Exception {
StaxMatcher<Object> delegateMatcher = new FullPacman(4);
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/ChainedCustomBeanTransformer.java
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // }
import java.util.ArrayList; import java.util.List; import net.sf.beanlib.PropertyInfo;
for (CustomBeanTransformerSpi.Factory f : customBeanTransformerFactories) { this.customTransformerFactories.add(f); } } } public Factory appendCustomerBeanTransformerFactory(CustomBeanTransformerSpi.Factory customBeanTransformerFactory) { this.customTransformerFactories.add(customBeanTransformerFactory); return this; } @Override public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer) { ChainedCustomBeanTransformer chained = new ChainedCustomBeanTransformer(); for (CustomBeanTransformerSpi.Factory f : customTransformerFactories) { chained.appendCustomerBeanTransformer(f.newCustomBeanTransformer(contextBeanTransformer)); } return chained; } } private ChainedCustomBeanTransformer() {} private ChainedCustomBeanTransformer appendCustomerBeanTransformer(CustomBeanTransformerSpi c) { this.customTransformers.add(c); return this; } @Override
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // } // Path: core/src/main/java/net/sf/beanlib/spi/ChainedCustomBeanTransformer.java import java.util.ArrayList; import java.util.List; import net.sf.beanlib.PropertyInfo; for (CustomBeanTransformerSpi.Factory f : customBeanTransformerFactories) { this.customTransformerFactories.add(f); } } } public Factory appendCustomerBeanTransformerFactory(CustomBeanTransformerSpi.Factory customBeanTransformerFactory) { this.customTransformerFactories.add(customBeanTransformerFactory); return this; } @Override public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer) { ChainedCustomBeanTransformer chained = new ChainedCustomBeanTransformer(); for (CustomBeanTransformerSpi.Factory f : customTransformerFactories) { chained.appendCustomerBeanTransformer(f.newCustomBeanTransformer(contextBeanTransformer)); } return chained; } } private ChainedCustomBeanTransformer() {} private ChainedCustomBeanTransformer appendCustomerBeanTransformer(CustomBeanTransformerSpi c) { this.customTransformers.add(c); return this; } @Override
public boolean isTransformable(Object from, Class<?> toClass, PropertyInfo propertyInfo) {
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/DetailedPropertyFilter.java
// Path: core/src/main/java/net/sf/beanlib/provider/JavaBeanDetailedPropertyFilter.java // public class JavaBeanDetailedPropertyFilter implements DetailedPropertyFilter { // // @Override // public boolean propagate(String propertyName, Object fromBean, Method readerMethod, Object toBean, Method setterMethod) { // Class<?> returnType = readerMethod.getReturnType(); // Class<?> paramType = setterMethod.getParameterTypes()[0]; // return paramType.isAssignableFrom(returnType); // } // }
import java.lang.reflect.Method; import net.sf.beanlib.provider.JavaBeanDetailedPropertyFilter;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Used to control if a property should be propagated. * * @author Joe D. Velopar */ public interface DetailedPropertyFilter { public static final DetailedPropertyFilter ALWAYS_PROPAGATE = new DetailedPropertyFilter() { @Override public boolean propagate(String propertyName, Object fromBean, Method readerMethod, Object toBean, Method setterMethod) { return true; } };
// Path: core/src/main/java/net/sf/beanlib/provider/JavaBeanDetailedPropertyFilter.java // public class JavaBeanDetailedPropertyFilter implements DetailedPropertyFilter { // // @Override // public boolean propagate(String propertyName, Object fromBean, Method readerMethod, Object toBean, Method setterMethod) { // Class<?> returnType = readerMethod.getReturnType(); // Class<?> paramType = setterMethod.getParameterTypes()[0]; // return paramType.isAssignableFrom(returnType); // } // } // Path: core/src/main/java/net/sf/beanlib/spi/DetailedPropertyFilter.java import java.lang.reflect.Method; import net.sf.beanlib.provider.JavaBeanDetailedPropertyFilter; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Used to control if a property should be propagated. * * @author Joe D. Velopar */ public interface DetailedPropertyFilter { public static final DetailedPropertyFilter ALWAYS_PROPAGATE = new DetailedPropertyFilter() { @Override public boolean propagate(String propertyName, Object fromBean, Method readerMethod, Object toBean, Method setterMethod) { return true; } };
public static final DetailedPropertyFilter JAVABEAN_PROPAGATE = new JavaBeanDetailedPropertyFilter();
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/CustomBeanTransformerSpi.java
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // }
import net.sf.beanlib.PropertyInfo;
/* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Custom Bean Transformer SPI. * <p> * Used to provide custom transformation that takes precedence over the default transformation. * <h2>Quick Start</h2> For example, by default when BeanReplicator is replicating the content of a JavaBean, it would * try to instantiate the target class via the no-arg constructor. If the no-arg constructor is not defined (such as in * the Point class below), it would cause a NoSuchMethodException to be thrown: * * <pre> * <blockquote>public class Point { * private final int x, y; * * // missing no-arg constructor * public Point(int x, int y) { * this.x = x; * this.y = y; * } * public int getX() { return x; } * public int getY() { return y; } * } * * public class Bean { * private Point point; * public Point getPoint() { return point; } * public void setPoint(Point point) { this.point = point; } * } * * ... * // Initialize a bean * Bean from = new Bean(); * from.setPoint(new Point(1,2)); * * // Tries to replicate the bean using the default implementation * BeanReplicator replicator = new BeanReplicator(); * // Will cause NoSuchMethodException, as Point does not have a no-arg constructor * Bean to = replicator.replicateBean(from); * </blockquote> * </pre> * * One way to get around this problem is to define a custom transformer and the respective factory: * * <pre> * <blockquote>public class MyBeanTransformer implements CustomBeanTransformerSpi { * public boolean isTransformable(Object from, Class toClass, PropertyInfo propertyInfo) { * return toClass == Point.class; * } * * public <T> T transform(Object in, Class<T> toClass, PropertyInfo propertyInfo) { * Point from = (Point)in; * // Note the framework takes care of the issue of object identity, * // so we don't need to here. * return (T)new Point(from.getX(), from.getY()); * } * } * * public class MyBeanTransformerFactory implements CustomBeanTransformerSpi.Factory { * public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi beanTransformer) { * return new MyBeanTransformer(); * } * } * * ... * // Initialize a bean * Bean from = new Bean(); * from.setPoint(new Point(1,2)); * * // Partially overrides the default transformer behavior * BeanTransformerSpi transformer = new BeanTransformer(new MyBeanTransformerFactory()); * BeanReplicator replicator = new BeanReplicator(transformer); * * // Replicates the bean * Bean to = replicator.replicateBean(from); // now works! * </blockquote> * </pre> * * <h2>Customizing HibernateBeanReplicator</h2> Customizing the behavior of HibernateBeanReplicator is basically * identical to that of BeanReplicator as decribed above. For example, assuming the same MyBeanTransformerFactory * defined above is used, * * <pre> * <blockquote>// Partially overrides the default Hibernate bean transformer's behavior * HibernateBeanReplicator replicator = new Hibernate3BeanReplicator(); * replicator.initCustomTransformerFactory(new MyBeanTransformerFactory()); * replicator.copy(...); * </blockquote> * </pre> * * @see BeanTransformerSpi * @author Joe D. Velopar */ public interface CustomBeanTransformerSpi extends Transformable { /** * Custom Bean Transformer Factory SPI. * * @author Joe D. Velopar */ public static interface Factory { /** * Returns a custom transformer. * * @param contextBeanTransformer the context bean transformer currently used to provide the default * transformation behavior. */ CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer); } /** * Returns true if the given object is to be transformed by this transformer; false otherwise. * * @param from source object * @param propertyInfo If null, it means the in object is a root level object. Otherwise, propertyInfo contains * information about the input object as a java bean property value to be transformed. * @param toClass target class */
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // } // Path: core/src/main/java/net/sf/beanlib/spi/CustomBeanTransformerSpi.java import net.sf.beanlib.PropertyInfo; /* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Custom Bean Transformer SPI. * <p> * Used to provide custom transformation that takes precedence over the default transformation. * <h2>Quick Start</h2> For example, by default when BeanReplicator is replicating the content of a JavaBean, it would * try to instantiate the target class via the no-arg constructor. If the no-arg constructor is not defined (such as in * the Point class below), it would cause a NoSuchMethodException to be thrown: * * <pre> * <blockquote>public class Point { * private final int x, y; * * // missing no-arg constructor * public Point(int x, int y) { * this.x = x; * this.y = y; * } * public int getX() { return x; } * public int getY() { return y; } * } * * public class Bean { * private Point point; * public Point getPoint() { return point; } * public void setPoint(Point point) { this.point = point; } * } * * ... * // Initialize a bean * Bean from = new Bean(); * from.setPoint(new Point(1,2)); * * // Tries to replicate the bean using the default implementation * BeanReplicator replicator = new BeanReplicator(); * // Will cause NoSuchMethodException, as Point does not have a no-arg constructor * Bean to = replicator.replicateBean(from); * </blockquote> * </pre> * * One way to get around this problem is to define a custom transformer and the respective factory: * * <pre> * <blockquote>public class MyBeanTransformer implements CustomBeanTransformerSpi { * public boolean isTransformable(Object from, Class toClass, PropertyInfo propertyInfo) { * return toClass == Point.class; * } * * public <T> T transform(Object in, Class<T> toClass, PropertyInfo propertyInfo) { * Point from = (Point)in; * // Note the framework takes care of the issue of object identity, * // so we don't need to here. * return (T)new Point(from.getX(), from.getY()); * } * } * * public class MyBeanTransformerFactory implements CustomBeanTransformerSpi.Factory { * public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi beanTransformer) { * return new MyBeanTransformer(); * } * } * * ... * // Initialize a bean * Bean from = new Bean(); * from.setPoint(new Point(1,2)); * * // Partially overrides the default transformer behavior * BeanTransformerSpi transformer = new BeanTransformer(new MyBeanTransformerFactory()); * BeanReplicator replicator = new BeanReplicator(transformer); * * // Replicates the bean * Bean to = replicator.replicateBean(from); // now works! * </blockquote> * </pre> * * <h2>Customizing HibernateBeanReplicator</h2> Customizing the behavior of HibernateBeanReplicator is basically * identical to that of BeanReplicator as decribed above. For example, assuming the same MyBeanTransformerFactory * defined above is used, * * <pre> * <blockquote>// Partially overrides the default Hibernate bean transformer's behavior * HibernateBeanReplicator replicator = new Hibernate3BeanReplicator(); * replicator.initCustomTransformerFactory(new MyBeanTransformerFactory()); * replicator.copy(...); * </blockquote> * </pre> * * @see BeanTransformerSpi * @author Joe D. Velopar */ public interface CustomBeanTransformerSpi extends Transformable { /** * Custom Bean Transformer Factory SPI. * * @author Joe D. Velopar */ public static interface Factory { /** * Returns a custom transformer. * * @param contextBeanTransformer the context bean transformer currently used to provide the default * transformation behavior. */ CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer); } /** * Returns true if the given object is to be transformed by this transformer; false otherwise. * * @param from source object * @param propertyInfo If null, it means the in object is a root level object. Otherwise, propertyInfo contains * information about the input object as a java bean property value to be transformed. * @param toClass target class */
boolean isTransformable(Object from, Class<?> toClass, PropertyInfo propertyInfo);
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMap.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // }
import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestMap { private static final Logger LOGGER = LoggerFactory.getLogger(HibernateBeanReplicatorTestMap.class); @Test public void deepCopyMap() { FooWithMap fooMap = new FooWithMap(null); fooMap.addToMap("1", "a"); fooMap.addToMap("2", "b"); // Test recursive references fooMap.addToMap("3", fooMap); FooWithList fooList = new FooWithList(); fooList.addToList("1"); fooList.addToList("2"); fooList.setFooWithList(fooList); // Test recursive references fooList.addToList(fooList); fooList.addToList(fooList.getList()); fooMap.addToMap("4", fooList);
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // } // Path: hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMap.java import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestMap { private static final Logger LOGGER = LoggerFactory.getLogger(HibernateBeanReplicatorTestMap.class); @Test public void deepCopyMap() { FooWithMap fooMap = new FooWithMap(null); fooMap.addToMap("1", "a"); fooMap.addToMap("2", "b"); // Test recursive references fooMap.addToMap("3", fooMap); FooWithList fooList = new FooWithList(); fooList.addToList("1"); fooList.addToList("2"); fooList.setFooWithList(fooList); // Test recursive references fooList.addToList(fooList); fooList.addToList(fooList.getList()); fooMap.addToMap("4", fooList);
FooWithMap toMap = new Hibernate5BeanReplicator().deepCopy(fooMap);
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMap.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // }
import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
public void copyMap() { FooWithMap fooMap = new FooWithMap(null); fooMap.addToMap("1", "a"); fooMap.addToMap("2", "b"); { FooWithMap toFooWithMap = new Hibernate5BeanReplicator().copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); toMap.size(); // log.info("toMap.size()=" + toMap.size()); assertEquals(toMap.size(), 2); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator(); r.getHibernatePropertyFilter().withCollectionPropertyNameSet(null); FooWithMap toFooWithMap = r.copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); toMap.size(); // log.info("toMap.size()=" + toMap.size()); assertEquals(toMap.size(), 2); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator(); r.getHibernatePropertyFilter().withCollectionPropertyNameSet(Collections.EMPTY_SET); FooWithMap toFooWithMap = r.copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); assertNull(toMap); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator();
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // } // Path: hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMap.java import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public void copyMap() { FooWithMap fooMap = new FooWithMap(null); fooMap.addToMap("1", "a"); fooMap.addToMap("2", "b"); { FooWithMap toFooWithMap = new Hibernate5BeanReplicator().copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); toMap.size(); // log.info("toMap.size()=" + toMap.size()); assertEquals(toMap.size(), 2); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator(); r.getHibernatePropertyFilter().withCollectionPropertyNameSet(null); FooWithMap toFooWithMap = r.copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); toMap.size(); // log.info("toMap.size()=" + toMap.size()); assertEquals(toMap.size(), 2); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator(); r.getHibernatePropertyFilter().withCollectionPropertyNameSet(Collections.EMPTY_SET); FooWithMap toFooWithMap = r.copy(fooMap); Map<Object, Object> toMap = toFooWithMap.getMap(); assertNull(toMap); } { Hibernate5BeanReplicator r = new Hibernate5BeanReplicator();
r.getHibernatePropertyFilter().withVetoer(new PropertyFilter() {
emsouza/beanlib
hibernate/src/test/java/elh/maayan/test/TestRep.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter;
// f.addSupplier(oracle); // f.addSupplier(mac); f.setAddress("main street"); this.session.save(f); this.id = f.getId(); this.session.flush(); beginTransaction.commit(); // this.session.connection().commit(); this.session.close(); } @Test public void load() throws Exception { this.session = this.sessionFactory.openSession(); final Factory load = this.session.load(Factory.class, this.id); // (long) 350); System.out.println("factory " + load); final Collection<Supplier> suppliers = load.getSuppliers(); final Collection<Contract> contracts = load.getContracts(); assertEquals(1, load.getSuppliers().size()); for (final Contract contract : contracts) { final Supplier supplier = contract.getSupplier(); assertTrue(suppliers.contains(supplier)); supplier.setName("hello"); assertEquals(supplier.getName(), suppliers.iterator().next().getName()); }
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // } // Path: hibernate/src/test/java/elh/maayan/test/TestRep.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; // f.addSupplier(oracle); // f.addSupplier(mac); f.setAddress("main street"); this.session.save(f); this.id = f.getId(); this.session.flush(); beginTransaction.commit(); // this.session.connection().commit(); this.session.close(); } @Test public void load() throws Exception { this.session = this.sessionFactory.openSession(); final Factory load = this.session.load(Factory.class, this.id); // (long) 350); System.out.println("factory " + load); final Collection<Supplier> suppliers = load.getSuppliers(); final Collection<Contract> contracts = load.getContracts(); assertEquals(1, load.getSuppliers().size()); for (final Contract contract : contracts) { final Supplier supplier = contract.getSupplier(); assertTrue(suppliers.contains(supplier)); supplier.setName("hello"); assertEquals(supplier.getName(), suppliers.iterator().next().getName()); }
final Hibernate5BeanReplicator r = new Hibernate5BeanReplicator();
emsouza/beanlib
hibernate/src/test/java/elh/maayan/test/TestRep.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter;
// f.addSupplier(mac); f.setAddress("main street"); this.session.save(f); this.id = f.getId(); this.session.flush(); beginTransaction.commit(); // this.session.connection().commit(); this.session.close(); } @Test public void load() throws Exception { this.session = this.sessionFactory.openSession(); final Factory load = this.session.load(Factory.class, this.id); // (long) 350); System.out.println("factory " + load); final Collection<Supplier> suppliers = load.getSuppliers(); final Collection<Contract> contracts = load.getContracts(); assertEquals(1, load.getSuppliers().size()); for (final Contract contract : contracts) { final Supplier supplier = contract.getSupplier(); assertTrue(suppliers.contains(supplier)); supplier.setName("hello"); assertEquals(supplier.getName(), suppliers.iterator().next().getName()); } final Hibernate5BeanReplicator r = new Hibernate5BeanReplicator();
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // } // Path: hibernate/src/test/java/elh/maayan/test/TestRep.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import net.sf.beanlib.spi.PropertyFilter; // f.addSupplier(mac); f.setAddress("main street"); this.session.save(f); this.id = f.getId(); this.session.flush(); beginTransaction.commit(); // this.session.connection().commit(); this.session.close(); } @Test public void load() throws Exception { this.session = this.sessionFactory.openSession(); final Factory load = this.session.load(Factory.class, this.id); // (long) 350); System.out.println("factory " + load); final Collection<Supplier> suppliers = load.getSuppliers(); final Collection<Contract> contracts = load.getContracts(); assertEquals(1, load.getSuppliers().size()); for (final Contract contract : contracts) { final Supplier supplier = contract.getSupplier(); assertTrue(suppliers.contains(supplier)); supplier.setName("hello"); assertEquals(supplier.getName(), suppliers.iterator().next().getName()); } final Hibernate5BeanReplicator r = new Hibernate5BeanReplicator();
r.initPropertyFilter(new PropertyFilter() {
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestCollection.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestCollection { private static class A { Set<String> set; public Set<String> getSet() { return set; } public void setSet(Set<String> set) { this.set = set; } } @Test public void linkedHashSet() { A from = new A(); Set<String> set = new LinkedHashSet<>(); set.add("a"); set.add("c"); set.add("b"); from.setSet(set); { Iterator<String> itr = from.getSet().iterator(); assertEquals("a", itr.next()); assertEquals("c", itr.next()); assertEquals("b", itr.next()); }
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // Path: hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestCollection.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestCollection { private static class A { Set<String> set; public Set<String> getSet() { return set; } public void setSet(Set<String> set) { this.set = set; } } @Test public void linkedHashSet() { A from = new A(); Set<String> set = new LinkedHashSet<>(); set.add("a"); set.add("c"); set.add("b"); from.setSet(set); { Iterator<String> itr = from.getSet().iterator(); assertEquals("a", itr.next()); assertEquals("c", itr.next()); assertEquals("b", itr.next()); }
A to = new Hibernate5BeanReplicator().deepCopy(from);
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/provider/replicator/CalendarReplicatorTest.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // }
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.Calendar; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator;
} @Override public boolean equals(Object obj) { if (obj instanceof CalendarBean) { CalendarBean that = (CalendarBean) obj; return calendar == null ? that.getCalendar() == null : calendar.equals(that.getCalendar()); } return false; } } @Test public void testBeanReplicator() { CalendarBean from = new CalendarBean(); from.setCalendar(Calendar.getInstance()); from.setCalendar2(from.getCalendar()); CalendarBean to = new BeanReplicator().replicateBean(from); assertThat(from, not(sameInstance(to))); assertThat(from.getCalendar(), not(sameInstance(to.getCalendar()))); assertThat(from, is(to)); assertThat(from.getCalendar(), sameInstance(from.getCalendar2())); assertThat(to.getCalendar(), sameInstance(to.getCalendar2())); } @Test public void testHibernate3BeanReplicator() { CalendarBean from = new CalendarBean(); from.setCalendar(Calendar.getInstance());
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // Path: hibernate/src/test/java/net/sf/beanlib/provider/replicator/CalendarReplicatorTest.java import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.Calendar; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; } @Override public boolean equals(Object obj) { if (obj instanceof CalendarBean) { CalendarBean that = (CalendarBean) obj; return calendar == null ? that.getCalendar() == null : calendar.equals(that.getCalendar()); } return false; } } @Test public void testBeanReplicator() { CalendarBean from = new CalendarBean(); from.setCalendar(Calendar.getInstance()); from.setCalendar2(from.getCalendar()); CalendarBean to = new BeanReplicator().replicateBean(from); assertThat(from, not(sameInstance(to))); assertThat(from.getCalendar(), not(sameInstance(to.getCalendar()))); assertThat(from, is(to)); assertThat(from.getCalendar(), sameInstance(from.getCalendar2())); assertThat(to.getCalendar(), sameInstance(to.getCalendar2())); } @Test public void testHibernate3BeanReplicator() { CalendarBean from = new CalendarBean(); from.setCalendar(Calendar.getInstance());
CalendarBean to = new Hibernate5BeanReplicator().copy(from);
emsouza/beanlib
core/src/main/java/net/sf/beanlib/utils/BlobUtils.java
// Path: core/src/main/java/net/sf/beanlib/BeanlibException.java // public class BeanlibException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public BeanlibException() {} // // public BeanlibException(String message) { // super(message); // } // // public BeanlibException(String message, Throwable cause) { // super(message, cause); // } // // public BeanlibException(Throwable cause) { // super(cause); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.beanlib.BeanlibException;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.utils; /** * Blob Utilities. * * @author Joe D. Velopar */ public class BlobUtils { private static final Logger LOGGER = LoggerFactory.getLogger(BlobUtils.class); public byte[] toByteArray(Blob fromBlob) { return toByteArray(fromBlob, 4000); } public byte[] toByteArray(Blob fromBlob, int bufferSize) { if (fromBlob == null) { return ArrayUtils.EMPTY_BYTE_ARRAY; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { return toByteArrayImpl(fromBlob, baos, bufferSize); } catch (SQLException e) { LOGGER.error("", e);
// Path: core/src/main/java/net/sf/beanlib/BeanlibException.java // public class BeanlibException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public BeanlibException() {} // // public BeanlibException(String message) { // super(message); // } // // public BeanlibException(String message, Throwable cause) { // super(message, cause); // } // // public BeanlibException(Throwable cause) { // super(cause); // } // } // Path: core/src/main/java/net/sf/beanlib/utils/BlobUtils.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.beanlib.BeanlibException; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.utils; /** * Blob Utilities. * * @author Joe D. Velopar */ public class BlobUtils { private static final Logger LOGGER = LoggerFactory.getLogger(BlobUtils.class); public byte[] toByteArray(Blob fromBlob) { return toByteArray(fromBlob, 4000); } public byte[] toByteArray(Blob fromBlob, int bufferSize) { if (fromBlob == null) { return ArrayUtils.EMPTY_BYTE_ARRAY; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { return toByteArrayImpl(fromBlob, baos, bufferSize); } catch (SQLException e) { LOGGER.error("", e);
throw new BeanlibException(e);
emsouza/beanlib
core/src/test/java/net/sf/beanlib/provider/BeanPopulatorTest.java
// Path: core/src/main/java/net/sf/beanlib/provider/collector/ProtectedSetterMethodCollector.java // public class ProtectedSetterMethodCollector implements BeanMethodCollector { // // @Override // public Method[] collect(Object bean) { // Class<?> beanClass = bean.getClass(); // // Get all methods declared by the class or interface. // // This includes public, protected, default (package) access, // // and private methods, but excludes inherited methods. // Set<Method> set = new HashSet<Method>(); // // while (beanClass != Object.class) { // for (Method m : beanClass.getDeclaredMethods()) { // if (!m.getName().startsWith(getMethodPrefix())) { // continue; // } // if (m.getParameterTypes().length != 1) { // continue; // } // final int mod = m.getModifiers(); // // if (Modifier.isStatic(mod)) { // continue; // } // if (Modifier.isPrivate(mod)) { // continue; // } // // Adds the specified element to the set if it is not already present // set.add(m); // } // // climb to the super class and repeat // beanClass = beanClass.getSuperclass(); // } // return set.toArray(new Method[set.size()]); // } // // @Override // public String getMethodPrefix() { // return "set"; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.provider.collector.ProtectedSetterMethodCollector;
// Note this is different than if the default transformer is used. assertSame(from.getBar(), to.getBar()); } // Default transformer { Bar from = new Bar("from"); from.setBoo(true); from.setString("foo"); from.setBarString("barString"); from.setBar(from); Bar to = new Bar("to"); new BeanPopulator(from, to).populate(); assertFalse(from.getProtectedSetString().equals(to.getProtectedSetString())); assertEquals(from.getString(), to.getString()); assertEquals(from.isBoo(), to.isBoo()); assertEquals(from.getBarString(), to.getBarString()); // Note this is different than if no transformer is used. assertSame(to, to.getBar()); } } @Test public void testProtected() { // No transformer { Foo from = new Foo("from"); from.setBoo(true); from.setString("foo"); Foo to = new Foo("to"); assertFalse(from.equals(to));
// Path: core/src/main/java/net/sf/beanlib/provider/collector/ProtectedSetterMethodCollector.java // public class ProtectedSetterMethodCollector implements BeanMethodCollector { // // @Override // public Method[] collect(Object bean) { // Class<?> beanClass = bean.getClass(); // // Get all methods declared by the class or interface. // // This includes public, protected, default (package) access, // // and private methods, but excludes inherited methods. // Set<Method> set = new HashSet<Method>(); // // while (beanClass != Object.class) { // for (Method m : beanClass.getDeclaredMethods()) { // if (!m.getName().startsWith(getMethodPrefix())) { // continue; // } // if (m.getParameterTypes().length != 1) { // continue; // } // final int mod = m.getModifiers(); // // if (Modifier.isStatic(mod)) { // continue; // } // if (Modifier.isPrivate(mod)) { // continue; // } // // Adds the specified element to the set if it is not already present // set.add(m); // } // // climb to the super class and repeat // beanClass = beanClass.getSuperclass(); // } // return set.toArray(new Method[set.size()]); // } // // @Override // public String getMethodPrefix() { // return "set"; // } // } // Path: core/src/test/java/net/sf/beanlib/provider/BeanPopulatorTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.provider.collector.ProtectedSetterMethodCollector; // Note this is different than if the default transformer is used. assertSame(from.getBar(), to.getBar()); } // Default transformer { Bar from = new Bar("from"); from.setBoo(true); from.setString("foo"); from.setBarString("barString"); from.setBar(from); Bar to = new Bar("to"); new BeanPopulator(from, to).populate(); assertFalse(from.getProtectedSetString().equals(to.getProtectedSetString())); assertEquals(from.getString(), to.getString()); assertEquals(from.isBoo(), to.isBoo()); assertEquals(from.getBarString(), to.getBarString()); // Note this is different than if no transformer is used. assertSame(to, to.getBar()); } } @Test public void testProtected() { // No transformer { Foo from = new Foo("from"); from.setBoo(true); from.setString("foo"); Foo to = new Foo("to"); assertFalse(from.equals(to));
new BeanPopulator(from, to).initSetterMethodCollector(new ProtectedSetterMethodCollector()).initTransformer(null).populate();
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/BeanPopulatorBaseConfig.java
// Path: core/src/main/java/net/sf/beanlib/provider/collector/PublicSetterMethodCollector.java // public class PublicSetterMethodCollector implements BeanMethodCollector { // // @Override // public Method[] collect(Object bean) { // // Get all the public member methods of the class or interface, // // including those declared by the class or interface and // // those inherited from superclasses and superinterfaces. // Method[] ma = bean.getClass().getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method m : ma) { // if (m.getParameterTypes().length == 1) { // if (m.getName().startsWith(getMethodPrefix())) { // list.add(m); // } // } // } // return list.toArray(new Method[list.size()]); // } // // @Override // public String getMethodPrefix() { // return "set"; // } // } // // Path: core/src/main/java/net/sf/beanlib/provider/finder/PublicReaderMethodFinder.java // public class PublicReaderMethodFinder implements BeanMethodFinder { // // @Override // public Method find(final String propertyName, Object bean) { // String s = propertyName; // // if (Character.isLowerCase(propertyName.charAt(0))) { // s = propertyName.substring(0, 1).toUpperCase(); // // if (propertyName.length() > 1) { // s += propertyName.substring(1); // } // } // Class<?> beanClass = bean.getClass(); // try { // // Find the public member method of the class or interface, // // recursively on super classes and interfaces as necessary. // Method m = beanClass.getMethod("get" + s); // if (m.getParameterTypes().length == 0) { // return m; // } // } catch (NoSuchMethodException ignore) {} // try { // Method m = beanClass.getMethod("is" + s); // if (m.getParameterTypes().length == 0) { // return m; // } // } catch (NoSuchMethodException ignore) {} // return null; // } // }
import net.sf.beanlib.provider.collector.PublicSetterMethodCollector; import net.sf.beanlib.provider.finder.PublicReaderMethodFinder;
/* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Base configuration for a Bean Populator. * * @author Joe D. Velopar */ public class BeanPopulatorBaseConfig implements Cloneable { // BeanPopulatorBaseSpi configurations private BeanMethodCollector setterMethodCollector = new PublicSetterMethodCollector();
// Path: core/src/main/java/net/sf/beanlib/provider/collector/PublicSetterMethodCollector.java // public class PublicSetterMethodCollector implements BeanMethodCollector { // // @Override // public Method[] collect(Object bean) { // // Get all the public member methods of the class or interface, // // including those declared by the class or interface and // // those inherited from superclasses and superinterfaces. // Method[] ma = bean.getClass().getMethods(); // List<Method> list = new ArrayList<Method>(); // // for (Method m : ma) { // if (m.getParameterTypes().length == 1) { // if (m.getName().startsWith(getMethodPrefix())) { // list.add(m); // } // } // } // return list.toArray(new Method[list.size()]); // } // // @Override // public String getMethodPrefix() { // return "set"; // } // } // // Path: core/src/main/java/net/sf/beanlib/provider/finder/PublicReaderMethodFinder.java // public class PublicReaderMethodFinder implements BeanMethodFinder { // // @Override // public Method find(final String propertyName, Object bean) { // String s = propertyName; // // if (Character.isLowerCase(propertyName.charAt(0))) { // s = propertyName.substring(0, 1).toUpperCase(); // // if (propertyName.length() > 1) { // s += propertyName.substring(1); // } // } // Class<?> beanClass = bean.getClass(); // try { // // Find the public member method of the class or interface, // // recursively on super classes and interfaces as necessary. // Method m = beanClass.getMethod("get" + s); // if (m.getParameterTypes().length == 0) { // return m; // } // } catch (NoSuchMethodException ignore) {} // try { // Method m = beanClass.getMethod("is" + s); // if (m.getParameterTypes().length == 0) { // return m; // } // } catch (NoSuchMethodException ignore) {} // return null; // } // } // Path: core/src/main/java/net/sf/beanlib/spi/BeanPopulatorBaseConfig.java import net.sf.beanlib.provider.collector.PublicSetterMethodCollector; import net.sf.beanlib.provider.finder.PublicReaderMethodFinder; /* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Base configuration for a Bean Populator. * * @author Joe D. Velopar */ public class BeanPopulatorBaseConfig implements Cloneable { // BeanPopulatorBaseSpi configurations private BeanMethodCollector setterMethodCollector = new PublicSetterMethodCollector();
private BeanMethodFinder readerMethodFinder = new PublicReaderMethodFinder();
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestComparator.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // }
import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestComparator { private static Comparator<String> reverseComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s2.compareTo(s1); } }; @Test public void deepCopySet() { Set<String> fromSet = new TreeSet<>(); fromSet.add("1"); fromSet.add("2"); @SuppressWarnings("unchecked")
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // Path: hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestComparator.java import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ @RunWith(JUnit4.class) public class HibernateBeanReplicatorTestComparator { private static Comparator<String> reverseComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s2.compareTo(s1); } }; @Test public void deepCopySet() { Set<String> fromSet = new TreeSet<>(); fromSet.add("1"); fromSet.add("2"); @SuppressWarnings("unchecked")
Set<String> toSet = new Hibernate5BeanReplicator().deepCopy(fromSet, Set.class);
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/TrivialCustomBeanTransformerFactories.java
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // }
import net.sf.beanlib.PropertyInfo;
/* * Copyright 2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * @author Hanson Char */ public class TrivialCustomBeanTransformerFactories { /** Returns the factory of a custom transformer that is always not applicable. */ public static CustomBeanTransformerSpi.Factory getNoopCustomTransformerFactory() { return NoopCustomTransformer.FACTORY; } /** Returns a custom transformer that is always not applicable. */ public static CustomBeanTransformerSpi getNoopCustomTransformer() { return NoopCustomTransformer.SINGLETON; } /** * Returns the factory of a custom transformer that always performs identical transformation (ie returns the same * input instance). */ public static CustomBeanTransformerSpi.Factory getIdentityCustomTransformerFactory() { return IdentityCustomTransformer.FACTORY; } /** * Returns a custom transformer that always performs identical transformation (ie returns the same input instance). */ public static CustomBeanTransformerSpi getIdentityCustomTransformer() { return IdentityCustomTransformer.SINGLETON; } /** Returns the factory a custom transformer that always transforms to null. */ public static CustomBeanTransformerSpi.Factory getNullCustomTransformerFactory() { return NullCustomTransformer.FACTORY; } /** Returns a custom transformer that always transforms to null. */ public static CustomBeanTransformerSpi getNullCustomTransformer() { return NullCustomTransformer.SINGLETON; } /** Used to delay loading class until necessary. */ private static class NoopCustomTransformer { /** Factory of a transformer that performs no custom transformation. */ static final CustomBeanTransformerSpi.Factory FACTORY = new CustomBeanTransformerSpi.Factory() { @Override public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer) { return SINGLETON; } }; /** Performs no custom transformation. */ static final CustomBeanTransformerSpi SINGLETON = new CustomBeanTransformerSpi() { @Override
// Path: core/src/main/java/net/sf/beanlib/PropertyInfo.java // public class PropertyInfo { // // private final String propertyName; // // private final Object fromBean; // // private final Object toBean; // // public PropertyInfo(String propertyName, Object fromBean, Object toBean) { // this.propertyName = propertyName; // this.fromBean = fromBean; // this.toBean = toBean; // } // // /** Returns the property name. */ // public String getPropertyName() { // return propertyName; // } // // /** Returns the Java Bean from which the property is read. */ // public Object getFromBean() { // return fromBean; // } // // /** Returns the Java Bean to which the property is to be written. */ // public Object getToBean() { // return toBean; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); // } // } // Path: core/src/main/java/net/sf/beanlib/spi/TrivialCustomBeanTransformerFactories.java import net.sf.beanlib.PropertyInfo; /* * Copyright 2008 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * @author Hanson Char */ public class TrivialCustomBeanTransformerFactories { /** Returns the factory of a custom transformer that is always not applicable. */ public static CustomBeanTransformerSpi.Factory getNoopCustomTransformerFactory() { return NoopCustomTransformer.FACTORY; } /** Returns a custom transformer that is always not applicable. */ public static CustomBeanTransformerSpi getNoopCustomTransformer() { return NoopCustomTransformer.SINGLETON; } /** * Returns the factory of a custom transformer that always performs identical transformation (ie returns the same * input instance). */ public static CustomBeanTransformerSpi.Factory getIdentityCustomTransformerFactory() { return IdentityCustomTransformer.FACTORY; } /** * Returns a custom transformer that always performs identical transformation (ie returns the same input instance). */ public static CustomBeanTransformerSpi getIdentityCustomTransformer() { return IdentityCustomTransformer.SINGLETON; } /** Returns the factory a custom transformer that always transforms to null. */ public static CustomBeanTransformerSpi.Factory getNullCustomTransformerFactory() { return NullCustomTransformer.FACTORY; } /** Returns a custom transformer that always transforms to null. */ public static CustomBeanTransformerSpi getNullCustomTransformer() { return NullCustomTransformer.SINGLETON; } /** Used to delay loading class until necessary. */ private static class NoopCustomTransformer { /** Factory of a transformer that performs no custom transformation. */ static final CustomBeanTransformerSpi.Factory FACTORY = new CustomBeanTransformerSpi.Factory() { @Override public CustomBeanTransformerSpi newCustomBeanTransformer(BeanTransformerSpi contextBeanTransformer) { return SINGLETON; } }; /** Performs no custom transformation. */ static final CustomBeanTransformerSpi SINGLETON = new CustomBeanTransformerSpi() { @Override
public boolean isTransformable(Object from, Class<?> toClass, PropertyInfo propertyInfo) {
emsouza/beanlib
hibernate/src/main/java/net/sf/beanlib/hibernate/HibernatePropertyFilter.java
// Path: core/src/main/java/net/sf/beanlib/CollectionPropertyName.java // public class CollectionPropertyName<T> { // // public static final CollectionPropertyName<?>[] EMPTY_ARRAY = {}; // // private final Class<T> declaringClass; // // private final String collectionProperty; // // private final int hashCode; // // private final BeanGetter beanGetter = new BeanGetter(); // // /** Convenient factory method. */ // public static <T> CollectionPropertyName<T>[] createCollectionPropertyNames(Class<T> declaringClass, String[] collectionProperties) { // Set<CollectionPropertyName<T>> set = new HashSet<>(); // // for (String s : collectionProperties) { // set.add(new CollectionPropertyName<>(declaringClass, s)); // } // // @SuppressWarnings("unchecked") // CollectionPropertyName<T>[] ret = (CollectionPropertyName<T>[]) set.toArray(EMPTY_ARRAY); // return ret; // } // // /** // * @param declaringClass declaring class of the Collection or Map property. // * @param collectionProperty Collection or Map property name. // */ // public CollectionPropertyName(Class<T> declaringClass, String collectionProperty) { // this.declaringClass = declaringClass; // this.collectionProperty = collectionProperty; // this.hashCode = beanGetter.getBeanHashCode(this); // } // // public Class<T> getDeclaringClass() { // return declaringClass; // } // // public String getCollectionProperty() { // return collectionProperty; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof CollectionPropertyName)) { // return false; // } // CollectionPropertyName<?> that = (CollectionPropertyName<?>) obj; // return new EqualsBuilder().append(this.declaringClass, that.declaringClass).append(this.collectionProperty, that.collectionProperty) // .isEquals(); // } // // @Override // public int hashCode() { // return this.hashCode; // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // }
import static net.sf.beanlib.utils.ClassUtils.fqcn; import static net.sf.beanlib.utils.ClassUtils.immutable; import static net.sf.beanlib.utils.ClassUtils.isJavaPackage; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import net.sf.beanlib.CollectionPropertyName; import net.sf.beanlib.spi.PropertyFilter;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate; /** * A default implementation used to determine if a Hibernate property that follows the JavaBean getter/setter convention * should be propagated. Each propagation decision can be controlled by specifying * <ul> * <li>An application package prefix used to determine if a property with a type of an entity bean class will be * included for replication;</li> * <li>The set of entity bean classes for matching properties that will be replicated;</li> * <li>The set of collection and map properties that will be replicated;</li> * <li>A {@link net.sf.beanlib.spi.PropertyFilter vetoer} used to veto the propagation of a property</li> * </ul> * * @author Joe D. Velopar */ public class HibernatePropertyFilter implements PropertyFilter { /** * The set of entity bean classes for matching properties that will be replicated, eagerly fetching if necessary. * Null means all whereas empty means none. */ private Set<Class<?>> entityBeanClassSet; /** * The set of collection and map properties that will be replicated, eagerly fetching if necessary. Null means all * whereas empty means none. */
// Path: core/src/main/java/net/sf/beanlib/CollectionPropertyName.java // public class CollectionPropertyName<T> { // // public static final CollectionPropertyName<?>[] EMPTY_ARRAY = {}; // // private final Class<T> declaringClass; // // private final String collectionProperty; // // private final int hashCode; // // private final BeanGetter beanGetter = new BeanGetter(); // // /** Convenient factory method. */ // public static <T> CollectionPropertyName<T>[] createCollectionPropertyNames(Class<T> declaringClass, String[] collectionProperties) { // Set<CollectionPropertyName<T>> set = new HashSet<>(); // // for (String s : collectionProperties) { // set.add(new CollectionPropertyName<>(declaringClass, s)); // } // // @SuppressWarnings("unchecked") // CollectionPropertyName<T>[] ret = (CollectionPropertyName<T>[]) set.toArray(EMPTY_ARRAY); // return ret; // } // // /** // * @param declaringClass declaring class of the Collection or Map property. // * @param collectionProperty Collection or Map property name. // */ // public CollectionPropertyName(Class<T> declaringClass, String collectionProperty) { // this.declaringClass = declaringClass; // this.collectionProperty = collectionProperty; // this.hashCode = beanGetter.getBeanHashCode(this); // } // // public Class<T> getDeclaringClass() { // return declaringClass; // } // // public String getCollectionProperty() { // return collectionProperty; // } // // @Override // public boolean equals(Object obj) { // if (!(obj instanceof CollectionPropertyName)) { // return false; // } // CollectionPropertyName<?> that = (CollectionPropertyName<?>) obj; // return new EqualsBuilder().append(this.declaringClass, that.declaringClass).append(this.collectionProperty, that.collectionProperty) // .isEquals(); // } // // @Override // public int hashCode() { // return this.hashCode; // } // } // // Path: core/src/main/java/net/sf/beanlib/spi/PropertyFilter.java // public interface PropertyFilter { // // /** // * Returns true if the given JavaBean property should be propagated; false otherwise. // * // * @param propertyName JavaBean property name. // * @param readerMethod reader method of the JavaBean property name. // * @return true if the given JavaBean property should be propagated. // */ // boolean propagate(String propertyName, Method readerMethod); // } // Path: hibernate/src/main/java/net/sf/beanlib/hibernate/HibernatePropertyFilter.java import static net.sf.beanlib.utils.ClassUtils.fqcn; import static net.sf.beanlib.utils.ClassUtils.immutable; import static net.sf.beanlib.utils.ClassUtils.isJavaPackage; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import net.sf.beanlib.CollectionPropertyName; import net.sf.beanlib.spi.PropertyFilter; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate; /** * A default implementation used to determine if a Hibernate property that follows the JavaBean getter/setter convention * should be propagated. Each propagation decision can be controlled by specifying * <ul> * <li>An application package prefix used to determine if a property with a type of an entity bean class will be * included for replication;</li> * <li>The set of entity bean classes for matching properties that will be replicated;</li> * <li>The set of collection and map properties that will be replicated;</li> * <li>A {@link net.sf.beanlib.spi.PropertyFilter vetoer} used to veto the propagation of a property</li> * </ul> * * @author Joe D. Velopar */ public class HibernatePropertyFilter implements PropertyFilter { /** * The set of entity bean classes for matching properties that will be replicated, eagerly fetching if necessary. * Null means all whereas empty means none. */ private Set<Class<?>> entityBeanClassSet; /** * The set of collection and map properties that will be replicated, eagerly fetching if necessary. Null means all * whereas empty means none. */
private Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet;
emsouza/beanlib
core/src/main/java/net/sf/beanlib/spi/BeanPopulationExceptionHandlerAdapter.java
// Path: core/src/main/java/net/sf/beanlib/BeanlibException.java // public class BeanlibException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public BeanlibException() {} // // public BeanlibException(String message) { // super(message); // } // // public BeanlibException(String message, Throwable cause) { // super(message, cause); // } // // public BeanlibException(Throwable cause) { // super(cause); // } // }
import java.lang.reflect.Method; import org.slf4j.Logger; import net.sf.beanlib.BeanlibException;
/* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Adapter class for {@link BeanPopulationExceptionHandler}. * * @author Joe D. Velopar */ public class BeanPopulationExceptionHandlerAdapter implements BeanPopulationExceptionHandler { protected String propertyName; protected Object fromBean; protected Method readerMethod; protected Object toBean; protected Method setterMethod; @Override public void handleException(Throwable t, Logger log) { log.error("\n" + "propertyName=" + propertyName + "\n" + "readerMethod=" + readerMethod + "\n" + "setterMethod=" + setterMethod + "\n" + "fromBean=" + fromBean + "\n" + "toBean=" + toBean + "\n", t); if (t instanceof RuntimeException) { throw (RuntimeException) t; } if (t instanceof Error) { throw (Error) t; }
// Path: core/src/main/java/net/sf/beanlib/BeanlibException.java // public class BeanlibException extends RuntimeException { // // private static final long serialVersionUID = 1; // // public BeanlibException() {} // // public BeanlibException(String message) { // super(message); // } // // public BeanlibException(String message, Throwable cause) { // super(message, cause); // } // // public BeanlibException(Throwable cause) { // super(cause); // } // } // Path: core/src/main/java/net/sf/beanlib/spi/BeanPopulationExceptionHandlerAdapter.java import java.lang.reflect.Method; import org.slf4j.Logger; import net.sf.beanlib.BeanlibException; /* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.spi; /** * Adapter class for {@link BeanPopulationExceptionHandler}. * * @author Joe D. Velopar */ public class BeanPopulationExceptionHandlerAdapter implements BeanPopulationExceptionHandler { protected String propertyName; protected Object fromBean; protected Method readerMethod; protected Object toBean; protected Method setterMethod; @Override public void handleException(Throwable t, Logger log) { log.error("\n" + "propertyName=" + propertyName + "\n" + "readerMethod=" + readerMethod + "\n" + "setterMethod=" + setterMethod + "\n" + "fromBean=" + fromBean + "\n" + "toBean=" + toBean + "\n", t); if (t instanceof RuntimeException) { throw (RuntimeException) t; } if (t instanceof Error) { throw (Error) t; }
throw new BeanlibException(t);
emsouza/beanlib
hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMySet.java
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator;
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ public class HibernateBeanReplicatorTestMySet { @Test public void testDeepCopyMap() { FooWithMySet fooWithMySet = new FooWithMySet(); fooWithMySet.addToMySet("a"); fooWithMySet.addToMySet("b"); // Test recursive references fooWithMySet.addToMySet(fooWithMySet); FooWithList fooList = new FooWithList(); fooList.addToList("1"); fooList.addToList("2"); fooList.setFooWithList(fooList); // Test recursive references fooList.addToList(fooList); fooList.addToList(fooList.getList()); fooWithMySet.addToMySet(fooList);
// Path: hibernate/src/main/java/net/sf/beanlib/hibernate5/Hibernate5BeanReplicator.java // public class Hibernate5BeanReplicator extends HibernateBeanReplicator { // // /** // * By default, all properties will be included for replication. // */ // public Hibernate5BeanReplicator() { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter())); // } // // /** // * Constructs with an application package prefix. // * // * @param applicationPackagePrefix An application package prefix used to determine if a property with a type of an // * entity bean class will be included for replication. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(Set<Class<?>> entityBeanClassSet, Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, // PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter().withEntityBeanClassSet(entityBeanClassSet) // .withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // // /** // * Convenient constructor to specify: // * <ol> // * <li>An application package prefix used to determine if a property with a type of an entity bean class will be // * included for replication;</li> // * <li>The set of entity bean classes for matching properties that will be replicated;</li> // * <li>The set of collection and map properties that will be replicated;</li> // * <li>A {@link PropertyFilter vetoer} used to veto the propagation of specific properties</li> // * </ol> // * <p> // * Note this constructor is relevant only if the default property filter {@link HibernatePropertyFilter} is used. // * // * @param entityBeanClassSet The set of entity bean classes for matching properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param collectionPropertyNameSet The set of collection and map properties that will be replicated, eagerly // * fetching if necessary. Null means all whereas empty means none. // * @param vetoer used to veto the propagation of specific properties. // */ // public Hibernate5BeanReplicator(String applicationPackagePrefix, Set<Class<?>> entityBeanClassSet, // Set<? extends CollectionPropertyName<?>> collectionPropertyNameSet, PropertyFilter vetoer) { // super(new Hibernate5BeanTransformer().initPropertyFilter(new HibernatePropertyFilter(applicationPackagePrefix) // .withEntityBeanClassSet(entityBeanClassSet).withCollectionPropertyNameSet(collectionPropertyNameSet).withVetoer(vetoer))); // } // } // Path: hibernate/src/test/java/net/sf/beanlib/hibernate5/HibernateBeanReplicatorTestMySet.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import junit.framework.JUnit4TestAdapter; import net.sf.beanlib.hibernate5.Hibernate5BeanReplicator; /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.hibernate5; /** * @author Joe D. Velopar */ public class HibernateBeanReplicatorTestMySet { @Test public void testDeepCopyMap() { FooWithMySet fooWithMySet = new FooWithMySet(); fooWithMySet.addToMySet("a"); fooWithMySet.addToMySet("b"); // Test recursive references fooWithMySet.addToMySet(fooWithMySet); FooWithList fooList = new FooWithList(); fooList.addToList("1"); fooList.addToList("2"); fooList.setFooWithList(fooList); // Test recursive references fooList.addToList(fooList); fooList.addToList(fooList.getList()); fooWithMySet.addToMySet(fooList);
FooWithMySet toSet = new Hibernate5BeanReplicator().deepCopy(fooWithMySet);
emsouza/beanlib
core/src/main/java/net/sf/beanlib/provider/collector/OrderedMethodCollector.java
// Path: core/src/main/java/net/sf/beanlib/spi/BeanMethodCollector.java // public interface BeanMethodCollector { // // Method[] collect(Object bean); // // String getMethodPrefix(); // } // // Path: core/src/main/java/net/sf/beanlib/utils/ClassUtils.java // public enum ClassUtils { // ; // /** copied from the private static Class.ENUM constant. */ // private static final int ENUM = 0x00004000; // // /** Returns the unqalified class name. */ // public static String unqualify(Class<?> c) { // if (c == null) { // return null; // } // String fqcn = c.getName(); // int idx = fqcn.lastIndexOf('.'); // return idx == -1 ? fqcn : fqcn.substring(idx + 1); // } // // /** // * Returns true if the given class is known to be immutable; false otherwise. // */ // public static boolean immutable(Class<?> c) { // if (c == null) { // return false; // } // return c == String.class || c.isPrimitive() || (c.getModifiers() & ENUM) != 0 || Number.class.isAssignableFrom(c) && isJavaPackage(c) // || Boolean.class == c || Character.class == c || Byte.class == c || Currency.class == c; // } // // /** // * Returns true if the given class is under a package that starts with "java.". // */ // public static boolean isJavaPackage(Class<?> c) { // return c != null && fqcn(c).startsWith("java."); // } // // /** // * Returns true if the given class is under a package that starts with "org.hibernate.". // */ // public static boolean isHibernatePackage(Class<?> c) { // return c != null && fqcn(c).startsWith("org.hibernate."); // } // // /** // * Returns the fully qualified class name of the given class but without any array prefix such as "[L"; or null if // * the given class is null; or an empty string if the given class is a primitive array which may be single or // * multiple dimensional. // */ // public static String fqcn(Class<?> c) { // if (c == null) { // return null; // } // String cn = c.getName(); // // if (c.isArray()) { // int idx = cn.lastIndexOf("["); // return idx + 2 < cn.length() ? cn.substring(idx + 2) : ""; // } // return cn; // } // }
import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import net.sf.beanlib.spi.BeanMethodCollector; import net.sf.beanlib.utils.ClassUtils;
/* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.provider.collector; /** * Supports collecting JavaBean public setter methods. This class differs from the * {@link net.sf.beanlib.provider.collector.PublicSetterMethodCollector PublicSetterMethodCollector} in that * <ul> * <li>Immutable and {@link java.util.Date Date} property setter methods are placed before the other setter methods in * the returned {@link java.lang.reflect.Method Method} array; and</li> * <li>{@link java.util.Collection Collection} and {@link java.util.Map Map} setter methods are guaranteed to be placed * after the other setter methods in the returned {@link java.lang.reflect.Method Method} array.</li> * </ul> * * @author Joe D. Velopar */ public class OrderedMethodCollector implements BeanMethodCollector { private final BeanMethodCollector beanMethodCollector; public OrderedMethodCollector() { beanMethodCollector = new PublicSetterMethodCollector(); } public OrderedMethodCollector(BeanMethodCollector beanMethodCollector) { this.beanMethodCollector = beanMethodCollector; } @Override public Method[] collect(Object bean) { Method[] ma = beanMethodCollector.collect(bean); List<Method> leaveMethods = new ArrayList<Method>(); List<Method> colMethods = new ArrayList<Method>(); for (Method m : ma) { Class<?> paramType = m.getParameterTypes()[0];
// Path: core/src/main/java/net/sf/beanlib/spi/BeanMethodCollector.java // public interface BeanMethodCollector { // // Method[] collect(Object bean); // // String getMethodPrefix(); // } // // Path: core/src/main/java/net/sf/beanlib/utils/ClassUtils.java // public enum ClassUtils { // ; // /** copied from the private static Class.ENUM constant. */ // private static final int ENUM = 0x00004000; // // /** Returns the unqalified class name. */ // public static String unqualify(Class<?> c) { // if (c == null) { // return null; // } // String fqcn = c.getName(); // int idx = fqcn.lastIndexOf('.'); // return idx == -1 ? fqcn : fqcn.substring(idx + 1); // } // // /** // * Returns true if the given class is known to be immutable; false otherwise. // */ // public static boolean immutable(Class<?> c) { // if (c == null) { // return false; // } // return c == String.class || c.isPrimitive() || (c.getModifiers() & ENUM) != 0 || Number.class.isAssignableFrom(c) && isJavaPackage(c) // || Boolean.class == c || Character.class == c || Byte.class == c || Currency.class == c; // } // // /** // * Returns true if the given class is under a package that starts with "java.". // */ // public static boolean isJavaPackage(Class<?> c) { // return c != null && fqcn(c).startsWith("java."); // } // // /** // * Returns true if the given class is under a package that starts with "org.hibernate.". // */ // public static boolean isHibernatePackage(Class<?> c) { // return c != null && fqcn(c).startsWith("org.hibernate."); // } // // /** // * Returns the fully qualified class name of the given class but without any array prefix such as "[L"; or null if // * the given class is null; or an empty string if the given class is a primitive array which may be single or // * multiple dimensional. // */ // public static String fqcn(Class<?> c) { // if (c == null) { // return null; // } // String cn = c.getName(); // // if (c.isArray()) { // int idx = cn.lastIndexOf("["); // return idx + 2 < cn.length() ? cn.substring(idx + 2) : ""; // } // return cn; // } // } // Path: core/src/main/java/net/sf/beanlib/provider/collector/OrderedMethodCollector.java import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import net.sf.beanlib.spi.BeanMethodCollector; import net.sf.beanlib.utils.ClassUtils; /* * Copyright 2007 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.beanlib.provider.collector; /** * Supports collecting JavaBean public setter methods. This class differs from the * {@link net.sf.beanlib.provider.collector.PublicSetterMethodCollector PublicSetterMethodCollector} in that * <ul> * <li>Immutable and {@link java.util.Date Date} property setter methods are placed before the other setter methods in * the returned {@link java.lang.reflect.Method Method} array; and</li> * <li>{@link java.util.Collection Collection} and {@link java.util.Map Map} setter methods are guaranteed to be placed * after the other setter methods in the returned {@link java.lang.reflect.Method Method} array.</li> * </ul> * * @author Joe D. Velopar */ public class OrderedMethodCollector implements BeanMethodCollector { private final BeanMethodCollector beanMethodCollector; public OrderedMethodCollector() { beanMethodCollector = new PublicSetterMethodCollector(); } public OrderedMethodCollector(BeanMethodCollector beanMethodCollector) { this.beanMethodCollector = beanMethodCollector; } @Override public Method[] collect(Object bean) { Method[] ma = beanMethodCollector.collect(bean); List<Method> leaveMethods = new ArrayList<Method>(); List<Method> colMethods = new ArrayList<Method>(); for (Method m : ma) { Class<?> paramType = m.getParameterTypes()[0];
if (ClassUtils.immutable(paramType) || Date.class.isAssignableFrom(paramType)) {
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // }
import static com.google.common.flogger.LazyArgs.lazy; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gerrit.entities.Project; import com.google.gerrit.entities.RefNames; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.metrics.Timer1; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.PerThreadRequestScope; import com.google.gerrit.server.git.ProjectRunnable; import com.google.gerrit.server.git.WorkQueue.CanceledWhileRunning; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackend.RefFilterOptions; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.ProjectPermission; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.eclipse.jgit.errors.NoRemoteRepositoryException; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.errors.RemoteRepositoryException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.errors.TransportException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchConnection; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish;
@Assisted URIish u) { gitManager = grm; this.permissionBackend = permissionBackend; pool = p; config = c; replConfig = rc; credentialsProvider = cpFactory.create(c.getName()); threadScoper = ts; projectName = d; uri = u; updateRefRetryCount = 0; maxUpdateRefRetries = pool.getUpdateRefErrorMaxRetries(); id = ig.next(); stateLog = sl; createdAt = System.nanoTime(); metrics = m; projectCache = pc; createProjectFactory = cpf; canceledWhileRunning = new AtomicBoolean(false); maxRetries = p.getMaxRetries(); transportFactory = tf; } @Inject(optional = true) public void setReplicationPushFilter(DynamicItem<ReplicationPushFilter> replicationPushFilter) { this.replicationPushFilter = replicationPushFilter; } @Override public void cancel() {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java import static com.google.common.flogger.LazyArgs.lazy; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gerrit.entities.Project; import com.google.gerrit.entities.RefNames; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.metrics.Timer1; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.PerThreadRequestScope; import com.google.gerrit.server.git.ProjectRunnable; import com.google.gerrit.server.git.WorkQueue.CanceledWhileRunning; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackend.RefFilterOptions; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.ProjectPermission; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.eclipse.jgit.errors.NoRemoteRepositoryException; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.errors.RemoteRepositoryException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.errors.TransportException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchConnection; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish; @Assisted URIish u) { gitManager = grm; this.permissionBackend = permissionBackend; pool = p; config = c; replConfig = rc; credentialsProvider = cpFactory.create(c.getName()); threadScoper = ts; projectName = d; uri = u; updateRefRetryCount = 0; maxUpdateRefRetries = pool.getUpdateRefErrorMaxRetries(); id = ig.next(); stateLog = sl; createdAt = System.nanoTime(); metrics = m; projectCache = pc; createProjectFactory = cpf; canceledWhileRunning = new AtomicBoolean(false); maxRetries = p.getMaxRetries(); transportFactory = tf; } @Inject(optional = true) public void setReplicationPushFilter(DynamicItem<ReplicationPushFilter> replicationPushFilter) { this.replicationPushFilter = replicationPushFilter; } @Override public void cancel() {
repLog.atInfo().log("Replication [%s] to %s was canceled", HexFormat.fromInt(id), getURI());
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // }
import static com.google.common.flogger.LazyArgs.lazy; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gerrit.entities.Project; import com.google.gerrit.entities.RefNames; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.metrics.Timer1; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.PerThreadRequestScope; import com.google.gerrit.server.git.ProjectRunnable; import com.google.gerrit.server.git.WorkQueue.CanceledWhileRunning; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackend.RefFilterOptions; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.ProjectPermission; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.eclipse.jgit.errors.NoRemoteRepositoryException; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.errors.RemoteRepositoryException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.errors.TransportException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchConnection; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish;
public Set<String> getRefs() { return pushAllRefs ? Sets.newHashSet(ALL_REFS) : delta; } void addRefs(Set<String> refs) { if (!pushAllRefs) { for (String ref : refs) { addRef(ref); } } } Set<String> setStartedRefs(Set<String> startedRefs) { Set<String> notAttemptedRefs = Sets.difference(delta, startedRefs); pushAllRefs = false; delta.clear(); addRefs(startedRefs); return notAttemptedRefs; } void notifyNotAttempted(Set<String> notAttemptedRefs) { notAttemptedRefs.forEach( ref -> Arrays.asList(getStatesByRef(ref)) .forEach( state -> state.notifyRefReplicated( projectName.get(), ref, uri,
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushOne.java import static com.google.common.flogger.LazyArgs.lazy; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import com.google.common.base.MoreObjects; import com.google.common.base.Throwables; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gerrit.entities.Project; import com.google.gerrit.entities.RefNames; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.metrics.Timer1; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.PerThreadRequestScope; import com.google.gerrit.server.git.ProjectRunnable; import com.google.gerrit.server.git.WorkQueue.CanceledWhileRunning; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackend.RefFilterOptions; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.ProjectPermission; import com.google.gerrit.server.project.ProjectCache; import com.google.gerrit.server.project.ProjectState; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.eclipse.jgit.errors.NoRemoteRepositoryException; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.errors.RemoteRepositoryException; import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.errors.TransportException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.NullProgressMonitor; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchConnection; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish; public Set<String> getRefs() { return pushAllRefs ? Sets.newHashSet(ALL_REFS) : delta; } void addRefs(Set<String> refs) { if (!pushAllRefs) { for (String ref : refs) { addRef(ref); } } } Set<String> setStartedRefs(Set<String> startedRefs) { Set<String> notAttemptedRefs = Sets.difference(delta, startedRefs); pushAllRefs = false; delta.clear(); addRefs(startedRefs); return notAttemptedRefs; } void notifyNotAttempted(Set<String> notAttemptedRefs) { notAttemptedRefs.forEach( ref -> Arrays.asList(getStatesByRef(ref)) .forEach( state -> state.notifyRefReplicated( projectName.get(), ref, uri,
RefPushResult.NOT_ATTEMPTED,
GerritCodeReview/plugins_replication
src/test/java/com/googlesource/gerrit/plugins/replication/GitUpdateProcessingTest.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // public static class GitUpdateProcessing implements PushResultProcessing { // private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // // private final EventDispatcher dispatcher; // // public GitUpdateProcessing(EventDispatcher dispatcher) { // this.dispatcher = dispatcher; // } // // @Override // public void onRefReplicatedToOneNode( // String project, // String ref, // URIish uri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // postEvent(new RefReplicatedEvent(project, ref, uri, status, refStatus)); // } // // @Override // public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) { // postEvent(new RefReplicationDoneEvent(project, ref, nodesCount)); // } // // private void postEvent(RefEvent event) { // try { // dispatcher.postEvent(event); // } catch (StorageException | PermissionBackendException e) { // logger.atSevere().withCause(e).log("Cannot post event"); // } // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // }
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.GitUpdateProcessing; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test;
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class GitUpdateProcessingTest { private EventDispatcher dispatcherMock;
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // public static class GitUpdateProcessing implements PushResultProcessing { // private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // // private final EventDispatcher dispatcher; // // public GitUpdateProcessing(EventDispatcher dispatcher) { // this.dispatcher = dispatcher; // } // // @Override // public void onRefReplicatedToOneNode( // String project, // String ref, // URIish uri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // postEvent(new RefReplicatedEvent(project, ref, uri, status, refStatus)); // } // // @Override // public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) { // postEvent(new RefReplicationDoneEvent(project, ref, nodesCount)); // } // // private void postEvent(RefEvent event) { // try { // dispatcher.postEvent(event); // } catch (StorageException | PermissionBackendException e) { // logger.atSevere().withCause(e).log("Cannot post event"); // } // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // Path: src/test/java/com/googlesource/gerrit/plugins/replication/GitUpdateProcessingTest.java import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.GitUpdateProcessing; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test; // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class GitUpdateProcessingTest { private EventDispatcher dispatcherMock;
private GitUpdateProcessing gitUpdateProcessing;
GerritCodeReview/plugins_replication
src/test/java/com/googlesource/gerrit/plugins/replication/events/EventFieldsTest.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // }
import static org.junit.Assert.assertEquals; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Test;
// Copyright (C) 2021 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication.events; public class EventFieldsTest { @SuppressWarnings("deprecation") @Test public void refReplicatedEventFields() throws URISyntaxException { URIish completeUri = new URIish("git://someHost:9417/basePath/someProject.git"); RefReplicatedEvent event = new RefReplicatedEvent( "someProject", "refs/heads/master", completeUri,
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // Path: src/test/java/com/googlesource/gerrit/plugins/replication/events/EventFieldsTest.java import static org.junit.Assert.assertEquals; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Test; // Copyright (C) 2021 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication.events; public class EventFieldsTest { @SuppressWarnings("deprecation") @Test public void refReplicatedEventFields() throws URISyntaxException { URIish completeUri = new URIish("git://someHost:9417/basePath/someProject.git"); RefReplicatedEvent event = new RefReplicatedEvent( "someProject", "refs/heads/master", completeUri,
RefPushResult.SUCCEEDED,
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // }
import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish;
private final Provider<ReplicationQueue> replicationQueue; private volatile List<Destination> destinations; private boolean shuttingDown; public static class EventQueueNotEmptyException extends Exception { private static final long serialVersionUID = 1L; public EventQueueNotEmptyException(String errorMessage) { super(errorMessage); } } @Inject public DestinationsCollection( Destination.Factory destinationFactory, Provider<ReplicationQueue> replicationQueue, ReplicationConfig replicationConfig, ConfigParser configParser, EventBus eventBus) throws ConfigInvalidException { this.destinationFactory = destinationFactory; this.replicationQueue = replicationQueue; this.destinations = allDestinations( destinationFactory, configParser.parseRemotes(replicationConfig.getConfig())); eventBus.register(this); } @Override public Multimap<Destination, URIish> getURIs(
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish; private final Provider<ReplicationQueue> replicationQueue; private volatile List<Destination> destinations; private boolean shuttingDown; public static class EventQueueNotEmptyException extends Exception { private static final long serialVersionUID = 1L; public EventQueueNotEmptyException(String errorMessage) { super(errorMessage); } } @Inject public DestinationsCollection( Destination.Factory destinationFactory, Provider<ReplicationQueue> replicationQueue, ReplicationConfig replicationConfig, ConfigParser configParser, EventBus eventBus) throws ConfigInvalidException { this.destinationFactory = destinationFactory; this.replicationQueue = replicationQueue; this.destinations = allDestinations( destinationFactory, configParser.parseRemotes(replicationConfig.getConfig())); eventBus.register(this); } @Override public Multimap<Destination, URIish> getURIs(
Optional<String> remoteName, Project.NameKey projectName, FilterType filterType) {
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // }
import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish;
} @Override public Multimap<Destination, URIish> getURIs( Optional<String> remoteName, Project.NameKey projectName, FilterType filterType) { if (getAll(filterType).isEmpty()) { return ImmutableMultimap.of(); } SetMultimap<Destination, URIish> uris = HashMultimap.create(); for (Destination config : getAll(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName.isPresent() && !config.getRemoteConfigName().equals(remoteName.get())) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish; } @Override public Multimap<Destination, URIish> getURIs( Optional<String> remoteName, Project.NameKey projectName, FilterType filterType) { if (getAll(filterType).isEmpty()) { return ImmutableMultimap.of(); } SetMultimap<Destination, URIish> uris = HashMultimap.create(); for (Destination config : getAll(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName.isPresent() && !config.getRemoteConfigName().equals(remoteName.get())) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) {
repLog.atWarning().log("adminURL '%s' is invalid: %s", url, e.getMessage());
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // }
import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish;
return ImmutableMultimap.of(); } SetMultimap<Destination, URIish> uris = HashMultimap.create(); for (Destination config : getAll(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName.isPresent() && !config.getRemoteConfigName().equals(remoteName.get())) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) { repLog.atWarning().log("adminURL '%s' is invalid: %s", url, e.getMessage()); continue; } if (!isGerrit(uri) && !isGerritHttp(uri)) { String path =
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java // public static String replaceName(String in, String name, boolean keyIsOptional) { // String key = "${name}"; // int n = in.indexOf(key); // if (0 <= n) { // return in.substring(0, n) + name + in.substring(n + key.length()); // } // if (keyIsOptional) { // return in; // } // return null; // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationConfig.java // enum FilterType { // PROJECT_CREATION, // PROJECT_DELETION, // ALL // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationsCollection.java import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerrit; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isGerritHttp; import static com.googlesource.gerrit.plugins.replication.AdminApiFactory.isSSH; import static com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.replaceName; import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import static java.util.stream.Collectors.toList; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; import com.google.gerrit.server.git.WorkQueue; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.googlesource.gerrit.plugins.replication.ReplicationConfig.FilterType; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.transport.URIish; return ImmutableMultimap.of(); } SetMultimap<Destination, URIish> uris = HashMultimap.create(); for (Destination config : getAll(filterType)) { if (filterType != FilterType.PROJECT_DELETION && !config.wouldPushProject(projectName)) { continue; } if (remoteName.isPresent() && !config.getRemoteConfigName().equals(remoteName.get())) { continue; } boolean adminURLUsed = false; for (String url : config.getAdminUrls()) { if (Strings.isNullOrEmpty(url)) { continue; } URIish uri; try { uri = new URIish(url); } catch (URISyntaxException e) { repLog.atWarning().log("adminURL '%s' is invalid: %s", url, e.getMessage()); continue; } if (!isGerrit(uri) && !isGerritHttp(uri)) { String path =
replaceName(uri.getPath(), projectName.get(), config.isSingleProjectMatch());
GerritCodeReview/plugins_replication
src/test/java/com/googlesource/gerrit/plugins/replication/ReplicationStateTest.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // }
import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test;
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class ReplicationStateTest { private ReplicationState replicationState; private PushResultProcessing pushResultProcessingMock; @Before public void setUp() throws Exception { pushResultProcessingMock = mock(PushResultProcessing.class); replicationState = new ReplicationState(pushResultProcessingMock); } @Test public void shouldNotHavePushTask() { assertThat(replicationState.hasPushTask()).isFalse(); } @Test public void shouldHavePushTask() { replicationState.increasePushTaskCount("someProject", "someRef"); assertThat(replicationState.hasPushTask()).isTrue(); } @Test public void shouldFireOneReplicationEventWhenNothingToReplicate() { // actual test replicationState.markAllPushTasksScheduled(); // expected event verify(pushResultProcessingMock).onAllRefsReplicatedToAllNodes(0); } @Test public void shouldFireEventsForReplicationOfOneRefToOneNode() throws URISyntaxException { URIish uri = new URIish("git://someHost/someRepo.git"); // actual test replicationState.increasePushTaskCount("someProject", "someRef"); replicationState.markAllPushTasksScheduled(); replicationState.notifyRefReplicated(
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // Path: src/test/java/com/googlesource/gerrit/plugins/replication/ReplicationStateTest.java import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.net.URISyntaxException; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; import org.junit.Before; import org.junit.Test; // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class ReplicationStateTest { private ReplicationState replicationState; private PushResultProcessing pushResultProcessingMock; @Before public void setUp() throws Exception { pushResultProcessingMock = mock(PushResultProcessing.class); replicationState = new ReplicationState(pushResultProcessingMock); } @Test public void shouldNotHavePushTask() { assertThat(replicationState.hasPushTask()).isFalse(); } @Test public void shouldHavePushTask() { replicationState.increasePushTaskCount("someProject", "someRef"); assertThat(replicationState.hasPushTask()).isTrue(); } @Test public void shouldFireOneReplicationEventWhenNothingToReplicate() { // actual test replicationState.markAllPushTasksScheduled(); // expected event verify(pushResultProcessingMock).onAllRefsReplicatedToAllNodes(0); } @Test public void shouldFireEventsForReplicationOfOneRefToOneNode() throws URISyntaxException { URIish uri = new URIish("git://someHost/someRepo.git"); // actual test replicationState.increasePushTaskCount("someProject", "someRef"); replicationState.markAllPushTasksScheduled(); replicationState.notifyRefReplicated(
"someProject", "someRef", uri, RefPushResult.SUCCEEDED, RemoteRefUpdate.Status.OK);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // public static class CommandProcessing implements PushResultProcessing { // private WeakReference<StartCommand> sshCommand; // private AtomicBoolean hasError = new AtomicBoolean(); // // CommandProcessing(StartCommand sshCommand) { // this.sshCommand = new WeakReference<>(sshCommand); // } // // @Override // public void onRefReplicatedToOneNode( // String project, // String ref, // URIish uri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // StringBuilder sb = new StringBuilder(); // sb.append("Replicate "); // sb.append(project); // sb.append(" ref "); // sb.append(ref); // sb.append(" to "); // sb.append(resolveNodeName(uri)); // sb.append(", "); // switch (status) { // case SUCCEEDED: // sb.append("Succeeded!"); // break; // case FAILED: // sb.append("FAILED!"); // hasError.compareAndSet(false, true); // break; // case NOT_ATTEMPTED: // sb.append("NOT ATTEMPTED!"); // break; // default: // sb.append("UNKNOWN RESULT!"); // break; // } // sb.append(" ("); // sb.append(refStatus == null ? "unknown" : refStatus.toString()); // sb.append(")"); // writeStdOut(sb.toString()); // } // // @Override // public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) { // StringBuilder sb = new StringBuilder(); // sb.append("Replication of "); // sb.append(project); // sb.append(" ref "); // sb.append(ref); // sb.append(" completed to "); // sb.append(nodesCount); // sb.append(" nodes, "); // writeStdOut(sb.toString()); // } // // @Override // public void onAllRefsReplicatedToAllNodes(int totalPushTasksCount) { // if (totalPushTasksCount == 0) { // return; // } // writeStdOut("----------------------------------------------"); // if (hasError.get()) { // writeStdOut("Replication completed with some errors!"); // } else { // writeStdOut("Replication completed successfully!"); // } // } // // @Override // public void writeStdOut(String message) { // StartCommand command = sshCommand.get(); // if (command != null) { // command.writeStdOutSync(message); // } // } // // @Override // public void writeStdErr(String message) { // StartCommand command = sshCommand.get(); // if (command != null) { // command.writeStdErrSync(message); // } // } // }
import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.CommandProcessing; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option;
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; @RequiresCapability(StartReplicationCapability.START_REPLICATION) @CommandMetaData( name = "start", description = "Start replication for specific project or all projects") final class StartCommand extends SshCommand { @Inject private ReplicationStateLogger stateLog; @Option(name = "--all", usage = "push all known projects") private boolean all; @Option(name = "--url", metaVar = "PATTERN", usage = "pattern to match URL on") private String urlMatch; @Option(name = "--wait", usage = "wait for replication to finish before exiting") private boolean wait; @Option(name = "--now", usage = "start replication without waiting for replicationDelay") private boolean now; @Argument(index = 0, multiValued = true, metaVar = "PATTERN", usage = "project name pattern") private List<String> projectPatterns = new ArrayList<>(2); @Inject private PushAll.Factory pushFactory; private final Object lock = new Object(); @Override protected void run() throws Failure { if (all && !projectPatterns.isEmpty()) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); }
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // public static class CommandProcessing implements PushResultProcessing { // private WeakReference<StartCommand> sshCommand; // private AtomicBoolean hasError = new AtomicBoolean(); // // CommandProcessing(StartCommand sshCommand) { // this.sshCommand = new WeakReference<>(sshCommand); // } // // @Override // public void onRefReplicatedToOneNode( // String project, // String ref, // URIish uri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // StringBuilder sb = new StringBuilder(); // sb.append("Replicate "); // sb.append(project); // sb.append(" ref "); // sb.append(ref); // sb.append(" to "); // sb.append(resolveNodeName(uri)); // sb.append(", "); // switch (status) { // case SUCCEEDED: // sb.append("Succeeded!"); // break; // case FAILED: // sb.append("FAILED!"); // hasError.compareAndSet(false, true); // break; // case NOT_ATTEMPTED: // sb.append("NOT ATTEMPTED!"); // break; // default: // sb.append("UNKNOWN RESULT!"); // break; // } // sb.append(" ("); // sb.append(refStatus == null ? "unknown" : refStatus.toString()); // sb.append(")"); // writeStdOut(sb.toString()); // } // // @Override // public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) { // StringBuilder sb = new StringBuilder(); // sb.append("Replication of "); // sb.append(project); // sb.append(" ref "); // sb.append(ref); // sb.append(" completed to "); // sb.append(nodesCount); // sb.append(" nodes, "); // writeStdOut(sb.toString()); // } // // @Override // public void onAllRefsReplicatedToAllNodes(int totalPushTasksCount) { // if (totalPushTasksCount == 0) { // return; // } // writeStdOut("----------------------------------------------"); // if (hasError.get()) { // writeStdOut("Replication completed with some errors!"); // } else { // writeStdOut("Replication completed successfully!"); // } // } // // @Override // public void writeStdOut(String message) { // StartCommand command = sshCommand.get(); // if (command != null) { // command.writeStdOutSync(message); // } // } // // @Override // public void writeStdErr(String message) { // StartCommand command = sshCommand.get(); // if (command != null) { // command.writeStdErrSync(message); // } // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/StartCommand.java import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.replication.PushResultProcessing.CommandProcessing; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; // Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; @RequiresCapability(StartReplicationCapability.START_REPLICATION) @CommandMetaData( name = "start", description = "Start replication for specific project or all projects") final class StartCommand extends SshCommand { @Inject private ReplicationStateLogger stateLog; @Option(name = "--all", usage = "push all known projects") private boolean all; @Option(name = "--url", metaVar = "PATTERN", usage = "pattern to match URL on") private String urlMatch; @Option(name = "--wait", usage = "wait for replication to finish before exiting") private boolean wait; @Option(name = "--now", usage = "start replication without waiting for replicationDelay") private boolean now; @Argument(index = 0, multiValued = true, metaVar = "PATTERN", usage = "project name pattern") private List<String> projectPatterns = new ArrayList<>(2); @Inject private PushAll.Factory pushFactory; private final Object lock = new Object(); @Override protected void run() throws Failure { if (all && !projectPatterns.isEmpty()) { throw new UnloggedFailure(1, "error: cannot combine --all and PROJECT"); }
ReplicationState state = new ReplicationState(new CommandProcessing(this));
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/LocalFS.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME);
import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import java.io.File; import java.io.IOException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.URIish;
// Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class LocalFS implements AdminApi { private final URIish uri; public LocalFS(URIish uri) { this.uri = uri; } @Override public boolean createProject(Project.NameKey project, String head) { try (Repository repo = new FileRepository(uri.getPath())) { repo.create(true /* bare */); if (head != null && head.startsWith(Constants.R_REFS)) { RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); }
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // Path: src/main/java/com/googlesource/gerrit/plugins/replication/LocalFS.java import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import java.io.File; import java.io.IOException; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.URIish; // Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class LocalFS implements AdminApi { private final URIish uri; public LocalFS(URIish uri) { this.uri = uri; } @Override public boolean createProject(Project.NameKey project, String head) { try (Repository repo = new FileRepository(uri.getPath())) { repo.create(true /* bare */); if (head != null && head.startsWith(Constants.R_REFS)) { RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(head); }
repLog.atInfo().log("Created local repository: %s", uri);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/DeleteProjectTask.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/ProjectDeletionState.java // public class ProjectDeletionState { // public interface Factory { // ProjectDeletionState create(Project.NameKey project); // } // // private final DynamicItem<EventDispatcher> eventDispatcher; // private final Project.NameKey project; // private final ConcurrentMap<URIish, ProjectDeletionStatus> statusByURI = // new ConcurrentHashMap<>(); // // @Inject // public ProjectDeletionState( // DynamicItem<EventDispatcher> eventDispatcher, @Assisted Project.NameKey project) { // this.eventDispatcher = eventDispatcher; // this.project = project; // } // // public void setToProcess(URIish uri) { // statusByURI.put(uri, TO_PROCESS); // } // // public void setScheduled(URIish uri) { // setStatusAndBroadcastEvent( // uri, SCHEDULED, new ProjectDeletionReplicationScheduledEvent(project.get(), uri)); // } // // public void setSucceeded(URIish uri) { // setStatusAndBroadcastEvent( // uri, SUCCEEDED, new ProjectDeletionReplicationSucceededEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // public void setFailed(URIish uri) { // setStatusAndBroadcastEvent( // uri, FAILED, new ProjectDeletionReplicationFailedEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // private void setStatusAndBroadcastEvent( // URIish uri, ProjectDeletionStatus status, ProjectEvent event) { // statusByURI.put(uri, status); // eventDispatcher.get().postEvent(project, event); // } // // public void notifyIfDeletionDoneOnAllNodes() { // synchronized (statusByURI) { // if (!statusByURI.isEmpty() // && statusByURI.values().stream() // .noneMatch(s -> s.equals(TO_PROCESS) || s.equals(SCHEDULED))) { // // statusByURI.clear(); // eventDispatcher // .get() // .postEvent(project, new ProjectDeletionReplicationDoneEvent(project.get())); // } // } // } // // public enum ProjectDeletionStatus { // TO_PROCESS, // SCHEDULED, // FAILED, // SUCCEEDED; // } // }
import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.events.ProjectDeletionState; import java.util.Optional; import org.eclipse.jgit.transport.URIish;
// Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class DeleteProjectTask implements Runnable { interface Factory { DeleteProjectTask create(
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/ProjectDeletionState.java // public class ProjectDeletionState { // public interface Factory { // ProjectDeletionState create(Project.NameKey project); // } // // private final DynamicItem<EventDispatcher> eventDispatcher; // private final Project.NameKey project; // private final ConcurrentMap<URIish, ProjectDeletionStatus> statusByURI = // new ConcurrentHashMap<>(); // // @Inject // public ProjectDeletionState( // DynamicItem<EventDispatcher> eventDispatcher, @Assisted Project.NameKey project) { // this.eventDispatcher = eventDispatcher; // this.project = project; // } // // public void setToProcess(URIish uri) { // statusByURI.put(uri, TO_PROCESS); // } // // public void setScheduled(URIish uri) { // setStatusAndBroadcastEvent( // uri, SCHEDULED, new ProjectDeletionReplicationScheduledEvent(project.get(), uri)); // } // // public void setSucceeded(URIish uri) { // setStatusAndBroadcastEvent( // uri, SUCCEEDED, new ProjectDeletionReplicationSucceededEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // public void setFailed(URIish uri) { // setStatusAndBroadcastEvent( // uri, FAILED, new ProjectDeletionReplicationFailedEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // private void setStatusAndBroadcastEvent( // URIish uri, ProjectDeletionStatus status, ProjectEvent event) { // statusByURI.put(uri, status); // eventDispatcher.get().postEvent(project, event); // } // // public void notifyIfDeletionDoneOnAllNodes() { // synchronized (statusByURI) { // if (!statusByURI.isEmpty() // && statusByURI.values().stream() // .noneMatch(s -> s.equals(TO_PROCESS) || s.equals(SCHEDULED))) { // // statusByURI.clear(); // eventDispatcher // .get() // .postEvent(project, new ProjectDeletionReplicationDoneEvent(project.get())); // } // } // } // // public enum ProjectDeletionStatus { // TO_PROCESS, // SCHEDULED, // FAILED, // SUCCEEDED; // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DeleteProjectTask.java import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.events.ProjectDeletionState; import java.util.Optional; import org.eclipse.jgit.transport.URIish; // Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class DeleteProjectTask implements Runnable { interface Factory { DeleteProjectTask create(
URIish replicateURI, Project.NameKey project, ProjectDeletionState state);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/DeleteProjectTask.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/ProjectDeletionState.java // public class ProjectDeletionState { // public interface Factory { // ProjectDeletionState create(Project.NameKey project); // } // // private final DynamicItem<EventDispatcher> eventDispatcher; // private final Project.NameKey project; // private final ConcurrentMap<URIish, ProjectDeletionStatus> statusByURI = // new ConcurrentHashMap<>(); // // @Inject // public ProjectDeletionState( // DynamicItem<EventDispatcher> eventDispatcher, @Assisted Project.NameKey project) { // this.eventDispatcher = eventDispatcher; // this.project = project; // } // // public void setToProcess(URIish uri) { // statusByURI.put(uri, TO_PROCESS); // } // // public void setScheduled(URIish uri) { // setStatusAndBroadcastEvent( // uri, SCHEDULED, new ProjectDeletionReplicationScheduledEvent(project.get(), uri)); // } // // public void setSucceeded(URIish uri) { // setStatusAndBroadcastEvent( // uri, SUCCEEDED, new ProjectDeletionReplicationSucceededEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // public void setFailed(URIish uri) { // setStatusAndBroadcastEvent( // uri, FAILED, new ProjectDeletionReplicationFailedEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // private void setStatusAndBroadcastEvent( // URIish uri, ProjectDeletionStatus status, ProjectEvent event) { // statusByURI.put(uri, status); // eventDispatcher.get().postEvent(project, event); // } // // public void notifyIfDeletionDoneOnAllNodes() { // synchronized (statusByURI) { // if (!statusByURI.isEmpty() // && statusByURI.values().stream() // .noneMatch(s -> s.equals(TO_PROCESS) || s.equals(SCHEDULED))) { // // statusByURI.clear(); // eventDispatcher // .get() // .postEvent(project, new ProjectDeletionReplicationDoneEvent(project.get())); // } // } // } // // public enum ProjectDeletionStatus { // TO_PROCESS, // SCHEDULED, // FAILED, // SUCCEEDED; // } // }
import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.events.ProjectDeletionState; import java.util.Optional; import org.eclipse.jgit.transport.URIish;
private final URIish replicateURI; private final Project.NameKey project; private final ProjectDeletionState state; @Inject DeleteProjectTask( DynamicItem<AdminApiFactory> adminApiFactory, IdGenerator ig, @Assisted ProjectDeletionState state, @Assisted URIish replicateURI, @Assisted Project.NameKey project) { this.adminApiFactory = adminApiFactory; this.id = ig.next(); this.replicateURI = replicateURI; this.project = project; this.state = state; } @Override public void run() { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { if (adminApi.get().deleteProject(project)) { state.setSucceeded(replicateURI); } else { state.setFailed(replicateURI); } return; }
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/ProjectDeletionState.java // public class ProjectDeletionState { // public interface Factory { // ProjectDeletionState create(Project.NameKey project); // } // // private final DynamicItem<EventDispatcher> eventDispatcher; // private final Project.NameKey project; // private final ConcurrentMap<URIish, ProjectDeletionStatus> statusByURI = // new ConcurrentHashMap<>(); // // @Inject // public ProjectDeletionState( // DynamicItem<EventDispatcher> eventDispatcher, @Assisted Project.NameKey project) { // this.eventDispatcher = eventDispatcher; // this.project = project; // } // // public void setToProcess(URIish uri) { // statusByURI.put(uri, TO_PROCESS); // } // // public void setScheduled(URIish uri) { // setStatusAndBroadcastEvent( // uri, SCHEDULED, new ProjectDeletionReplicationScheduledEvent(project.get(), uri)); // } // // public void setSucceeded(URIish uri) { // setStatusAndBroadcastEvent( // uri, SUCCEEDED, new ProjectDeletionReplicationSucceededEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // public void setFailed(URIish uri) { // setStatusAndBroadcastEvent( // uri, FAILED, new ProjectDeletionReplicationFailedEvent(project.get(), uri)); // notifyIfDeletionDoneOnAllNodes(); // } // // private void setStatusAndBroadcastEvent( // URIish uri, ProjectDeletionStatus status, ProjectEvent event) { // statusByURI.put(uri, status); // eventDispatcher.get().postEvent(project, event); // } // // public void notifyIfDeletionDoneOnAllNodes() { // synchronized (statusByURI) { // if (!statusByURI.isEmpty() // && statusByURI.values().stream() // .noneMatch(s -> s.equals(TO_PROCESS) || s.equals(SCHEDULED))) { // // statusByURI.clear(); // eventDispatcher // .get() // .postEvent(project, new ProjectDeletionReplicationDoneEvent(project.get())); // } // } // } // // public enum ProjectDeletionStatus { // TO_PROCESS, // SCHEDULED, // FAILED, // SUCCEEDED; // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DeleteProjectTask.java import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.server.ioutil.HexFormat; import com.google.gerrit.server.util.IdGenerator; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.googlesource.gerrit.plugins.replication.events.ProjectDeletionState; import java.util.Optional; import org.eclipse.jgit.transport.URIish; private final URIish replicateURI; private final Project.NameKey project; private final ProjectDeletionState state; @Inject DeleteProjectTask( DynamicItem<AdminApiFactory> adminApiFactory, IdGenerator ig, @Assisted ProjectDeletionState state, @Assisted URIish replicateURI, @Assisted Project.NameKey project) { this.adminApiFactory = adminApiFactory; this.id = ig.next(); this.replicateURI = replicateURI; this.project = project; this.state = state; } @Override public void run() { Optional<AdminApi> adminApi = adminApiFactory.get().create(replicateURI); if (adminApi.isPresent()) { if (adminApi.get().deleteProject(project)) { state.setSucceeded(replicateURI); } else { state.setFailed(replicateURI); } return; }
repLog.atWarning().log("Cannot delete project %s on remote site %s.", project, replicateURI);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/Init.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_REPLICATION_DELAY = 15; // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_RESCHEDULE_DELAY = 3;
import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_REPLICATION_DELAY; import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_RESCHEDULE_DELAY; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitStep; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.File; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS;
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class Init implements InitStep { private final String pluginName; private final SitePaths site; private final ConsoleUI ui; @Inject Init(@PluginName String pluginName, SitePaths site, ConsoleUI ui) { this.pluginName = pluginName; this.site = site; this.ui = ui; } @Override public void run() throws Exception { File configFile = site.etc_dir.resolve(pluginName + ".config").toFile(); if (!configFile.exists()) { return; } FileBasedConfig config = new FileBasedConfig(configFile, FS.DETECTED); config.load(); for (String name : config.getSubsections("remote")) { if (!Strings.isNullOrEmpty(config.getString("remote", name, "rescheduleDelay"))) { continue; } int replicationDelay =
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_REPLICATION_DELAY = 15; // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_RESCHEDULE_DELAY = 3; // Path: src/main/java/com/googlesource/gerrit/plugins/replication/Init.java import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_REPLICATION_DELAY; import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_RESCHEDULE_DELAY; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitStep; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.File; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; // Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class Init implements InitStep { private final String pluginName; private final SitePaths site; private final ConsoleUI ui; @Inject Init(@PluginName String pluginName, SitePaths site, ConsoleUI ui) { this.pluginName = pluginName; this.site = site; this.ui = ui; } @Override public void run() throws Exception { File configFile = site.etc_dir.resolve(pluginName + ".config").toFile(); if (!configFile.exists()) { return; } FileBasedConfig config = new FileBasedConfig(configFile, FS.DETECTED); config.load(); for (String name : config.getSubsections("remote")) { if (!Strings.isNullOrEmpty(config.getString("remote", name, "rescheduleDelay"))) { continue; } int replicationDelay =
config.getInt("remote", name, "replicationDelay", DEFAULT_REPLICATION_DELAY);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/Init.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_REPLICATION_DELAY = 15; // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_RESCHEDULE_DELAY = 3;
import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_REPLICATION_DELAY; import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_RESCHEDULE_DELAY; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitStep; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.File; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS;
// Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class Init implements InitStep { private final String pluginName; private final SitePaths site; private final ConsoleUI ui; @Inject Init(@PluginName String pluginName, SitePaths site, ConsoleUI ui) { this.pluginName = pluginName; this.site = site; this.ui = ui; } @Override public void run() throws Exception { File configFile = site.etc_dir.resolve(pluginName + ".config").toFile(); if (!configFile.exists()) { return; } FileBasedConfig config = new FileBasedConfig(configFile, FS.DETECTED); config.load(); for (String name : config.getSubsections("remote")) { if (!Strings.isNullOrEmpty(config.getString("remote", name, "rescheduleDelay"))) { continue; } int replicationDelay = config.getInt("remote", name, "replicationDelay", DEFAULT_REPLICATION_DELAY); if (replicationDelay > 0) {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_REPLICATION_DELAY = 15; // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/DestinationConfiguration.java // static final int DEFAULT_RESCHEDULE_DELAY = 3; // Path: src/main/java/com/googlesource/gerrit/plugins/replication/Init.java import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_REPLICATION_DELAY; import static com.googlesource.gerrit.plugins.replication.DestinationConfiguration.DEFAULT_RESCHEDULE_DELAY; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginName; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitStep; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.File; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; // Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class Init implements InitStep { private final String pluginName; private final SitePaths site; private final ConsoleUI ui; @Inject Init(@PluginName String pluginName, SitePaths site, ConsoleUI ui) { this.pluginName = pluginName; this.site = site; this.ui = ui; } @Override public void run() throws Exception { File configFile = site.etc_dir.resolve(pluginName + ".config").toFile(); if (!configFile.exists()) { return; } FileBasedConfig config = new FileBasedConfig(configFile, FS.DETECTED); config.load(); for (String name : config.getSubsections("remote")) { if (!Strings.isNullOrEmpty(config.getString("remote", name, "rescheduleDelay"))) { continue; } int replicationDelay = config.getInt("remote", name, "replicationDelay", DEFAULT_REPLICATION_DELAY); if (replicationDelay > 0) {
int delay = Math.max(replicationDelay, DEFAULT_RESCHEDULE_DELAY);
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // }
import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish;
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public interface PushResultProcessing { public static final PushResultProcessing NO_OP = new PushResultProcessing() {}; /** * Invoked when a ref has been replicated to one node. * * @param project the project name * @param ref the ref name * @param uri the URI * @param status the status of the push * @param refStatus the status for the ref */ default void onRefReplicatedToOneNode( String project, String ref, URIish uri,
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public interface PushResultProcessing { public static final PushResultProcessing NO_OP = new PushResultProcessing() {}; /** * Invoked when a ref has been replicated to one node. * * @param project the project name * @param ref the ref name * @param uri the URI * @param status the status of the push * @param refStatus the status for the ref */ default void onRefReplicatedToOneNode( String project, String ref, URIish uri,
RefPushResult status,
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // }
import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish;
if (command != null) { command.writeStdOutSync(message); } } @Override public void writeStdErr(String message) { StartCommand command = sshCommand.get(); if (command != null) { command.writeStdErrSync(message); } } } public static class GitUpdateProcessing implements PushResultProcessing { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final EventDispatcher dispatcher; public GitUpdateProcessing(EventDispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public void onRefReplicatedToOneNode( String project, String ref, URIish uri, RefPushResult status, RemoteRefUpdate.Status refStatus) {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; if (command != null) { command.writeStdOutSync(message); } } @Override public void writeStdErr(String message) { StartCommand command = sshCommand.get(); if (command != null) { command.writeStdErrSync(message); } } } public static class GitUpdateProcessing implements PushResultProcessing { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final EventDispatcher dispatcher; public GitUpdateProcessing(EventDispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public void onRefReplicatedToOneNode( String project, String ref, URIish uri, RefPushResult status, RemoteRefUpdate.Status refStatus) {
postEvent(new RefReplicatedEvent(project, ref, uri, status, refStatus));
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // }
import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish;
@Override public void writeStdErr(String message) { StartCommand command = sshCommand.get(); if (command != null) { command.writeStdErrSync(message); } } } public static class GitUpdateProcessing implements PushResultProcessing { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final EventDispatcher dispatcher; public GitUpdateProcessing(EventDispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public void onRefReplicatedToOneNode( String project, String ref, URIish uri, RefPushResult status, RemoteRefUpdate.Status refStatus) { postEvent(new RefReplicatedEvent(project, ref, uri, status, refStatus)); } @Override public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java // public class RefReplicatedEvent extends RemoteRefReplicationEvent { // public static final String TYPE = "ref-replicated"; // // @Deprecated public final String targetNode; // public final Status refStatus; // // public RefReplicatedEvent( // String project, // String ref, // URIish targetUri, // RefPushResult status, // RemoteRefUpdate.Status refStatus) { // super(TYPE, project, ref, targetUri, status.toString()); // this.targetNode = resolveNodeName(targetUri); // this.refStatus = refStatus; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicatedEvent)) { // return false; // } // RefReplicatedEvent event = (RefReplicatedEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (!Objects.equals(event.targetNode, this.targetNode)) { // return false; // } // if (!Objects.equals(event.targetUri, this.targetUri)) { // return false; // } // if (!Objects.equals(event.status, this.status)) { // return false; // } // if (!Objects.equals(event.refStatus, this.refStatus)) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicationDoneEvent.java // public class RefReplicationDoneEvent extends RefEvent { // public static final String TYPE = "ref-replication-done"; // // final String project; // final String ref; // final int nodesCount; // // public RefReplicationDoneEvent(String project, String ref, int nodesCount) { // super(TYPE); // this.project = project; // this.ref = ref; // this.nodesCount = nodesCount; // } // // @Override // public Project.NameKey getProjectNameKey() { // return Project.nameKey(project); // } // // @Override // public String getRefName() { // return ref; // } // // @Override // public boolean equals(Object other) { // if (!(other instanceof RefReplicationDoneEvent)) { // return false; // } // // RefReplicationDoneEvent event = (RefReplicationDoneEvent) other; // if (!Objects.equals(event.project, this.project)) { // return false; // } // if (!Objects.equals(event.ref, this.ref)) { // return false; // } // if (event.nodesCount != this.nodesCount) { // return false; // } // return true; // } // // @Override // public int hashCode() { // return super.hashCode(); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java import com.google.common.flogger.FluentLogger; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.server.events.EventDispatcher; import com.google.gerrit.server.events.RefEvent; import com.google.gerrit.server.permissions.PermissionBackendException; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import com.googlesource.gerrit.plugins.replication.events.RefReplicatedEvent; import com.googlesource.gerrit.plugins.replication.events.RefReplicationDoneEvent; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.URIish; @Override public void writeStdErr(String message) { StartCommand command = sshCommand.get(); if (command != null) { command.writeStdErrSync(message); } } } public static class GitUpdateProcessing implements PushResultProcessing { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final EventDispatcher dispatcher; public GitUpdateProcessing(EventDispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public void onRefReplicatedToOneNode( String project, String ref, URIish uri, RefPushResult status, RemoteRefUpdate.Status refStatus) { postEvent(new RefReplicatedEvent(project, ref, uri, status, refStatus)); } @Override public void onRefReplicatedToAllNodes(String project, String ref, int nodesCount) {
postEvent(new RefReplicationDoneEvent(project, ref, nodesCount));
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME);
import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginData; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.IOException; import java.nio.file.Path; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS;
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class ReplicationFileBasedConfig implements ReplicationConfig { private static final int DEFAULT_SSH_CONNECTION_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes private final SitePaths site; private Path cfgPath; private boolean replicateAllOnPluginStart; private boolean defaultForceUpdate; private int maxRefsToLog; private final int maxRefsToShow; private int sshCommandTimeout; private int sshConnectionTimeout = DEFAULT_SSH_CONNECTION_TIMEOUT_MS; private final FileBasedConfig config; private final Path pluginDataDir; @Inject public ReplicationFileBasedConfig(SitePaths site, @PluginData Path pluginDataDir) { this.site = site; this.cfgPath = site.etc_dir.resolve("replication.config"); this.config = new FileBasedConfig(cfgPath.toFile(), FS.DETECTED); try { config.load(); } catch (ConfigInvalidException e) {
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationQueue.java // static final NamedFluentLogger repLog = NamedFluentLogger.forName(REPLICATION_LOG_NAME); // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationFileBasedConfig.java import static com.googlesource.gerrit.plugins.replication.ReplicationQueue.repLog; import com.google.common.base.Strings; import com.google.gerrit.extensions.annotations.PluginData; import com.google.gerrit.server.config.SitePaths; import com.google.inject.Inject; import java.io.IOException; import java.nio.file.Path; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication; public class ReplicationFileBasedConfig implements ReplicationConfig { private static final int DEFAULT_SSH_CONNECTION_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes private final SitePaths site; private Path cfgPath; private boolean replicateAllOnPluginStart; private boolean defaultForceUpdate; private int maxRefsToLog; private final int maxRefsToShow; private int sshCommandTimeout; private int sshConnectionTimeout = DEFAULT_SSH_CONNECTION_TIMEOUT_MS; private final FileBasedConfig config; private final Path pluginDataDir; @Inject public ReplicationFileBasedConfig(SitePaths site, @PluginData Path pluginDataDir) { this.site = site; this.cfgPath = site.etc_dir.resolve("replication.config"); this.config = new FileBasedConfig(cfgPath.toFile(), FS.DETECTED); try { config.load(); } catch (ConfigInvalidException e) {
repLog.atSevere().withCause(e).log("Config file %s is invalid: %s", cfgPath, e.getMessage());
GerritCodeReview/plugins_replication
src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // static String resolveNodeName(URIish uri) { // StringBuilder sb = new StringBuilder(); // if (uri.isRemote()) { // sb.append(uri.getHost()); // if (uri.getPort() != -1) { // sb.append(":"); // sb.append(uri.getPort()); // } // } else { // sb.append(uri.getPath()); // } // return sb.toString(); // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // }
import static com.googlesource.gerrit.plugins.replication.PushResultProcessing.resolveNodeName; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.util.Objects; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.URIish;
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication.events; public class RefReplicatedEvent extends RemoteRefReplicationEvent { public static final String TYPE = "ref-replicated"; @Deprecated public final String targetNode; public final Status refStatus; public RefReplicatedEvent( String project, String ref, URIish targetUri,
// Path: src/main/java/com/googlesource/gerrit/plugins/replication/PushResultProcessing.java // static String resolveNodeName(URIish uri) { // StringBuilder sb = new StringBuilder(); // if (uri.isRemote()) { // sb.append(uri.getHost()); // if (uri.getPort() != -1) { // sb.append(":"); // sb.append(uri.getPort()); // } // } else { // sb.append(uri.getPath()); // } // return sb.toString(); // } // // Path: src/main/java/com/googlesource/gerrit/plugins/replication/ReplicationState.java // public enum RefPushResult { // /** The ref was not successfully replicated. */ // FAILED, // // /** The ref is not configured to be replicated. */ // NOT_ATTEMPTED, // // /** The ref was successfully replicated. */ // SUCCEEDED; // // @Override // public String toString() { // return name().toLowerCase().replace("_", "-"); // } // } // Path: src/main/java/com/googlesource/gerrit/plugins/replication/events/RefReplicatedEvent.java import static com.googlesource.gerrit.plugins.replication.PushResultProcessing.resolveNodeName; import com.googlesource.gerrit.plugins.replication.ReplicationState.RefPushResult; import java.util.Objects; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.RemoteRefUpdate.Status; import org.eclipse.jgit.transport.URIish; // Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.replication.events; public class RefReplicatedEvent extends RemoteRefReplicationEvent { public static final String TYPE = "ref-replicated"; @Deprecated public final String targetNode; public final Status refStatus; public RefReplicatedEvent( String project, String ref, URIish targetUri,
RefPushResult status,