Dataset Viewer
Auto-converted to Parquet
id
stringlengths
8
13
source
stringlengths
164
33.1k
target
stringlengths
36
5.98k
486214_0
class CommonSource extends ReflectiveExpressionSource { @Property public Object emit() { return Attribute.ATTR_EMIT; } @Inject public CommonSource(Stage stage); @Property public Object skip(); @Method public String urlencode(String in); @Method("urlencode") public String urlencodeInput(@Instance String in); @Method public String htmlencode(String in); @Method("htmlencode") public String htmlencodeInput(@Instance String in); } class CommonSourceTest extends ReflectiveExpressionSource { @Test public void testEmit() {
Assert.assertEquals(Attribute.ATTR_EMIT, execute("t:emit", "")); Assert.assertEquals(Attribute.ATTR_EMIT, execute("true ? t:emit", "")); } }
486214_1
class CommonSource extends ReflectiveExpressionSource { @Property public Object skip() { return Attribute.ATTR_SKIP; } @Inject public CommonSource(Stage stage); @Property public Object emit(); @Method public String urlencode(String in); @Method("urlencode") public String urlencodeInput(@Instance String in); @Method public String htmlencode(String in); @Method("htmlencode") public String htmlencodeInput(@Instance String in); } class CommonSourceTest extends ReflectiveExpressionSource { @Test public void testSkip() {
Assert.assertEquals(Attribute.ATTR_SKIP, execute("t:skip", "")); Assert.assertEquals(Attribute.ATTR_SKIP, execute("true ? t:skip", "")); } }
781084_0
class WebHookSecurityInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return webHookAdapter.isValidRequest(request); } } class TestWebHookSecurityInterceptor { @Test public void testPreHandle() throws Exception {
MyTestWebHookAdapter adapter = new MyTestWebHookAdapter(); WebHookSecurityInterceptor interceptor = new WebHookSecurityInterceptor(); // set the adapter like spring would do. Field field = WebHookSecurityInterceptor.class.getDeclaredField("webHookAdapter"); field.setAccessible(true); field.set(interceptor, adapter); field.setAccessible(false); // call the interceptor. interceptor.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), null); // all we have to check is if the adapter was called. assertTrue(adapter.wasCalled("isValidRequest")); } }
854893_4
class Converters { public static <T, V> Converter<T, V> get(Class<T> from, Class<V> to) { if (to == Integer.class || to == int.class) { if (from == Byte.class || from == byte.class) { return (Converter<T, V>) byteToInteger; } else if (from == Short.class || from == short.class) { return (Converter<T, V>) shortToInteger; } else if (from == Long.class || from == long.class) { return (Converter<T, V>) longToInteger; } else { return null; } } else { return null; } } public static int toInt(T value); } class ConvertersTest { @Test public void testConversions() {
assertNull(Converters.get(String.class, Boolean.class)); Converter<Byte, Integer> converter1 = Converters.get(Byte.class, Integer.class); assertNotNull(converter1); assertEquals(new Integer(3), converter1.convert(new Byte((byte) 3))); Converter<Short, Integer> converter2 = Converters.get(Short.class, Integer.class); assertNotNull(converter2); assertEquals(new Integer(3), converter2.convert(new Short((byte) 3))); Converter<Long, Integer> converter3 = Converters.get(Long.class, Integer.class); assertNotNull(converter3); assertEquals(new Integer(3), converter3.convert(new Long(3))); } }
854893_5
class VariableContext implements ReferenceContext<VariableResolver> { public Reference<VariableResolver> selectAttribute(String name) { return new VariableReference(name, this); } public VariableContext(VariableDefinitions defs); public Reference<VariableResolver> selectItem(String index); public Reference<VariableResolver> selectItem( Expression<Integer, VariableResolver> index); public void document(Document target); } class VariableContextTest { @Test public void testPropertySelectors() {
final Data data = new Data(); data.data = new Data(); data.data.str = "foobar"; VariableDefinitions defs = new DataVariableDefinitions(); VariableContext context = new VariableContext(defs); Reference<VariableResolver> reference = context.selectAttribute("data"); reference = reference.selectAttribute("data"); reference = reference.selectAttribute("str"); assertEquals("foobar", reference.resolve(new DataResolver(data))); } }
854893_7
class MultiReference implements Reference<E> { public Reference<E> narrow(Class<?> type) throws BindingException { List<Reference<E>> resulting = new ArrayList<Reference<E>>(); for (Reference<E> reference :references) { Reference<E> result = reference.narrow(type); if (result != null) { resulting.add(result); } } if (resulting.size() == 0) { return null; } else { return new MultiReference<E>(resulting.toArray(REFERENCE_ARRAY_TYPE)); } } public MultiReference(Reference<E>... references); private static Class<?> calculateCommonSuperType( Reference<E>... references); public ReferenceContext<E> getReferenceContext(); public Object resolve(E context); public Reference<E> selectItem(String index); public Reference<E> selectItem(Expression<Integer, E> index); public Reference<E> selectAttribute(String name); public void document(Document target); public boolean isAssignableTo(Class<?> type); public Class<?> getType(); public boolean isBasedOn(ReferenceContext<E> context); public Reference<E> rescope(ReferenceContext<E> eReferenceContext); private Reference reference1; private Reference reference2; private Reference reference3; private ReferenceContext context; } class MultiReferenceTest { private Reference reference1; private Reference reference2; private Reference reference3; private ReferenceContext context; @Test public void testNarrow() {
StringBuilder builder = new StringBuilder(); Document document = new StringBuilderDocument(builder); String propertyName = "pi"; expect(reference1.narrow(String.class)).andReturn(reference1); expect(reference2.narrow(String.class)).andReturn(reference2); expect(reference1.getType()).andReturn(String.class).times(2); expect(reference2.getType()).andReturn(String.class).times(2); expect(reference1.getReferenceContext()).andReturn(context).times(2); expect(reference2.getReferenceContext()).andReturn(context).times(2); replay(reference1, reference2, context); MultiReference multi = new MultiReference(reference1, reference2); multi.narrow(String.class); verify(reference1, reference2, context); } }
1552601_0
class FilePublicKeyProvider extends AbstractKeyPairProvider { public Iterable<KeyPair> loadKeys() { if (!SecurityUtils.isBouncyCastleRegistered()) { throw new IllegalStateException("BouncyCastle must be registered as a JCE provider"); } List<KeyPair> keys = new ArrayList<KeyPair>(); for (String file : files) { try { Object o = KeyPairUtils.readKey(new InputStreamReader(new FileInputStream(file))); if (o instanceof KeyPair) { keys.add(new KeyPair(((KeyPair)o).getPublic(), null)); } else if (o instanceof PublicKey) { keys.add(new KeyPair((PublicKey)o, null)); } else if (o instanceof PEMKeyPair) { PEMKeyPair keyPair = (PEMKeyPair)o; keys.add(convertPemKeyPair(keyPair)); } else if (o instanceof SubjectPublicKeyInfo) { PEMKeyPair keyPair = new PEMKeyPair((SubjectPublicKeyInfo) o, null); keys.add(convertPemKeyPair(keyPair)); } else { throw new UnsupportedOperationException(String.format("Key type %s not supported.", o.getClass().getName())); } } catch (Exception e) { LOG.info("Unable to read key {}: {}", file, e); } } return keys; } FilePublicKeyProvider(String[] files); private KeyPair convertPemKeyPair(PEMKeyPair pemKeyPair); } class FilePublicKeyProviderTest { @Test public void test() {
String pubKeyFile = Thread.currentThread().getContextClassLoader().getResource("test_authorized_key.pem").getFile(); assertTrue(new File(pubKeyFile).exists()); FilePublicKeyProvider SUT = new FilePublicKeyProvider(new String[]{pubKeyFile}); assertTrue(SUT.loadKeys().iterator().hasNext()); } }
1556938_0
class Erector { public BlueprintTemplate getTemplate() { return blueprintTemplate; } public Erector(); public Object createNewInstance(); public void addCommands(ModelField modelField, Set<Command> commands); public void addCommand( ModelField modelField, Command command ); public Set<Command> getCommands( ModelField modelField ); public void clearCommands(); public Object getBlueprint(); public void setBlueprint(Object blueprint); public Collection<ModelField> getModelFields(); public ModelField getModelField(String name); public void setModelFields(Collection<ModelField> modelFields); public void addModelField(ModelField modelField); public void setTemplate(BlueprintTemplate blueprintTemplate); public Class getTarget(); public void setTarget(Class target); public Object getReference(); public void setReference(Object reference); public Constructable getNewInstance(); public void setNewInstance(Constructable newInstance); public void setCallbacks(String type, List<Callback> callbacks); public List<Callback> getCallbacks(String type); public String toString(); public Erector erector; public DefaultField defaultField; public CarBlueprint carBlueprint; } class ErectorTest { public Erector erector; public DefaultField defaultField; public CarBlueprint carBlueprint; @Test public void testGet() throws BlueprintTemplateException {
Car car = new Car(); car.setMileage(new Float(123.456)); Float val = (Float) erector.getTemplate().get(car, "mileage"); assertEquals(new Float(123.456), val); } }
1644710_0
class RestBuilder { public Model buildModel(Iterable<NamedInputSupplier> suppliers) throws IOException { List<Model> models = Lists.newArrayList(); for (NamedInputSupplier supplier : suppliers) { Model model = buildModel(supplier); models.add(model); } return new MultiModel(models).resolve(); } public boolean isTracingEnabled(); public void setTracingEnabled(boolean tracingEnabled); private Model buildModel(NamedInputSupplier supplier); private Model model; } class RestBuilderTest { private Model model; @Test public void testBuildModel() throws Exception {
assertThat(model) .describedAs("A restbuilder model object") .isNotNull() .isInstanceOf(Model.class); assertThat(model.getNamespace()).isEqualTo("example"); assertThat(model.getOperations()).isNotEmpty().hasSize(2); Resource accountResource = model.getResources().get("account"); assertThat(accountResource.getPreamble()).isNotEmpty(); assertThat(accountResource.getComment()).isNotEmpty(); Operation cancellationOperation = accountResource.getOperations().get("cancellation"); assertThat(cancellationOperation.getAttributes()).isNotEmpty(); } }
2017533_0
class FlacAudioFileReader extends AudioFileReader { public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = new FileInputStream(file); try { return getAudioInputStream(inputStream, (int) file.length()); } catch (UnsupportedAudioFileException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } catch (IOException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } } public AudioFileFormat getAudioFileFormat(File file); public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioInputStreamWithFlacFile() throws UnsupportedAudioFileException, IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final AudioInputStream stream = flacAudioFileReader.getAudioInputStream(getFlacTestFile("cymbals.flac")); assertNotNull(stream); } }
2017533_1
class FlacAudioFileReader extends AudioFileReader { public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = new FileInputStream(file); try { return getAudioInputStream(inputStream, (int) file.length()); } catch (UnsupportedAudioFileException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } catch (IOException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } } public AudioFileFormat getAudioFileFormat(File file); public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioInputStreamWithBufferedFlacStream() throws UnsupportedAudioFileException, IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File flacTestFile = getFlacTestFile("cymbals.flac"); InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(flacTestFile)); assertTrue("For this test the stream MUST support mark()", in.markSupported()); final AudioInputStream stream = flacAudioFileReader.getAudioInputStream(in); assertNotNull(stream); final AudioFormat format = stream.getFormat(); assertEquals(44100f, format.getSampleRate(), 0); assertEquals(16, format.getSampleSizeInBits()); assertEquals(2, format.getChannels()); assertEquals("FLAC", format.getEncoding().toString()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2017533_2
class FlacAudioFileReader extends AudioFileReader { public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = new FileInputStream(file); try { return getAudioInputStream(inputStream, (int) file.length()); } catch (UnsupportedAudioFileException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } catch (IOException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } } public AudioFileFormat getAudioFileFormat(File file); public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioInputStreamWithUnbufferedFlacStream() throws IOException, UnsupportedAudioFileException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File flacTestFile = getFlacTestFile("cymbals.flac"); InputStream in = null; try { in = new FileInputStream(flacTestFile); assertFalse("For this test the stream MUST NOT support mark()", in.markSupported()); flacAudioFileReader.getAudioInputStream(in); fail("Expected an IOException, because the stream didn't support mark. See AudioSystem#getAudioInputStream(InputStream stream) javadocs for contract"); } catch (IOException e) { // expected this } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2017533_3
class FlacAudioFileReader extends AudioFileReader { public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = null; try { inputStream = new FileInputStream(file); return getAudioFileFormat(inputStream, (int) file.length()); } finally { if (inputStream != null) inputStream.close(); } } public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(File file); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioFileFormatWithBufferedFlacStream() throws UnsupportedAudioFileException, IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File flacTestFile = getFlacTestFile("cymbals.flac"); InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(flacTestFile)); assertTrue("For this test the stream MUST support mark()", in.markSupported()); final AudioFileFormat fileFormat = flacAudioFileReader.getAudioFileFormat(in); assertNotNull(fileFormat); final AudioFormat format = fileFormat.getFormat(); assertEquals(44100f, format.getSampleRate(), 0); assertEquals(16, format.getSampleSizeInBits()); assertEquals(2, format.getChannels()); assertEquals("FLAC", format.getEncoding().toString()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2017533_4
class FlacAudioFileReader extends AudioFileReader { public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = null; try { inputStream = new FileInputStream(file); return getAudioFileFormat(inputStream, (int) file.length()); } finally { if (inputStream != null) inputStream.close(); } } public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(File file); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioFileFormatWithUnbufferedFlacStream() throws IOException, UnsupportedAudioFileException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File flacTestFile = getFlacTestFile("cymbals.flac"); InputStream in = null; try { in = new FileInputStream(flacTestFile); assertFalse("For this test the stream MUST NOT support mark()", in.markSupported()); flacAudioFileReader.getAudioFileFormat(in); fail("Expected an IOException, because the stream didn't support mark. See AudioSystem#getAudioFileFormat(InputStream stream) javadocs for contract"); } catch (IOException e) { // expected this } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2017533_5
class FlacAudioFileReader extends AudioFileReader { public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = null; try { inputStream = new FileInputStream(file); return getAudioFileFormat(inputStream, (int) file.length()); } finally { if (inputStream != null) inputStream.close(); } } public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(File file); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioFileFormatWithFlacFile() throws UnsupportedAudioFileException, IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final AudioFileFormat audioFileFormat = flacAudioFileReader.getAudioFileFormat(getFlacTestFile("cymbals.flac")); assertNotNull(audioFileFormat); assertEquals("flac", audioFileFormat.getType().getExtension()); assertEquals(new Long(9338775), audioFileFormat.getProperty("duration")); assertEquals(411840, audioFileFormat.getFrameLength()); final AudioFormat format = audioFileFormat.getFormat(); assertEquals(44100f, format.getSampleRate(), 0); assertEquals(16, format.getSampleSizeInBits()); assertEquals(2, format.getChannels()); assertEquals("FLAC", format.getEncoding().toString()); } }
2017533_6
class FlacAudioFileReader extends AudioFileReader { public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = new FileInputStream(file); try { return getAudioInputStream(inputStream, (int) file.length()); } catch (UnsupportedAudioFileException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } catch (IOException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } } public AudioFileFormat getAudioFileFormat(File file); public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioInputStreamWithUnsupportedFile() throws IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File file = File.createTempFile("flacTest", ".wav"); final OutputStream out = new FileOutputStream(file); out.write(new byte[2048]); out.close(); try { flacAudioFileReader.getAudioInputStream(file); fail("Expected UnsupportedAudioFileException"); } catch (UnsupportedAudioFileException e) { // expected this } finally { file.delete(); } } }
2017533_7
class FlacAudioFileReader extends AudioFileReader { public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { InputStream inputStream = new FileInputStream(file); try { return getAudioInputStream(inputStream, (int) file.length()); } catch (UnsupportedAudioFileException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } catch (IOException e) { try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } throw e; } } public AudioFileFormat getAudioFileFormat(File file); public AudioFileFormat getAudioFileFormat(URL url); public AudioFileFormat getAudioFileFormat(InputStream stream); protected AudioFileFormat getAudioFileFormat(InputStream bitStream, int mediaLength); public AudioInputStream getAudioInputStream(URL url); public AudioInputStream getAudioInputStream(final InputStream stream); protected AudioInputStream getAudioInputStream(InputStream inputStream, int medialength); } class FlacAudioFileReaderTest { @Test public void testGetAudioFileFormatWithUnsupportedFile() throws IOException {
final FlacAudioFileReader flacAudioFileReader = new FlacAudioFileReader(); final File file = File.createTempFile("flacTest", ".wav"); final OutputStream out = new FileOutputStream(file); out.write(new byte[2048]); out.close(); try { flacAudioFileReader.getAudioInputStream(file); fail("Expected UnsupportedAudioFileException"); } catch (UnsupportedAudioFileException e) { // expected this } finally { file.delete(); } } }
2193717_0
class ConvertClassToReflectedTypeMatcher implements Converter<Class<?>, Matcher<FluentAccess<?>>> { @Override public Matcher<FluentAccess<?>> convert(final Class<?> from) { return reflectingOn(from); } } class TestConvertClassToReflectedTypeMatcher { @Test public void classConvertedToMatcherForReflectedType() throws Exception {
final Matcher<FluentAccess<?>> matcherUnderTest = new ConvertClassToReflectedTypeMatcher().convert(ExampleClass.class); assertThat(type(ExampleClass.class), matcherUnderTest); } }
2193717_2
class ConvertClassToReflectedType implements Converter<Class<?>, FluentClass<?>> { @Override public FluentClass<?> convert(final Class<?> from) { return reflectedTypeFactory.reflect(from); } public ConvertClassToReflectedType(final ReflectedTypeFactory reflectedTypeFactory); } class TestConvertClassToReflectedType { @Test public void classCanBeConvertedToReflectedType() throws Exception {
assertThat( new ConvertClassToReflectedType(new ReflectedTypeFactoryImpl()).convert(ExampleClass.class), reflectingOn(ExampleClass.class)); } }
2280644_0
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testSame() {
String s1 = "abcde"; String s2 = "abcde"; assertTrue(s1 + " should equals " + s2, posixComparator.compare(s1, s2) == 0); } }
2280644_1
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testDifferentNames() {
String s1 = "Abcde"; String s2 = "Bbcde"; assertTrue(s1 + " should be before " + s2, posixComparator.compare(s1, s2) < 0); String s3 = "abcde"; String s4 = "Bbcde"; assertTrue(s3 + " should be before " + s4, posixComparator.compare(s3, s4) < 0); String s5 = "bbcde"; String s6 = "Abcde"; assertTrue(s5 + " should be after " + s6, posixComparator.compare(s5, s6) > 0); } }
2280644_2
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testIgnoreCasesDifferentLength() {
String s1 = "abcde"; String s2 = "Abc"; assertTrue(s1 + " should be after " + s2, posixComparator.compare(s1, s2) > 0); String s3 = "Abcde"; String s4 = "abc"; assertTrue(s3 + " should be after " + s4, posixComparator.compare(s3, s4) > 0); } }
2280644_3
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testIgnoreDotsDifferent() {
String s1 = ".Abcde"; String s2 = "Bbcde"; assertTrue(s1 + " should be before " + s2, posixComparator.compare(s1, s2) < 0); String s3 = "Abcde"; String s4 = ".Bbcde"; assertTrue(s3 + " should be before " + s4, posixComparator.compare(s3, s4) < 0); } }
2280644_4
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testLowerCaseBeforeUpperCases() {
String s1 = "abcde"; String s2 = "Abcde"; assertTrue(s1 + " should be before " + s2, posixComparator.compare(s1, s2) < 0); String s3 = "AbCde"; String s4 = "Abcde"; assertTrue(s3 + " should be after " + s4, posixComparator.compare(s3, s4) > 0); } }
2280644_5
class PosixFileNameComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { String o1WithoutDot = o1; String o2WithoutDot = o2; if (o1.indexOf(AeshConstants.DOT) == 0) { o1WithoutDot = o1.substring(1); } if (o2.indexOf(AeshConstants.DOT) == 0) { o2WithoutDot = o2.substring(1); } // if names are same when removed dot, make without dot first // if names are same when ignored case, make lower case first (by default compareTo returns upper case first) if (o1WithoutDot.compareTo(o2WithoutDot) == 0) { return o2.compareTo(o1); } else if (o1WithoutDot.compareToIgnoreCase(o2WithoutDot) == 0) { return o2WithoutDot.compareTo(o1WithoutDot); } else { return o1WithoutDot.compareToIgnoreCase(o2WithoutDot); } } private Comparator<String> posixComparator; } class PosixFileNameComparatorTest { private Comparator<String> posixComparator; @Test public void testIgnoreDotsSameName() {
String s1 = ".abcde"; String s2 = "abcde"; assertTrue(s1 + " should be after " + s2, posixComparator.compare(s1, s2) > 0); String s3 = "abcde"; String s4 = ".abcde"; assertTrue(s3 + " should be before " + s4, posixComparator.compare(s3, s4) < 0); } }
2280644_6
class GraalReflectionFileGenerator { public void generateReflection(CommandLineParser<CommandInvocation> parser, Writer w) throws IOException { w.append('[').append(getLineSeparator()); processCommand(parser, w); appendOptions(w); w.append(getLineSeparator()).append("]"); } public GraalReflectionFileGenerator(); private void processCommand(CommandLineParser<CommandInvocation> parser, Writer w); private void parseCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); private void appendOptions(Writer w); private void appendDefaults(Writer w); private void appendCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); } class GraalReflectionFileGeneratorTest { @Test public void testSimpleCommand() throws IOException {
GraalReflectionFileGenerator generator = new GraalReflectionFileGenerator(); CommandLineParser<CommandInvocation> parser = getParser(TestCommand1.class); StringWriter writer = new StringWriter(); generator.generateReflection(parser, writer); assertEquals(readFile("src/test/resources/graal1"), writer.toString()); } }
2280644_7
class GraalReflectionFileGenerator { public void generateReflection(CommandLineParser<CommandInvocation> parser, Writer w) throws IOException { w.append('[').append(getLineSeparator()); processCommand(parser, w); appendOptions(w); w.append(getLineSeparator()).append("]"); } public GraalReflectionFileGenerator(); private void processCommand(CommandLineParser<CommandInvocation> parser, Writer w); private void parseCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); private void appendOptions(Writer w); private void appendDefaults(Writer w); private void appendCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); } class GraalReflectionFileGeneratorTest { @Test public void testCommand() throws IOException {
GraalReflectionFileGenerator generator = new GraalReflectionFileGenerator(); CommandLineParser<CommandInvocation> parser = getParser(TestCommand2.class); StringWriter writer = new StringWriter(); generator.generateReflection(parser, writer); assertEquals(readFile("src/test/resources/graal2"), writer.toString()); } }
2280644_8
class GraalReflectionFileGenerator { public void generateReflection(CommandLineParser<CommandInvocation> parser, Writer w) throws IOException { w.append('[').append(getLineSeparator()); processCommand(parser, w); appendOptions(w); w.append(getLineSeparator()).append("]"); } public GraalReflectionFileGenerator(); private void processCommand(CommandLineParser<CommandInvocation> parser, Writer w); private void parseCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); private void appendOptions(Writer w); private void appendDefaults(Writer w); private void appendCommand(ProcessedCommand<Command<CommandInvocation>, CommandInvocation> command, Writer w); } class GraalReflectionFileGeneratorTest { @Test public void testCommandWithFileOption() throws IOException {
GraalReflectionFileGenerator generator = new GraalReflectionFileGenerator(); CommandLineParser<CommandInvocation> parser = getParser(TestCommand3.class); StringWriter writer = new StringWriter(); generator.generateReflection(parser, writer); assertEquals(readFile("src/test/resources/graal3"), writer.toString()); } }
2827764_0
class App { public String getMessage() { return message; } public App(); public App(String message); public static void main(String[] args); public void setMessage(String message); public void run(); protected void readMessageFromFile(String file); private static final Logger LOG; private App app; } class AppTest { private static final Logger LOG; private App app; @Test public void testDefaultMessage() {
String message = app.getMessage(); assertEquals("Hello, world!", message); LOG.debug(message); } }
3052688_0
class DateUtils { public static Date yearStart() { final GregorianCalendar calendar = new GregorianCalendar(US); calendar.set(DAY_OF_YEAR, 1); return calendar.getTime(); } public static Date today(); public static Date yesterday(); public static Date addDays(final int days, final Calendar from); public static Date addDays(final int days, final Date from); public static Date addDays(final int days, final long from); public static Date addMonths(final int months, final Calendar from); public static Date addMonths(final int months, final Date from); public static Date addMonths(final int months, final long from); public static Date addYears(final int years, final Calendar from); public static Date addYears(final int years, final Date from); public static Date addYears(final int years, final long from); public static Date addWeeks(final int weeks, final Calendar from); public static Date addWeeks(final int weeks, final Date from); public static Date addWeeks(final int weeks, final long from); public static Date yearEnd(); } class DateUtilsTest { @Test public void yearStart() {
Date date = DateUtils.yearStart(); assertNotNull(date); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); assertEquals(1, calendar.get(DAY_OF_YEAR)); } }
3052688_1
class DateUtils { public static Date yearEnd() { final GregorianCalendar calendar = new GregorianCalendar(US); calendar.add(YEAR, 1); calendar.set(DAY_OF_YEAR, 1); calendar.add(DAY_OF_YEAR, -1); return calendar.getTime(); } public static Date today(); public static Date yesterday(); public static Date addDays(final int days, final Calendar from); public static Date addDays(final int days, final Date from); public static Date addDays(final int days, final long from); public static Date addMonths(final int months, final Calendar from); public static Date addMonths(final int months, final Date from); public static Date addMonths(final int months, final long from); public static Date addYears(final int years, final Calendar from); public static Date addYears(final int years, final Date from); public static Date addYears(final int years, final long from); public static Date addWeeks(final int weeks, final Calendar from); public static Date addWeeks(final int weeks, final Date from); public static Date addWeeks(final int weeks, final long from); public static Date yearStart(); } class DateUtilsTest { @Test public void yearEnd() {
Date date = DateUtils.yearEnd(); assertNotNull(date); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); assertEquals(11, calendar.get(MONTH)); assertEquals(31, calendar.get(DAY_OF_MONTH)); } }
4269155_0
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public void removeValue(String name) { request.setVariable(name, null); } public EnvironmentScopeExtractor(Environment request); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public Object getValue(String key); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @Test public void testRemoveValue() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateModel valueModel = createMock(TemplateModel.class); Configuration configuration = createMock(Configuration.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(model.get("key")).andReturn(null); expect(template.getConfiguration()).andReturn(configuration); expect(configuration.getSharedVariable("key")).andReturn(null); replay(template, model, valueModel, configuration); Environment env = new Environment(template, model, writer); env.setVariable("key", valueModel); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); extractor.removeValue("key"); assertNull(env.getVariable("key")); verify(template, model, valueModel, configuration); } }
4269155_1
class EnvironmentScopeExtractor implements AttributeExtractor { @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys() { try { return Collections.<String> enumeration(request.getKnownVariableNames()); } catch (TemplateModelException e) { throw new FreemarkerRequestException("Cannot iterate variable names correctly", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @Override public Object getValue(String key); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @Test public void testGetKeys() {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateModel valueModel = createMock(TemplateModel.class); Configuration configuration = createMock(Configuration.class); Set<String> names = new HashSet<String>(); names.add("testGetKeys"); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(template.getConfiguration()).andReturn(configuration); expect(configuration.getSharedVariableNames()).andReturn(names); replay(template, model, valueModel, configuration); Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); Enumeration<String> keys = extractor.getKeys(); assertEquals("testGetKeys", keys.nextElement()); assertFalse(keys.hasMoreElements()); verify(template, model, valueModel, configuration); } }
4269155_2
class EnvironmentScopeExtractor implements AttributeExtractor { @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys() { try { return Collections.<String> enumeration(request.getKnownVariableNames()); } catch (TemplateModelException e) { throw new FreemarkerRequestException("Cannot iterate variable names correctly", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @Override public Object getValue(String key); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @SuppressWarnings("unchecked") @Test(expected = FreemarkerRequestException.class) public void testGetKeysException() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModelEx model = createMock(TemplateHashModelEx.class); TemplateModel valueModel = createMock(TemplateModel.class); Configuration configuration = createMock(Configuration.class); Set<String> names = createMock(Set.class); Iterator<String> namesIt = createMock(Iterator.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(model.keys()).andThrow(new TemplateModelException()); expect(template.getConfiguration()).andReturn(configuration); expect(configuration.getSharedVariableNames()).andReturn(names); replay(template, model, valueModel, configuration, names, namesIt); try { Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); extractor.getKeys(); } finally { verify(template, model, valueModel, configuration, names, namesIt); } } }
4269155_3
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public Object getValue(String key) { try { TemplateModel variable = request.getVariable(key); if (variable != null) { return DeepUnwrap.unwrap(variable); } return null; } catch (TemplateModelException e) { throw new FreemarkerRequestException("Cannot get attribute with name '" + key + "'", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @Test public void testGetValue() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateScalarModel valueModel = createMock(TemplateScalarModel.class); Configuration configuration = createMock(Configuration.class); ObjectWrapper objectWrapper = createMock(ObjectWrapper.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(valueModel.getAsString()).andReturn("value"); replay(template, model, valueModel, configuration, objectWrapper); Environment env = new Environment(template, model, writer); env.setVariable("key", valueModel); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); assertEquals("value", extractor.getValue("key")); verify(template, model, valueModel, configuration, objectWrapper); } }
4269155_4
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public Object getValue(String key) { try { TemplateModel variable = request.getVariable(key); if (variable != null) { return DeepUnwrap.unwrap(variable); } return null; } catch (TemplateModelException e) { throw new FreemarkerRequestException("Cannot get attribute with name '" + key + "'", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @Test public void testGetValueNull() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateScalarModel valueModel = createMock(TemplateScalarModel.class); Configuration configuration = createMock(Configuration.class); ObjectWrapper objectWrapper = createMock(ObjectWrapper.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(model.get("key")).andReturn(null); expect(template.getConfiguration()).andReturn(configuration); expect(configuration.getSharedVariable("key")).andReturn(null); replay(template, model, valueModel, configuration, objectWrapper); Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); assertNull(extractor.getValue("key")); verify(template, model, valueModel, configuration, objectWrapper); } }
4269155_5
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public Object getValue(String key) { try { TemplateModel variable = request.getVariable(key); if (variable != null) { return DeepUnwrap.unwrap(variable); } return null; } catch (TemplateModelException e) { throw new FreemarkerRequestException("Cannot get attribute with name '" + key + "'", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public void setValue(String key, Object value); } class EnvironmentScopeExtractorTest { @Test(expected = FreemarkerRequestException.class) public void testGetValueException() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateScalarModel valueModel = createMock(TemplateScalarModel.class); Configuration configuration = createMock(Configuration.class); ObjectWrapper objectWrapper = createMock(ObjectWrapper.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(model.get("key")).andThrow(new TemplateModelException()); replay(template, model, valueModel, configuration, objectWrapper); try { Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); extractor.getValue("key"); } finally { verify(template, model, valueModel, configuration, objectWrapper); } } }
4269155_6
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public void setValue(String key, Object value) { try { TemplateModel model = request.getObjectWrapper().wrap(value); request.setVariable(key, model); } catch (TemplateModelException e) { throw new FreemarkerRequestException("Error when wrapping an object setting the '" + key + "' attribute", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public Object getValue(String key); } class EnvironmentScopeExtractorTest { @Test public void testSetValue() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateModel valueModel = createMock(TemplateModel.class); Configuration configuration = createMock(Configuration.class); ObjectWrapper objectWrapper = createMock(ObjectWrapper.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(template.getObjectWrapper()).andReturn(objectWrapper); expect(objectWrapper.wrap("value")).andReturn(valueModel); replay(template, model, valueModel, configuration, objectWrapper); Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); extractor.setValue("key", "value"); assertEquals(valueModel, env.getVariable("key")); verify(template, model, valueModel, configuration, objectWrapper); } }
4269155_7
class EnvironmentScopeExtractor implements AttributeExtractor { @Override public void setValue(String key, Object value) { try { TemplateModel model = request.getObjectWrapper().wrap(value); request.setVariable(key, model); } catch (TemplateModelException e) { throw new FreemarkerRequestException("Error when wrapping an object setting the '" + key + "' attribute", e); } } public EnvironmentScopeExtractor(Environment request); @Override public void removeValue(String name); @SuppressWarnings("unchecked") @Override public Enumeration<String> getKeys(); @Override public Object getValue(String key); } class EnvironmentScopeExtractorTest { @Test(expected = FreemarkerRequestException.class) public void testSetValueException() throws TemplateModelException {
Template template = createMock(Template.class); TemplateHashModel model = createMock(TemplateHashModel.class); TemplateModel valueModel = createMock(TemplateModel.class); Configuration configuration = createMock(Configuration.class); ObjectWrapper objectWrapper = createMock(ObjectWrapper.class); Writer writer = new StringWriter(); expect(template.getMacros()).andReturn(new HashMap<Object, Object>()); expect(template.getObjectWrapper()).andReturn(objectWrapper); expect(objectWrapper.wrap("value")).andThrow(new TemplateModelException()); replay(template, model, valueModel, configuration, objectWrapper); try { Environment env = new Environment(template, model, writer); EnvironmentScopeExtractor extractor = new EnvironmentScopeExtractor(env); extractor.setValue("key", "value"); assertEquals(valueModel, env.getVariable("key")); } finally { verify(template, model, valueModel, configuration, objectWrapper); } } }
5155211_3
class SensorDataSource { public void addSensorDataSink(SensorDataSink sink) { addSensorDataSink(sink, 1.0); } public SensorDataSource(); public SensorDataSource(SensorDataSink sink); public synchronized void addSensorDataSink(SensorDataSink sink, double weight); public synchronized void removeSensorDataSink(SensorDataSink sink); public synchronized void pushData(long timestamp, Object value); public synchronized void clearSensorDataSinks(); private SensorDataSource dataSrc; } class SensorDataSourceTest { private SensorDataSource dataSrc; @Test public void testSinkWeight() {
SensorDataSink ds0 = new SensorDataSink() { @Override public void onSensorData(long timestamp, Object value) { } }; SensorDataSink ds1 = new SensorDataSink() { @Override public void onSensorData(long timestamp, Object value) { } }; SensorDataSink ds2 = new SensorDataSink() { @Override public void onSensorData(long timestamp, Object value) { } }; SensorDataSink ds3 = new SensorDataSink() { @Override public void onSensorData(long timestamp, Object value) { } }; SensorDataSink ds4 = new SensorDataSink() { @Override public void onSensorData(long timestamp, Object value) { } }; dataSrc.addSensorDataSink(ds0, 0.0); dataSrc.addSensorDataSink(ds3); dataSrc.addSensorDataSink(ds4); dataSrc.addSensorDataSink(ds1, 0.0); dataSrc.addSensorDataSink(ds2, 0.1); assertEquals(ds0, dataSrc.sinkList.get(0)); assertEquals(ds1, dataSrc.sinkList.get(1)); assertEquals(ds2, dataSrc.sinkList.get(2)); assertEquals(ds3, dataSrc.sinkList.get(3)); assertEquals(ds4, dataSrc.sinkList.get(4)); } }
5155211_5
class ParameterService { public synchronized void setParam(Parameter param, Object value) { // check either param is registered if (getParam(param.getId()) != param) { throw new IllegalArgumentException(String.format("parameter provided with id %s is not the same as the registered one")); } try { if (recursionOn) { throw new IllegalStateException("recursion detected - parameter listeners are not allowed to modify parameters from within same thread"); } recursionOn = true; if (param.setParameterValue(value)) { onParamChanged(param); } } finally { recursionOn = false; } } public ParameterService(RoboStrokeEventBus bus); public synchronized void addListener(ParameterListenerRegistration ...value); public synchronized void removeListener(ParameterListenerRegistration ...value); public void addListeners(ParameterListenerOwner listenersOwner); public void removeListeners(ParameterListenerOwner listenersOwner); public synchronized void removeListener(String paramId, ParameterChangeListener listener); public synchronized void addListener(String paramId, ParameterChangeListener listener); public synchronized void registerParam(Parameter ... param); private void onParamChanged(Parameter param); public synchronized void setParam(String id, Object value); @SuppressWarnings("unchecked") public T getValue(String id); public Map<String, Parameter> getParamMap(); public synchronized Parameter getParam(String id); private static final ParameterInfo BOOLEAN_PARAM; private static final ParameterInfo INTEGER_PARAM; private static final ParameterInfo FLOAT_PARAM; Parameter f; Parameter i; Parameter b; private ParameterService ps; private final RoboStrokeEventBus bus; private final ParameterListenerRegistration[] listenerRegistration; private int intVal; } class ParameterServiceTest { private static final ParameterInfo BOOLEAN_PARAM; private static final ParameterInfo INTEGER_PARAM; private static final ParameterInfo FLOAT_PARAM; Parameter f; Parameter i; Parameter b; private ParameterService ps; private final RoboStrokeEventBus bus; private final ParameterListenerRegistration[] listenerRegistration; private int intVal; @Test public void testSetParam() {
assertEquals(.5f, (Float)f.getDefaultValue(), 0); ps.setParam("float", "0.7"); assertEquals(.7f, (Float)f.getValue(), 0); ps.setParam(f, 0.8f); assertEquals(.8f, (Float)f.getValue(), 0); } }
5155211_6
class ParameterService { public synchronized void setParam(Parameter param, Object value) { // check either param is registered if (getParam(param.getId()) != param) { throw new IllegalArgumentException(String.format("parameter provided with id %s is not the same as the registered one")); } try { if (recursionOn) { throw new IllegalStateException("recursion detected - parameter listeners are not allowed to modify parameters from within same thread"); } recursionOn = true; if (param.setParameterValue(value)) { onParamChanged(param); } } finally { recursionOn = false; } } public ParameterService(RoboStrokeEventBus bus); public synchronized void addListener(ParameterListenerRegistration ...value); public synchronized void removeListener(ParameterListenerRegistration ...value); public void addListeners(ParameterListenerOwner listenersOwner); public void removeListeners(ParameterListenerOwner listenersOwner); public synchronized void removeListener(String paramId, ParameterChangeListener listener); public synchronized void addListener(String paramId, ParameterChangeListener listener); public synchronized void registerParam(Parameter ... param); private void onParamChanged(Parameter param); public synchronized void setParam(String id, Object value); @SuppressWarnings("unchecked") public T getValue(String id); public Map<String, Parameter> getParamMap(); public synchronized Parameter getParam(String id); private static final ParameterInfo BOOLEAN_PARAM; private static final ParameterInfo INTEGER_PARAM; private static final ParameterInfo FLOAT_PARAM; Parameter f; Parameter i; Parameter b; private ParameterService ps; private final RoboStrokeEventBus bus; private final ParameterListenerRegistration[] listenerRegistration; private int intVal; } class ParameterServiceTest { private static final ParameterInfo BOOLEAN_PARAM; private static final ParameterInfo INTEGER_PARAM; private static final ParameterInfo FLOAT_PARAM; Parameter f; Parameter i; Parameter b; private ParameterService ps; private final RoboStrokeEventBus bus; private final ParameterListenerRegistration[] listenerRegistration; private int intVal; @Test public void testSetParamViaListener() {
ps.setParam("int", "7"); assertEquals(7, intVal); ps.setParam("int", "8"); assertEquals(8, intVal); } }
5518934_1
class GlacierUploaderOptionParser extends OptionParser { public String parseEndpointToRegion(String endpointOptionValue) { String region = endpointOptionValue; final Matcher matcher = REGION_REGEX_PATTERN.matcher(endpointOptionValue); if(matcher.matches()) { region = matcher.group("region"); LOG.debug("Endpoint parsed: {}", region); } return region; } public GlacierUploaderOptionParser(final Configuration config); public List<File> mergeNonOptionsFiles(List<File> optionsFiles, List<String> nonOptions); private ArgumentAcceptingOptionSpec<String> parseVault(final Configuration config); @Deprecated private ArgumentAcceptingOptionSpec<String> parseEndpoint(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseRegion(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseUploadFile(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseInventory(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseDownload(final Configuration config); @Deprecated private ArgumentAcceptingOptionSpec<File> parseCredentials(final Configuration config); private OptionSpec<Void> parseCreateVault(final Configuration config); private OptionSpec<Void> parseListVault(final Configuration config); private OptionSpec<Void> parseListJobs(final Configuration config); private OptionSpec<Void> parseDeleteVault(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseTargetFile(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseHashFile(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseDeleteArchive(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseMultipartUploadFile(final Configuration config); private ArgumentAcceptingOptionSpec<Long> parsePartSize(final Configuration config); private OptionSpecBuilder parseHelp(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseAbortUpload(final Configuration config); public static final String ENDPOINT_URL; private GlacierUploaderOptionParser optionsParser; private String[] args; } class GlacierUploaderOptionParserTest { public static final String ENDPOINT_URL; private GlacierUploaderOptionParser optionsParser; private String[] args; @Test public void canParseEndpointUrlToRegion() {
assertEquals("eu-west-1", optionsParser.parseEndpointToRegion(ENDPOINT_URL)); assertEquals("eu-central-2", optionsParser.parseEndpointToRegion("eu-central-2")); } }
5518934_2
class GlacierUploaderOptionParser extends OptionParser { public List<File> mergeNonOptionsFiles(List<File> optionsFiles, List<String> nonOptions) { final List<File> files = new ArrayList<>(optionsFiles); if (!nonOptions.isEmpty()) { // Adds non options to the list in order // to be able to use * in filenames for (String nonOption : nonOptions) { File file = new File(nonOption); if (file.exists() && file.isFile()) { files.add(file); } } } return files; } public GlacierUploaderOptionParser(final Configuration config); public String parseEndpointToRegion(String endpointOptionValue); private ArgumentAcceptingOptionSpec<String> parseVault(final Configuration config); @Deprecated private ArgumentAcceptingOptionSpec<String> parseEndpoint(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseRegion(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseUploadFile(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseInventory(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseDownload(final Configuration config); @Deprecated private ArgumentAcceptingOptionSpec<File> parseCredentials(final Configuration config); private OptionSpec<Void> parseCreateVault(final Configuration config); private OptionSpec<Void> parseListVault(final Configuration config); private OptionSpec<Void> parseListJobs(final Configuration config); private OptionSpec<Void> parseDeleteVault(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseTargetFile(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseHashFile(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseDeleteArchive(final Configuration config); private ArgumentAcceptingOptionSpec<File> parseMultipartUploadFile(final Configuration config); private ArgumentAcceptingOptionSpec<Long> parsePartSize(final Configuration config); private OptionSpecBuilder parseHelp(final Configuration config); private ArgumentAcceptingOptionSpec<String> parseAbortUpload(final Configuration config); public static final String ENDPOINT_URL; private GlacierUploaderOptionParser optionsParser; private String[] args; } class GlacierUploaderOptionParserTest { public static final String ENDPOINT_URL; private GlacierUploaderOptionParser optionsParser; private String[] args; @Test public void parsesFilesWithWhitespaceSuccessfully() throws IOException {
File tempFile = File.createTempFile("this is a test with whitespaces", ".txt"); tempFile.deleteOnExit(); System.out.println("Using temp file: " + tempFile.getAbsolutePath()); // use a dummy configuration final CompositeConfiguration dummyConfig = new CompositeConfiguration(); final OptionSet options = optionsParser.parse("-m", tempFile.getAbsolutePath()); final List<File> optionsFiles = options.valuesOf(optionsParser.multipartUpload); final List<String> nonOptions = options.nonOptionArguments(); Assert.assertEquals(1, optionsFiles.size()); Assert.assertEquals(0, nonOptions.size()); final List<File> files = optionsParser.mergeNonOptionsFiles(optionsFiles, nonOptions); Assert.assertEquals(tempFile.getName(), files.get(0).getName()); } }
5518934_3
class VaultInventoryPrinter { public String printArchiveSize(final JSONObject archive) throws JSONException { final BigDecimal size = archive.getBigDecimal("Size"); final String humanReadableSize = HumanReadableSize.parse(size); return size + " (" + humanReadableSize + ")"; } public VaultInventoryPrinter(); public VaultInventoryPrinter(final String inventory); public String getInventory(); public void setInventory(final String inventory); public void printInventory(final OutputStream out); private void printArchive(final PrintWriter o, final JSONObject archive); } class VaultInventoryPrinterTest { @Test public void test68GbLargeInventorySizeInteger() {
final JSONObject inventoryJson = new JSONObject("{\"Size\": 73476694570 }"); final VaultInventoryPrinter printer = new VaultInventoryPrinter(); final String readableSize = printer.printArchiveSize(inventoryJson); assertEquals("73476694570 (68.44GB)", readableSize); } }
5518934_4
class JobPrinter { public void printJob(GlacierJobDescription job, OutputStream o) { final PrintWriter out = new PrintWriter(o); out.println("Job ID:\t\t\t\t" + job.getJobId()); out.println("Creation date:\t\t\t" + job.getCreationDate()); if (job.getCompleted()) { out.println("Completion date:\t" + job.getCompletionDate()); } out.println("Status:\t\t\t\t" + job.getStatusCode() + (job.getStatusMessage() != null ? " (" + job.getStatusMessage() + ")" : "")); out.println(); out.flush(); } private static final String LINE_SEPARATOR; } class JobPrinterTest { private static final String LINE_SEPARATOR; @Test public void printJob() throws Exception {
final String jobId = UUID.randomUUID().toString(); final String statusMessage = UUID.randomUUID().toString(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final GlacierJobDescription job = new GlacierJobDescription(); job.setJobId(jobId); job.setCompleted(true); final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); job.setCompletionDate(dateFormat.format(new Date(0))); job.setStatusCode(StatusCode.Succeeded); job.setStatusMessage(statusMessage); new JobPrinter().printJob(job, out); assertEquals("Job ID:\t\t\t\t" + jobId + LINE_SEPARATOR + "Creation date:\t\t\tnull" + LINE_SEPARATOR + "Completion date:\t1970-01-01 00:00:00" + LINE_SEPARATOR + "Status:\t\t\t\tSucceeded (" + statusMessage + ")" + LINE_SEPARATOR + LINE_SEPARATOR, out.toString()); } }
5518934_5
class VaultPrinter { public void printVault(final DescribeVaultOutput output, OutputStream o) { final PrintWriter out = new PrintWriter(o); final String creationDate = output.getCreationDate(); final String lastInventoryDate = output.getLastInventoryDate(); final Long numberOfArchives = output.getNumberOfArchives(); final Long sizeInBytes = output.getSizeInBytes(); final String vaultARN = output.getVaultARN(); final String vaultName = output.getVaultName(); printVault(out, creationDate, lastInventoryDate, numberOfArchives, sizeInBytes, vaultARN, vaultName); } public void printVault(final DescribeVaultResult output, final OutputStream o); private void printVault(final PrintWriter out, final String creationDate, final String lastInventoryDate, final Long numberOfArchives, final Long sizeInBytes, final String vaultARN, final String vaultName); private static final String VAULT_NAME; private static final String ARN; private static final Long SIZE_IN_BYTES; private static final Long NUMBER_OF_ARCHIVES; private static final String INVENTORY_DATE; private static final String CREATION_DATE; } class VaultPrinterTest { private static final String VAULT_NAME; private static final String ARN; private static final Long SIZE_IN_BYTES; private static final Long NUMBER_OF_ARCHIVES; private static final String INVENTORY_DATE; private static final String CREATION_DATE; @Test public void testPrintVaultOutput() {
final String linebreak = System.getProperty("line.separator"); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final DescribeVaultOutput describeVaultResult = new DescribeVaultOutput(); describeVaultResult.setCreationDate(CREATION_DATE); describeVaultResult.setLastInventoryDate(INVENTORY_DATE); describeVaultResult.setNumberOfArchives(NUMBER_OF_ARCHIVES); describeVaultResult.setSizeInBytes(SIZE_IN_BYTES); describeVaultResult.setVaultARN(ARN); describeVaultResult.setVaultName(VAULT_NAME); new VaultPrinter().printVault(describeVaultResult, out); assertEquals("CreationDate:\t" + CREATION_DATE + linebreak + "LastInventoryDate:\t" + INVENTORY_DATE + linebreak + "NumberOfArchives:\t" + NUMBER_OF_ARCHIVES + linebreak + "SizeInBytes:\t\t" + SIZE_IN_BYTES + linebreak + "VaultARN:\t\t" + ARN + linebreak + "VaultName:\t\t" + VAULT_NAME + linebreak, out.toString()); } }
5518934_6
class VaultPrinter { public void printVault(final DescribeVaultOutput output, OutputStream o) { final PrintWriter out = new PrintWriter(o); final String creationDate = output.getCreationDate(); final String lastInventoryDate = output.getLastInventoryDate(); final Long numberOfArchives = output.getNumberOfArchives(); final Long sizeInBytes = output.getSizeInBytes(); final String vaultARN = output.getVaultARN(); final String vaultName = output.getVaultName(); printVault(out, creationDate, lastInventoryDate, numberOfArchives, sizeInBytes, vaultARN, vaultName); } public void printVault(final DescribeVaultResult output, final OutputStream o); private void printVault(final PrintWriter out, final String creationDate, final String lastInventoryDate, final Long numberOfArchives, final Long sizeInBytes, final String vaultARN, final String vaultName); private static final String VAULT_NAME; private static final String ARN; private static final Long SIZE_IN_BYTES; private static final Long NUMBER_OF_ARCHIVES; private static final String INVENTORY_DATE; private static final String CREATION_DATE; } class VaultPrinterTest { private static final String VAULT_NAME; private static final String ARN; private static final Long SIZE_IN_BYTES; private static final Long NUMBER_OF_ARCHIVES; private static final String INVENTORY_DATE; private static final String CREATION_DATE; @Test public void testPrintVaultResult() {
final String linebreak = System.getProperty("line.separator"); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final DescribeVaultResult describeVaultResult = new DescribeVaultResult(); describeVaultResult.setCreationDate(CREATION_DATE); describeVaultResult.setLastInventoryDate(INVENTORY_DATE); describeVaultResult.setNumberOfArchives(NUMBER_OF_ARCHIVES); describeVaultResult.setSizeInBytes(SIZE_IN_BYTES); describeVaultResult.setVaultARN(ARN); describeVaultResult.setVaultName(VAULT_NAME); new VaultPrinter().printVault(describeVaultResult, out); assertEquals("CreationDate:\t" + CREATION_DATE + linebreak + "LastInventoryDate:\t" + INVENTORY_DATE + linebreak + "NumberOfArchives:\t" + NUMBER_OF_ARCHIVES + linebreak + "SizeInBytes:\t\t" + SIZE_IN_BYTES + linebreak + "VaultARN:\t\t" + ARN + linebreak + "VaultName:\t\t" + VAULT_NAME + linebreak, out.toString()); } }
5518934_7
class HumanReadableSize { public static String[] sanitize(final String size) { LOG.debug("Sanitizing '{}'", size); final Pattern patternClass = Pattern.compile("([0-9.]+)\\s*?([kMGTP]?B)"); final Matcher m = patternClass.matcher(size); String[] s = new String[]{size, "B"}; if (m.find()) { final String pureSize = m.group(1); final String sizeClass = m.group(2); s = new String[]{pureSize, sizeClass}; } if(LOG.isDebugEnabled()) { LOG.debug("Sanitized: {}", Arrays.deepToString(s)); } return s; } private HumanReadableSize(); public static String parse(final BigDecimal size); public static String parse(final Long size); public static String parse(final Integer size); public static String parse(final String size); private static String getLargerSizeClass(final String oldSizeClass); private static String round(final BigDecimal unrounded, final int precision, final int roundingMode); } class HumanReadableSizeTest { @Test public void sanitizeMissingSizeIndicator() {
assertArrayEquals(new String[]{"123456789", "B"}, HumanReadableSize.sanitize("123456789")); } }
5518934_8
class HumanReadableSize { public static String[] sanitize(final String size) { LOG.debug("Sanitizing '{}'", size); final Pattern patternClass = Pattern.compile("([0-9.]+)\\s*?([kMGTP]?B)"); final Matcher m = patternClass.matcher(size); String[] s = new String[]{size, "B"}; if (m.find()) { final String pureSize = m.group(1); final String sizeClass = m.group(2); s = new String[]{pureSize, sizeClass}; } if(LOG.isDebugEnabled()) { LOG.debug("Sanitized: {}", Arrays.deepToString(s)); } return s; } private HumanReadableSize(); public static String parse(final BigDecimal size); public static String parse(final Long size); public static String parse(final Integer size); public static String parse(final String size); private static String getLargerSizeClass(final String oldSizeClass); private static String round(final BigDecimal unrounded, final int precision, final int roundingMode); } class HumanReadableSizeTest { @Test public void sanitizeBytes() {
assertArrayEquals(new String[]{"123456789", "B"}, HumanReadableSize.sanitize("123456789 B")); } }
5518934_9
class HumanReadableSize { public static String[] sanitize(final String size) { LOG.debug("Sanitizing '{}'", size); final Pattern patternClass = Pattern.compile("([0-9.]+)\\s*?([kMGTP]?B)"); final Matcher m = patternClass.matcher(size); String[] s = new String[]{size, "B"}; if (m.find()) { final String pureSize = m.group(1); final String sizeClass = m.group(2); s = new String[]{pureSize, sizeClass}; } if(LOG.isDebugEnabled()) { LOG.debug("Sanitized: {}", Arrays.deepToString(s)); } return s; } private HumanReadableSize(); public static String parse(final BigDecimal size); public static String parse(final Long size); public static String parse(final Integer size); public static String parse(final String size); private static String getLargerSizeClass(final String oldSizeClass); private static String round(final BigDecimal unrounded, final int precision, final int roundingMode); } class HumanReadableSizeTest { @Test public void sanitizeKilobytes() {
assertArrayEquals(new String[]{"123456789", "kB"}, HumanReadableSize.sanitize("123456789kB")); } }
7292204_0
class Util { public static <T> List<T> reverse(List<T> src) { List<T> copy = new ArrayList<T>(src); Collections.reverse(copy); return copy; } private Util(); @SuppressWarnings("unchecked") public static T[] reverse(T[] array); public static String expandUserHome(String text); private static String getUserHome(); public static String fixBackslashesToSlashes(String path); public static String fixSpacesToPercentTwenty(String path); public static T ignoreAndReturnNull(); public static void ignore(); public static boolean isFeatureDisabled(Method method, DisableableFeature feature); private static boolean isFeatureDisabled(DisableableFeature feature, DisableFeature annotation); public static UnsupportedOperationException unsupported(Throwable cause, String msg, Object... args); public static UnsupportedOperationException unsupported(String msg, Object... args); public static T unreachableButCompilerNeedsThis(); public static String asString(Object result); public static long now(); public static File fileFromURI(URI uri); public static File fileFromURI(String uriSpec); public static boolean eq(Object o1, Object o2); public static SystemProvider system(); public static void save(File target, Properties p); private static boolean isWindows(); public static void delete(File target); private static void store(File target, Properties p); private static void store(OutputStream out, Properties p); public static void saveJar(File target, String entryName, Properties props); private static void rename(File source, File target); private static void storeJar(File target, String entryName, Properties props); private static byte[] toBytes(Properties props); public static T newInstance(Class<T> clazz); public static List<T> newInstance(Class<? extends T>[] classes, List<T> result); } class UtilTest { @Test public void testReverse() {
Integer[] i = {1, 2, 3, 4, 5}; Integer[] result = Util.reverse(i); assertTrue(Arrays.equals(new Integer[] {1, 2, 3, 4, 5}, i)); assertTrue(Arrays.equals(new Integer[] {5, 4, 3, 2, 1}, result)); } }
7292204_4
class Util { public static String expandUserHome(String text) { if (text.equals("~")) return getUserHome(); if (text.indexOf("~/") == 0 || text.indexOf("file:~/") == 0 || text.indexOf("jar:file:~/") == 0) return text.replaceFirst("~/", Matcher.quoteReplacement(getUserHome()) + "/"); if (text.indexOf("~\\") == 0 || text.indexOf("file:~\\") == 0 || text.indexOf("jar:file:~\\") == 0) return text.replaceFirst("~\\\\", Matcher.quoteReplacement(getUserHome()) + "\\\\"); return text; } private Util(); public static List<T> reverse(List<T> src); @SuppressWarnings("unchecked") public static T[] reverse(T[] array); private static String getUserHome(); public static String fixBackslashesToSlashes(String path); public static String fixSpacesToPercentTwenty(String path); public static T ignoreAndReturnNull(); public static void ignore(); public static boolean isFeatureDisabled(Method method, DisableableFeature feature); private static boolean isFeatureDisabled(DisableableFeature feature, DisableFeature annotation); public static UnsupportedOperationException unsupported(Throwable cause, String msg, Object... args); public static UnsupportedOperationException unsupported(String msg, Object... args); public static T unreachableButCompilerNeedsThis(); public static String asString(Object result); public static long now(); public static File fileFromURI(URI uri); public static File fileFromURI(String uriSpec); public static boolean eq(Object o1, Object o2); public static SystemProvider system(); public static void save(File target, Properties p); private static boolean isWindows(); public static void delete(File target); private static void store(File target, Properties p); private static void store(OutputStream out, Properties p); public static void saveJar(File target, String entryName, Properties props); private static void rename(File source, File target); private static void storeJar(File target, String entryName, Properties props); private static byte[] toBytes(Properties props); public static T newInstance(Class<T> clazz); public static List<T> newInstance(Class<? extends T>[] classes, List<T> result); } class UtilTest { @Test public void testExpandUserHomeOnUnix() {
SystemProvider save = UtilTest.setSystem(new SystemProviderForTest( new Properties() {{ setProperty("user.home", "/home/john"); }}, new HashMap<String, String>() )); try { assertEquals("/home/john", Util.expandUserHome("~")); assertEquals("/home/john/foo/bar/", Util.expandUserHome("~/foo/bar/")); assertEquals("file:/home/john/foo/bar/", Util.expandUserHome("file:~/foo/bar/")); assertEquals("jar:file:/home/john/foo/bar/", Util.expandUserHome("jar:file:~/foo/bar/")); assertEquals("/home/john\\foo\\bar\\", Util.expandUserHome("~\\foo\\bar\\")); assertEquals("file:/home/john\\foo\\bar\\", Util.expandUserHome("file:~\\foo\\bar\\")); assertEquals("jar:file:/home/john\\foo\\bar\\", Util.expandUserHome("jar:file:~\\foo\\bar\\")); } finally { UtilTest.setSystem(save); } } }
7292204_5
class Util { public static String expandUserHome(String text) { if (text.equals("~")) return getUserHome(); if (text.indexOf("~/") == 0 || text.indexOf("file:~/") == 0 || text.indexOf("jar:file:~/") == 0) return text.replaceFirst("~/", Matcher.quoteReplacement(getUserHome()) + "/"); if (text.indexOf("~\\") == 0 || text.indexOf("file:~\\") == 0 || text.indexOf("jar:file:~\\") == 0) return text.replaceFirst("~\\\\", Matcher.quoteReplacement(getUserHome()) + "\\\\"); return text; } private Util(); public static List<T> reverse(List<T> src); @SuppressWarnings("unchecked") public static T[] reverse(T[] array); private static String getUserHome(); public static String fixBackslashesToSlashes(String path); public static String fixSpacesToPercentTwenty(String path); public static T ignoreAndReturnNull(); public static void ignore(); public static boolean isFeatureDisabled(Method method, DisableableFeature feature); private static boolean isFeatureDisabled(DisableableFeature feature, DisableFeature annotation); public static UnsupportedOperationException unsupported(Throwable cause, String msg, Object... args); public static UnsupportedOperationException unsupported(String msg, Object... args); public static T unreachableButCompilerNeedsThis(); public static String asString(Object result); public static long now(); public static File fileFromURI(URI uri); public static File fileFromURI(String uriSpec); public static boolean eq(Object o1, Object o2); public static SystemProvider system(); public static void save(File target, Properties p); private static boolean isWindows(); public static void delete(File target); private static void store(File target, Properties p); private static void store(OutputStream out, Properties p); public static void saveJar(File target, String entryName, Properties props); private static void rename(File source, File target); private static void storeJar(File target, String entryName, Properties props); private static byte[] toBytes(Properties props); public static T newInstance(Class<T> clazz); public static List<T> newInstance(Class<? extends T>[] classes, List<T> result); } class UtilTest { @Test public void testExpandUserHomeOnWindows() {
SystemProvider save = UtilTest.setSystem(new SystemProviderForTest( new Properties() {{ setProperty("user.home", "C:\\Users\\John"); }}, new HashMap<String, String>() )); try { assertEquals("C:\\Users\\John", Util.expandUserHome("~")); assertEquals("C:\\Users\\John/foo/bar/", Util.expandUserHome("~/foo/bar/")); assertEquals("file:C:\\Users\\John/foo/bar/", Util.expandUserHome("file:~/foo/bar/")); assertEquals("jar:file:C:\\Users\\John/foo/bar/", Util.expandUserHome("jar:file:~/foo/bar/")); assertEquals("C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("~\\foo\\bar\\")); assertEquals("file:C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("file:~\\foo\\bar\\")); assertEquals("jar:file:C:\\Users\\John\\foo\\bar\\", Util.expandUserHome("jar:file:~\\foo\\bar\\")); } finally { UtilTest.setSystem(save); } } }
7292204_6
class Base64 { public static String encode(byte[] data) { if (encoderMethod == null) throw new UnsupportedOperationException("Cannot find Base64 encoder."); try { return (String) encoderMethod.invoke(encoderObject, data); } catch (Exception e) { throw new UnsupportedOperationException(e); } } private Base64(); private static void reset(); public static byte[] decode(String data); } class Base64Test { @Test public void testEncode() {
String input = "Hello World!"; String result = Base64.encode(input.getBytes()); assertEquals("SGVsbG8gV29ybGQh", result); } }
7292204_7
class Base64 { public static byte[] decode(String data) { if (decoderMethod == null) throw new UnsupportedOperationException("Cannot find Base64 decoder."); try { return (byte[]) decoderMethod.invoke(decoderObject, data); } catch (Exception e) { throw new UnsupportedOperationException(e); } } private Base64(); private static void reset(); public static String encode(byte[] data); } class Base64Test { @Test public void testDecode() throws Exception {
String input = "SGVsbG8gV29ybGQh"; byte[] result = Base64.decode(input); assertEquals("Hello World!", new String(result)); } }
7292204_8
class Reflection { public static boolean isClassAvailable(String className) { return forName(className) != null; } private Reflection(); public static Class<?> forName(String className); private static Java8Support getJava8Support(); private static Java8Support java8NotSupported(); public static boolean isDefault(Method method); public static Object invokeDefaultMethod(Object proxy, Method method, Object[] args); } class ReflectionTest { @Test public void testAvailableWithNonExistentClass() {
boolean available = Reflection.isClassAvailable("foo.bar.baz.FooBar"); assertFalse(available); } }
7292204_9
class Reflection { public static boolean isClassAvailable(String className) { return forName(className) != null; } private Reflection(); public static Class<?> forName(String className); private static Java8Support getJava8Support(); private static Java8Support java8NotSupported(); public static boolean isDefault(Method method); public static Object invokeDefaultMethod(Object proxy, Method method, Object[] args); } class ReflectionTest { @Test public void testAvailableWithExistentClass(){
boolean available = Reflection.isClassAvailable("java.lang.String"); assertTrue(available); } }
8103494_1
class TeamCityRestRequest { public Build fetchBuildStatus(int buildId) throws IOException { String urlEndpoint = buildServerUrl + PATH_BUILD + Integer.toString(buildId); JsonElement json = RestRequest.fetchJson(username, password, urlEndpoint); System.out.println("Rest Response: " + json.toString()); Gson gson = new Gson(); return gson.fromJson(json, Build.class); } @SuppressWarnings("unused") private TeamCityRestRequest(); public TeamCityRestRequest(String buildServerUrl, String buildServerUsername, String buildServerPassword); private MavenGithub github; } class TeamCityRestRequestTest { private MavenGithub github; @Test public void testRestRequestSuccess() throws IOException {
String serverUrl = "http://teamcity.gonevertical.org"; String username = github.getUsername(); String password = github.getPassword(); int buildId = 299; TeamCityRestRequest rest = new TeamCityRestRequest(serverUrl, username, password); Build build = rest.fetchBuildStatus(buildId); Assert.assertNotNull(build); Assert.assertTrue(build.getStatus().contains("SUCC")); } }
8103494_2
class TeamCityRestRequest { public Build fetchBuildStatus(int buildId) throws IOException { String urlEndpoint = buildServerUrl + PATH_BUILD + Integer.toString(buildId); JsonElement json = RestRequest.fetchJson(username, password, urlEndpoint); System.out.println("Rest Response: " + json.toString()); Gson gson = new Gson(); return gson.fromJson(json, Build.class); } @SuppressWarnings("unused") private TeamCityRestRequest(); public TeamCityRestRequest(String buildServerUrl, String buildServerUsername, String buildServerPassword); private MavenGithub github; } class TeamCityRestRequestTest { private MavenGithub github; @Test public void testRestRequestFailure() throws IOException {
String serverUrl = "http://teamcity.gonevertical.org"; String username = github.getUsername(); String password = github.getPassword(); int buildId = 490; TeamCityRestRequest rest = new TeamCityRestRequest(serverUrl, username, password); Build build = rest.fetchBuildStatus(buildId); Assert.assertNotNull(build); Assert.assertTrue(build.getStatus().contains("FAIL")); } }
8103494_7
class PullNotification { public static void main(String[] args) { PullNotification.newInstance(args).run(); } private PullNotification(); private PullNotification(String[] args); private static PullNotification newInstance(String[] args); private void parameterParser(String[] args); private void displayHelp(); private String parameterParser(String param); private void run(); private void autoCheckAndChangeGitPullStatus(int buildId); private void changeStatus(String buildStatus); private void addCommitMessage(); private void changeStatus(CommitStatus status); private Repository getRepository(); private void loginToGitHub(); } class PullNotificationTest { @Test public void testOptionalFail() {
String[] args = new String[8]; args[0] = "-ro=branflake2267"; args[1] = "-rn=Sandbox"; args[2] = "-sha=2e84e6446df300cd572930869c5ed2be8ee1f614"; args[3] = "-github=github"; args[4] = "-teamcity=teamcity-gonevertical"; args[5] = "-returnurl=http://teamcity.gonevertical.org"; args[6] = "-status=failed"; args[7] = "-skipcomment=true"; PullNotification.main(args); } }
8121707_0
class TypeParameter { @Override public String toString() { return new TypeParameterRenderer().render(this, null); } public TypeParameter(String name); public TypeParameter(String name, List<FullyQualifiedJavaType> extendsTypes); public String getName(); public List<FullyQualifiedJavaType> getExtendsTypes(); } class TypeParameterTest { @Test public void testToString() {
FullyQualifiedJavaType list = FullyQualifiedJavaType.getNewListInstance(); FullyQualifiedJavaType compare = new FullyQualifiedJavaType("java.util.Comparator"); TypeParameter typeParameter = new TypeParameter("T", Arrays.asList(list, compare)); assertNotNull(typeParameter); assertEquals("T extends List & Comparator", typeParameter.toString()); } }
8121707_1
class Interface extends InnerInterface implements CompilationUnit { @Override public void addImportedType(FullyQualifiedJavaType importedType) { if (importedType.isExplicitlyImported() && !importedType.getPackageName().equals(getType().getPackageName())) { importedTypes.add(importedType); } } public Interface(FullyQualifiedJavaType type); public Interface(String type); @Override public Set<FullyQualifiedJavaType> getImportedTypes(); @Override public void addFileCommentLine(String commentLine); @Override public List<String> getFileCommentLines(); @Override public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes); @Override public Set<String> getStaticImports(); @Override public void addStaticImport(String staticImport); @Override public void addStaticImports(Set<String> staticImports); @Override public R accept(CompilationUnitVisitor<R> visitor); } class InterfaceTest { @Test public void testAddImportedType() {
Interface interfaze = new Interface("com.foo.UserInterface"); FullyQualifiedJavaType arrayList = FullyQualifiedJavaType.getNewArrayListInstance(); interfaze.addImportedType(arrayList); assertNotNull(interfaze.getImportedTypes()); assertEquals(1, interfaze.getImportedTypes().size()); assertTrue(interfaze.getImportedTypes().contains(arrayList)); } }
8121707_2
class Interface extends InnerInterface implements CompilationUnit { @Override public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes) { this.importedTypes.addAll(importedTypes); } public Interface(FullyQualifiedJavaType type); public Interface(String type); @Override public Set<FullyQualifiedJavaType> getImportedTypes(); @Override public void addImportedType(FullyQualifiedJavaType importedType); @Override public void addFileCommentLine(String commentLine); @Override public List<String> getFileCommentLines(); @Override public Set<String> getStaticImports(); @Override public void addStaticImport(String staticImport); @Override public void addStaticImports(Set<String> staticImports); @Override public R accept(CompilationUnitVisitor<R> visitor); } class InterfaceTest { @Test public void testAddImportedTypes() {
Interface interfaze = new Interface("com.foo.UserInterface"); Set<FullyQualifiedJavaType> importedTypes = new HashSet<>(); FullyQualifiedJavaType arrayList = FullyQualifiedJavaType.getNewArrayListInstance(); FullyQualifiedJavaType hashMap = FullyQualifiedJavaType.getNewHashMapInstance(); importedTypes.add(arrayList); importedTypes.add(hashMap); interfaze.addImportedTypes(importedTypes); assertNotNull(interfaze.getImportedTypes()); assertEquals(2, interfaze.getImportedTypes().size()); assertTrue(interfaze.getImportedTypes().contains(arrayList)); assertTrue(interfaze.getImportedTypes().contains(hashMap)); } }
8121707_3
class Interface extends InnerInterface implements CompilationUnit { @Override public void addFileCommentLine(String commentLine) { fileCommentLines.add(commentLine); } public Interface(FullyQualifiedJavaType type); public Interface(String type); @Override public Set<FullyQualifiedJavaType> getImportedTypes(); @Override public void addImportedType(FullyQualifiedJavaType importedType); @Override public List<String> getFileCommentLines(); @Override public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes); @Override public Set<String> getStaticImports(); @Override public void addStaticImport(String staticImport); @Override public void addStaticImports(Set<String> staticImports); @Override public R accept(CompilationUnitVisitor<R> visitor); } class InterfaceTest { @Test public void testAddFileCommentLine() {
Interface interfaze = new Interface("com.foo.UserInterface"); interfaze.addFileCommentLine("test"); assertNotNull(interfaze.getFileCommentLines()); assertEquals(1, interfaze.getFileCommentLines().size()); assertEquals("test", interfaze.getFileCommentLines().get(0)); } }
8121707_4
class Interface extends InnerInterface implements CompilationUnit { @Override public void addStaticImport(String staticImport) { staticImports.add(staticImport); } public Interface(FullyQualifiedJavaType type); public Interface(String type); @Override public Set<FullyQualifiedJavaType> getImportedTypes(); @Override public void addImportedType(FullyQualifiedJavaType importedType); @Override public void addFileCommentLine(String commentLine); @Override public List<String> getFileCommentLines(); @Override public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes); @Override public Set<String> getStaticImports(); @Override public void addStaticImports(Set<String> staticImports); @Override public R accept(CompilationUnitVisitor<R> visitor); } class InterfaceTest { @Test public void testAddStaticImport() {
Interface interfaze = new Interface("com.foo.UserInterface"); interfaze.addStaticImport("com.foo.StaticUtil"); assertNotNull(interfaze.getStaticImports()); assertEquals(1, interfaze.getStaticImports().size()); assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil")); } }
8121707_5
class Interface extends InnerInterface implements CompilationUnit { @Override public void addStaticImports(Set<String> staticImports) { this.staticImports.addAll(staticImports); } public Interface(FullyQualifiedJavaType type); public Interface(String type); @Override public Set<FullyQualifiedJavaType> getImportedTypes(); @Override public void addImportedType(FullyQualifiedJavaType importedType); @Override public void addFileCommentLine(String commentLine); @Override public List<String> getFileCommentLines(); @Override public void addImportedTypes(Set<FullyQualifiedJavaType> importedTypes); @Override public Set<String> getStaticImports(); @Override public void addStaticImport(String staticImport); @Override public R accept(CompilationUnitVisitor<R> visitor); } class InterfaceTest { @Test public void testAddStaticImports() {
Interface interfaze = new Interface("com.foo.UserInterface"); Set<String> staticImports = new HashSet<>(); staticImports.add("com.foo.StaticUtil1"); staticImports.add("com.foo.StaticUtil2"); interfaze.addStaticImports(staticImports); assertNotNull(interfaze.getStaticImports()); assertEquals(2, interfaze.getStaticImports().size()); assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil1")); assertTrue(interfaze.getStaticImports().contains("com.foo.StaticUtil2")); } }
8121707_6
class InnerClass extends AbstractJavaType { public void setSuperClass(FullyQualifiedJavaType superClass) { this.superClass = superClass; } public InnerClass(FullyQualifiedJavaType type); public InnerClass(String type); public Optional<FullyQualifiedJavaType> getSuperClass(); public void setSuperClass(String superClassType); public List<TypeParameter> getTypeParameters(); public void addTypeParameter(TypeParameter typeParameter); public List<InitializationBlock> getInitializationBlocks(); public void addInitializationBlock(InitializationBlock initializationBlock); public boolean isAbstract(); public void setAbstract(boolean isAbtract); public boolean isFinal(); public void setFinal(boolean isFinal); private static final String LF; } class InnerClassTest { private static final String LF; @Test public void testSetSuperClass() {
InnerClass clazz = new InnerClass("com.foo.UserClass"); assertFalse(clazz.getSuperClass().isPresent()); clazz.setSuperClass("com.hoge.SuperClass"); assertNotNull(clazz.getSuperClass()); assertEquals("com.hoge.SuperClass", clazz.getSuperClass().get().getFullyQualifiedName()); } }
8121707_7
class InnerClass extends AbstractJavaType { public void addTypeParameter(TypeParameter typeParameter) { this.typeParameters.add(typeParameter); } public InnerClass(FullyQualifiedJavaType type); public InnerClass(String type); public Optional<FullyQualifiedJavaType> getSuperClass(); public void setSuperClass(FullyQualifiedJavaType superClass); public void setSuperClass(String superClassType); public List<TypeParameter> getTypeParameters(); public List<InitializationBlock> getInitializationBlocks(); public void addInitializationBlock(InitializationBlock initializationBlock); public boolean isAbstract(); public void setAbstract(boolean isAbtract); public boolean isFinal(); public void setFinal(boolean isFinal); private static final String LF; } class InnerClassTest { private static final String LF; @Test public void testAddTypeParameter() {
InnerClass clazz = new InnerClass("com.foo.UserClass"); assertEquals(0, clazz.getTypeParameters().size()); clazz.addTypeParameter(new TypeParameter("T")); assertEquals(1, clazz.getTypeParameters().size()); clazz.addTypeParameter(new TypeParameter("U")); assertEquals(2, clazz.getTypeParameters().size()); } }
8121707_8
class InnerClass extends AbstractJavaType { public void addInitializationBlock(InitializationBlock initializationBlock) { initializationBlocks.add(initializationBlock); } public InnerClass(FullyQualifiedJavaType type); public InnerClass(String type); public Optional<FullyQualifiedJavaType> getSuperClass(); public void setSuperClass(FullyQualifiedJavaType superClass); public void setSuperClass(String superClassType); public List<TypeParameter> getTypeParameters(); public void addTypeParameter(TypeParameter typeParameter); public List<InitializationBlock> getInitializationBlocks(); public boolean isAbstract(); public void setAbstract(boolean isAbtract); public boolean isFinal(); public void setFinal(boolean isFinal); private static final String LF; } class InnerClassTest { private static final String LF; @Test public void testAddInitializationBlock() {
InnerClass clazz = new InnerClass("com.foo.UserClass"); assertEquals(0, clazz.getInitializationBlocks().size()); clazz.addInitializationBlock(new InitializationBlock(false)); assertEquals(1, clazz.getInitializationBlocks().size()); clazz.addInitializationBlock(new InitializationBlock(true)); assertEquals(2, clazz.getInitializationBlocks().size()); } }
8121707_9
class InnerClass extends AbstractJavaType { public void setAbstract(boolean isAbtract) { this.isAbstract = isAbtract; } public InnerClass(FullyQualifiedJavaType type); public InnerClass(String type); public Optional<FullyQualifiedJavaType> getSuperClass(); public void setSuperClass(FullyQualifiedJavaType superClass); public void setSuperClass(String superClassType); public List<TypeParameter> getTypeParameters(); public void addTypeParameter(TypeParameter typeParameter); public List<InitializationBlock> getInitializationBlocks(); public void addInitializationBlock(InitializationBlock initializationBlock); public boolean isAbstract(); public boolean isFinal(); public void setFinal(boolean isFinal); private static final String LF; } class InnerClassTest { private static final String LF; @Test public void testSetAbstract() {
InnerClass clazz = new InnerClass("com.foo.UserClass"); assertFalse(clazz.isAbstract()); clazz.setAbstract(true); assertTrue(clazz.isAbstract()); } }
854893_28
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptBooleans() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(true); channel.write(true); channel.write(true); channel.write(true); channel.write(false); channel.write(false); channel.write(false); channel.write(false); channel.write(false); verify(out).write((byte) 0xf0); verifyNoMoreInteractions(out); } }
854893_29
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptFullBytes() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(8, (byte) 32); verify(out).write((byte) 32); verifyNoMoreInteractions(out); } }
854893_30
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptPartialBytes() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(4, (byte) 0xff); // 1111 channel.write(4, (byte) 0x00); // 0000 verify(out).write((byte) 0xf0); verifyNoMoreInteractions(out); } }
854893_31
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldDealWithNonAlignedBytes() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(3, (byte) 0xff); // 111 channel.write(7, (byte) 0x00); // 0000000 verify(out).write((byte) Integer.parseInt("11100000", 2)); verifyNoMoreInteractions(out); } }
854893_32
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldDealWithNonAlignedMultipleBytes() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(3, (byte) 0xff); // 111 channel.write(7, (byte) 0x00); // 0000000 channel.write(8, (byte) 0xff); // 11111111 channel.write(6, (byte) 0x00); // 000000 verify(out).write((byte) Integer.parseInt("11100000", 2)); verify(out).write((byte) Integer.parseInt("00111111", 2)); verify(out).write((byte) Integer.parseInt("11000000", 2)); verifyNoMoreInteractions(out); } }
854893_33
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptInts() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(12, (int) 0xfff, ByteOrder.BigEndian); // 1111 1111 1111 channel.write(4, (int) 0x0, ByteOrder.BigEndian); // 0000 verify(out).write((byte) Integer.parseInt("11111111", 2)); verify(out).write((byte) Integer.parseInt("11110000", 2)); verifyNoMoreInteractions(out); } }
854893_34
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptIntsAndBytes() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(12, (int) 0xfff, ByteOrder.BigEndian); // 1111 1111 1111 channel.write(5, (byte) 0x0); // 0000 0 verify(out).write((byte) Integer.parseInt("11111111", 2)); verify(out).write((byte) Integer.parseInt("11110000", 2)); verifyNoMoreInteractions(out); } }
854893_35
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptLittleEndian() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(12, (int) 0xf00, ByteOrder.LittleEndian); // 1111 0000 0000 channel.write(4, (int) 0x0, ByteOrder.LittleEndian); // 0000 // What I expect: // 0000 0000 1111 0000 verify(out).write((byte) Integer.parseInt("00000000", 2)); verify(out).write((byte) Integer.parseInt("11110000", 2)); verifyNoMoreInteractions(out); } }
854893_36
class OutputStreamBitChannel implements BitChannel, Closeable { public void write(boolean value) throws IOException { if (value) { buffer = (byte) (0xff & ((buffer << 1) | 0x01)); } else { buffer = (byte) (0xff & (buffer << 1)); } if (++bitPos == 8) { bitPos = 0; out.write(buffer); buffer = 0; } } public OutputStreamBitChannel(@Nonnull OutputStream out); public void write(@Nonnegative int nrbits, byte value); public void write(@Nonnegative int nrbits, int value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, long value, ByteOrder byteOrder); public void write(@Nonnegative int nrbits, short value, ByteOrder byteOrder); public void write(@Nonnull byte[] src, int offset, int length); public long write(@Nonnull ByteBuffer buffer); public @Nonnegative int getRelativeBitPos(); public void close(); @Mock private OutputStream out; } class OutputStreamBitChannelTest { @Mock private OutputStream out; @Test public void shouldAcceptLongs() throws IOException {
OutputStreamBitChannel channel = new OutputStreamBitChannel(out); channel.write(12, Long.MAX_VALUE / 2, ByteOrder.BigEndian); // 1111 1111 1111 channel.write(5, (byte) 0x0); // 0000 0 verify(out).write((byte) Integer.parseInt("11111111", 2)); verify(out).write((byte) Integer.parseInt("11110000", 2)); verifyNoMoreInteractions(out); } }
854893_37
class BoundedBitChannel implements BitChannel { public void write(boolean value) throws IOException { if (written + 1 <= maxBits) { channel.write(value); written += 1; } else { throw new IOException(OVERRUN_MESSAGE); } } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public int getRelativeBitPos(); public void close(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldAccept9BitsAsInt() throws IOException {
boundedChannel.write(9, Integer.MAX_VALUE, ByteOrder.BigEndian); verify(channel).write(9, Integer.MAX_VALUE, ByteOrder.BigEndian); verifyNoMoreInteractions(channel); } }
854893_39
class BoundedBitChannel implements BitChannel { public void write(boolean value) throws IOException { if (written + 1 <= maxBits) { channel.write(value); written += 1; } else { throw new IOException(OVERRUN_MESSAGE); } } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public int getRelativeBitPos(); public void close(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldAccept9BitsAsLong() throws IOException {
boundedChannel.write(9, Long.MAX_VALUE, ByteOrder.BigEndian); verify(channel).write(9, Long.MAX_VALUE, ByteOrder.BigEndian); verifyNoMoreInteractions(channel); } }
854893_41
class BoundedBitChannel implements BitChannel { public void write(boolean value) throws IOException { if (written + 1 <= maxBits) { channel.write(value); written += 1; } else { throw new IOException(OVERRUN_MESSAGE); } } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public int getRelativeBitPos(); public void close(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldAccept9BitsAsShort() throws IOException {
boundedChannel.write(9, Short.MAX_VALUE, ByteOrder.BigEndian); verify(channel).write(9, Short.MAX_VALUE, ByteOrder.BigEndian); verifyNoMoreInteractions(channel); } }
854893_43
class BoundedBitChannel implements BitChannel { public void write(boolean value) throws IOException { if (written + 1 <= maxBits) { channel.write(value); written += 1; } else { throw new IOException(OVERRUN_MESSAGE); } } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public int getRelativeBitPos(); public void close(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldAccept9BitsAsBytesAccummulated() throws IOException {
boundedChannel.write(8, Byte.MAX_VALUE, ByteOrder.BigEndian); boundedChannel.write(1, Byte.MAX_VALUE, ByteOrder.BigEndian); verify(channel).write(8, Byte.MAX_VALUE, ByteOrder.BigEndian); verify(channel).write(1, Byte.MAX_VALUE, ByteOrder.BigEndian); verifyNoMoreInteractions(channel); } }
854893_45
class BoundedBitChannel implements BitChannel { public void close() throws IOException { channel.close(); } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(boolean value); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public int getRelativeBitPos(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldCloseCorrectly() throws IOException {
boundedChannel.close(); verify(channel).close(); } }
854893_46
class BoundedBitChannel implements BitChannel { public int getRelativeBitPos() { return channel.getRelativeBitPos(); } public BoundedBitChannel(@Nonnull BitChannel channel, @Nonnegative long maxBits); public void write(boolean value); public void write(int nrbits, byte value); public void write(int nrbits, int value, ByteOrder byteOrder); public void write(int nrbits, long value, ByteOrder byteOrder); public void write(int nrbits, short value, ByteOrder byteOrder); public void write(byte[] src, int offset, int length); public long write(ByteBuffer buffer); public void close(); private BitChannel channel; private BoundedBitChannel boundedChannel; } class BoundedBitChannelTest { private BitChannel channel; private BoundedBitChannel boundedChannel; @Test public void shouldReportRelativeBitPosCorrectly() throws IOException {
when(channel.getRelativeBitPos()).thenReturn(4); assertThat(boundedChannel.getRelativeBitPos(), is(4)); verify(channel).getRelativeBitPos(); } }
9198697_0
class CommandInvocation { public String[] args() { return Arrays.copyOf(args, args.length); } public CommandInvocation(final String command, final String... args); public String command(); } class CommandInvocationTest { @Test public void testArgsImmutability() throws Exception {
final CommandInvocation commandInvocation = new CommandInvocation("cmd", "a", "t"); commandInvocation.args()[1] = "b"; assertArrayEquals(new String[] { "a", "t" }, commandInvocation.args()); } }
9198697_1
class Call { @Override public boolean equals(final Object o) { return o instanceof Call && commandName.equals(((Call) o).commandName); } public Call(final String commandName, final Completer... completers); public static Call call(final String commandName, final Completer... completers); public String commandName(); public Completer[] completers(); @Override public int hashCode(); } class CallTest { @Test public void testEquals() throws Exception {
final Call call = call("cmd"); assertTrue(call.equals(call("cmd"))); } }
9198697_2
class Call { @Override public int hashCode() { return commandName.hashCode(); } public Call(final String commandName, final Completer... completers); public static Call call(final String commandName, final Completer... completers); public String commandName(); public Completer[] completers(); @Override public boolean equals(final Object o); } class CallTest { @Test public void testHashCode() throws Exception {
final Call call = call("cmd"); assertTrue(call.equals(call("cmd"))); assertTrue(call.hashCode() == call("cmd").hashCode()); } }
9198697_3
class HadoopREPL extends REPL { @Override protected void evaluate(final String input) throws ExitSignal { popHistory(); final Iterable<String> inputParts = ARG_SPLITTER.limit(2).split(input); if (Iterables.isEmpty(inputParts)) { // Do nothing } else { final String command = Iterables.get(inputParts, 0).toLowerCase(); if (commandMappings.containsKey(call(command))) { commandMappings.get(call(command)).execute( new CommandInvocation(command, Iterables.toArray(ARG_SPLITTER.split(Iterables.get(inputParts, 1, "")), String.class)), sessionState ); } else { sessionState.output("Unknown command \"%s\"", command); } pushHistory(input); } } public HadoopREPL(final Configuration configuration); public HadoopREPL(final Configuration configuration, final SessionState sessionState); public HadoopREPL(final Configuration configuration, final SessionState sessionState, final Map<Call, Command> commandMappings); protected Map<Call, Command> buildCommandMappings(); protected void resetCompletors(); protected SessionState sessionState(); protected Map<Call, Command> commandMappings(); public static void main(final String[] args); } class HadoopREPLTest { @Test public void testEvaluate() throws Exception {
final Configuration configuration = mock(Configuration.class); final SessionState sessionState = mock(SessionState.class); final HadoopREPL repl = new HadoopREPL(configuration, sessionState, ImmutableMap.<Call, Command>of( call("test"), new Command() { @Override public void execute(final CommandInvocation call, final SessionState ss) throws REPL.ExitSignal { assertEquals("test", call.command()); assertArrayEquals(new String[0], call.args()); assertEquals(sessionState, ss); } @Override public Usage usage(final SessionState sessionState) { return null; } } )); repl.evaluate("test"); assertEquals("test", Iterables.get(repl.history(), 0)); } }
9198697_4
class HadoopREPL extends REPL { @Override protected void evaluate(final String input) throws ExitSignal { popHistory(); final Iterable<String> inputParts = ARG_SPLITTER.limit(2).split(input); if (Iterables.isEmpty(inputParts)) { // Do nothing } else { final String command = Iterables.get(inputParts, 0).toLowerCase(); if (commandMappings.containsKey(call(command))) { commandMappings.get(call(command)).execute( new CommandInvocation(command, Iterables.toArray(ARG_SPLITTER.split(Iterables.get(inputParts, 1, "")), String.class)), sessionState ); } else { sessionState.output("Unknown command \"%s\"", command); } pushHistory(input); } } public HadoopREPL(final Configuration configuration); public HadoopREPL(final Configuration configuration, final SessionState sessionState); public HadoopREPL(final Configuration configuration, final SessionState sessionState, final Map<Call, Command> commandMappings); protected Map<Call, Command> buildCommandMappings(); protected void resetCompletors(); protected SessionState sessionState(); protected Map<Call, Command> commandMappings(); public static void main(final String[] args); } class HadoopREPLTest { @Test public void testEvaluateHelpWithUsage() throws Exception {
final Configuration configuration = new Configuration(); final SessionState sessionState = mock(SessionState.class); when(sessionState.configuration()).thenReturn(configuration); final HadoopREPL repl = new HadoopREPL(configuration, sessionState); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { assertEquals("Displaying help for \"save\"", String.format(invocationOnMock.getArguments()[0].toString(), invocationOnMock.getArguments()[1])); return null; } }).when(sessionState).output(anyString()); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { final Command.Usage usage = (Command.Usage) invocationOnMock.getArguments()[0]; assertEquals("save", usage.command); return null; } }).when(sessionState).outputUsage(any(Command.Usage.class)); repl.evaluate("help save"); assertEquals("help save", Iterables.get(repl.history(), 0)); } }
9198697_5
class HadoopREPL extends REPL { @Override protected void evaluate(final String input) throws ExitSignal { popHistory(); final Iterable<String> inputParts = ARG_SPLITTER.limit(2).split(input); if (Iterables.isEmpty(inputParts)) { // Do nothing } else { final String command = Iterables.get(inputParts, 0).toLowerCase(); if (commandMappings.containsKey(call(command))) { commandMappings.get(call(command)).execute( new CommandInvocation(command, Iterables.toArray(ARG_SPLITTER.split(Iterables.get(inputParts, 1, "")), String.class)), sessionState ); } else { sessionState.output("Unknown command \"%s\"", command); } pushHistory(input); } } public HadoopREPL(final Configuration configuration); public HadoopREPL(final Configuration configuration, final SessionState sessionState); public HadoopREPL(final Configuration configuration, final SessionState sessionState, final Map<Call, Command> commandMappings); protected Map<Call, Command> buildCommandMappings(); protected void resetCompletors(); protected SessionState sessionState(); protected Map<Call, Command> commandMappings(); public static void main(final String[] args); } class HadoopREPLTest { @Test public void testEvaluateHelpWithNoSuchCommandUsage() throws Exception {
final Configuration configuration = new Configuration(); final SessionState sessionState = mock(SessionState.class); when(sessionState.configuration()).thenReturn(configuration); final HadoopREPL repl = new HadoopREPL(configuration, sessionState); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { assertEquals("Unknown command \"test\"", String.format(invocationOnMock.getArguments()[0].toString(), invocationOnMock.getArguments()[1])); return null; } }).when(sessionState).error(anyString()); repl.evaluate("help test"); assertEquals("help test", Iterables.get(repl.history(), 0)); } }
9198697_6
class HadoopREPL extends REPL { @Override protected void evaluate(final String input) throws ExitSignal { popHistory(); final Iterable<String> inputParts = ARG_SPLITTER.limit(2).split(input); if (Iterables.isEmpty(inputParts)) { // Do nothing } else { final String command = Iterables.get(inputParts, 0).toLowerCase(); if (commandMappings.containsKey(call(command))) { commandMappings.get(call(command)).execute( new CommandInvocation(command, Iterables.toArray(ARG_SPLITTER.split(Iterables.get(inputParts, 1, "")), String.class)), sessionState ); } else { sessionState.output("Unknown command \"%s\"", command); } pushHistory(input); } } public HadoopREPL(final Configuration configuration); public HadoopREPL(final Configuration configuration, final SessionState sessionState); public HadoopREPL(final Configuration configuration, final SessionState sessionState, final Map<Call, Command> commandMappings); protected Map<Call, Command> buildCommandMappings(); protected void resetCompletors(); protected SessionState sessionState(); protected Map<Call, Command> commandMappings(); public static void main(final String[] args); } class HadoopREPLTest { @Test public void testEvaluateUnknownCommand() throws Exception {
final Configuration configuration = mock(Configuration.class); final SessionState sessionState = mock(SessionState.class); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocationOnMock) throws Throwable { assertEquals("Unknown command \"test\"", String.format(invocationOnMock.getArguments()[0].toString(), invocationOnMock.getArguments()[1])); return null; } }).when(sessionState).output(anyString(), any(Object[].class)); final HadoopREPL repl = new HadoopREPL(configuration, sessionState, ImmutableMap.<Call, Command>of()); repl.evaluate("test"); assertEquals("test", Iterables.get(repl.history(), 0)); } }
10585052_0
class Stamp implements Serializable { @Override public boolean equals(Object o) { if (!(o instanceof Stamp)) { return false; } else { Stamp other = (Stamp) o; return id.equals(other.getId()) && event.equals(other.getEvent()); } } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] fork(); public Stamp[] peek(); public Stamp join(Stamp other); public Stamp event(); @Override public String toString(); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); public boolean leq(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testEquals() {
assertTrue(seedStamp.equals(new Stamp())); assertFalse(seedStamp.equals(forkedStamp1)); assertTrue(forkedStamp1.equals(forkedStamp1)); assertFalse(forkedStamp1.equals(forkedStamp2)); } }
10585052_1
class Stamp implements Serializable { public Stamp[] peek() { return new Stamp[] { new Stamp(id, event), new Stamp(IDs.zero(), event) }; } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] fork(); public Stamp join(Stamp other); public Stamp event(); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); public boolean leq(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testPeek() {
for (Stamp stamp : stamps) { Stamp[] peek = stamp.peek(); assertIntEquals(2, peek.length); assertTrue(peek[0].equals(stamp)); assertTrue(peek[1].getId().isZero()); assertTrue(peek[1].getEvent().equals(stamp.getEvent())); assertNormalizedStamp(peek[0]); assertNormalizedStamp(peek[1]); } } }
10585052_2
class Stamp implements Serializable { public Stamp[] fork() { ID[] ids = id.split(); return new Stamp[] { new Stamp(ids[0], event), new Stamp(ids[1], event) }; } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] peek(); public Stamp join(Stamp other); public Stamp event(); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); public boolean leq(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testFork() {
for (Stamp stamp : stamps) { Stamp[] fork = stamp.fork(); ID[] splitIDs = stamp.getId().split(); assertIntEquals(2, fork.length); assertEquals(stamp.getEvent(), fork[0].getEvent()); assertEquals(stamp.getEvent(), fork[1].getEvent()); assertEquals(splitIDs[0], fork[0].getId()); assertEquals(splitIDs[1], fork[1].getId()); assertNormalizedStamp(fork[0]); assertNormalizedStamp(fork[1]); } } }
10585052_3
class Stamp implements Serializable { public Stamp join(Stamp other) { ID idSum = id.sum(other.id); Event eventJoin = event.join(other.event); return new Stamp(idSum, eventJoin); } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] fork(); public Stamp[] peek(); public Stamp event(); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); public boolean leq(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testJoin() {
Stamp expected = new Stamp(IDs.one(), Events.with(1, Events.zero(), Events.with(1))); assertEquals(expected, forkedStamp1.join(forkedStamp2)); assertEquals(expected, forkedStamp2.join(forkedStamp1)); assertNormalizedStamp(forkedStamp1.join(forkedStamp2)); } }
10585052_4
class Stamp implements Serializable { public Stamp event() { Event filled = Filler.fill(id, event); if (!filled.equals(event)) { return new Stamp(id, filled); } else { return new Stamp(id, Grower.grow(id, event)); } } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] fork(); public Stamp[] peek(); public Stamp join(Stamp other); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); public boolean leq(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testEvent() {
for (Stamp stamp : stamps) { Stamp evented = stamp.event(); assertTrue(stamp.getEvent().leq(evented.getEvent())); assertNormalizedStamp(evented); } } }
10585052_5
class Stamp implements Serializable { public boolean leq(Stamp other) { return event.leq(other.event); } public Stamp(); Stamp(ID id, Event event); ID getId(); Event getEvent(); public Stamp[] fork(); public Stamp[] peek(); public Stamp join(Stamp other); public Stamp event(); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public Stamp[] send(); public Stamp receive(Stamp other); public Stamp[] sync(Stamp other); private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; } class StampTest { private Stamp seedStamp; private Stamp forkedStamp1; private Stamp forkedStamp2; private Stamp joinedStamp; private List<Stamp> stamps; @Test public void testLeq() {
Stamp s1 = new Stamp(); Stamp s2 = new Stamp(); Assert.assertTrue(s1.leq(s2.event())); Assert.assertTrue(Causality.lessThanEquals(s1, s2.event())); Assert.assertFalse(s2.event().leq(s1)); Assert.assertFalse(Causality.lessThanEquals(s2.event(), s1)); } }
11383343_0
class MyAction extends ActionSupport { public String view() { id = "11"; name = "test-11"; return SUCCESS; } public String getId(); public void setId(String id); public String getName(); public void setName(String name); public String save(); public static final Logger LOG; } class TestMyAction extends ActionSupport { public static final Logger LOG; @Test public void testView() throws Exception {
ActionProxy proxy = getActionProxy("/view"); // actions.MyAction myAct = (actions.MyAction) proxy.getAction(); String result = proxy.execute(); assertEquals("success", result); // System.out.println(ToStringBuilder.reflectionToString(response)); System.out.println(response.getContentAsString()); // request.setParameter("id", "1"); // request.setParameter("name", "Test Desc"); } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
63