method2testcases
stringlengths
118
3.08k
### Question: SeamBeanNameResolver implements ELBeanNameResolver { public boolean init(ServletContext servletContext, ClassLoader classLoader) { try { Class<?> seamClass = classLoader.loadClass(SEAM_CLASS); getComponentNameMethod = seamClass.getMethod(GET_COMPONENT_NAME_METHOD, Class.class); if (log.isDebugEnabled()) { log.debug("Seam environment detected. Enabling bean name resolving via Seam."); } return true; } catch (ClassNotFoundException e) { if (log.isDebugEnabled()) { log.debug("Seam class has not been found. Seam resolver will be disabled."); } } catch (NoSuchMethodException e) { log.warn("Cannot find method getComponentName() on Seam class.", e); } catch (SecurityException e) { log.warn("Unable to init resolver due to security restrictions", e); } return false; } boolean init(ServletContext servletContext, ClassLoader classLoader); String getBeanName(Class<?> clazz); }### Answer: @Test public void testNoSeamEnvironment() throws Exception { ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); ClassLoader classLoader = EasyMock.createNiceMock(ClassLoader.class); EasyMock.expect(classLoader.loadClass((String) EasyMock.anyObject())).andThrow(new ClassNotFoundException()) .anyTimes(); EasyMock.replay(classLoader); SeamBeanNameResolver resolver = new SeamBeanNameResolver(); boolean initCompleted = resolver.init(servletContext, classLoader); assertFalse(initCompleted); }
### Question: ConstantExpression implements PrettyExpression { public String getELExpression() { return expression; } ConstantExpression(String expression); String getELExpression(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSimpleConstantExpression() { PrettyExpression expr = new ConstantExpression("#{someBean.someProperty}"); assertEquals("#{someBean.someProperty}", expr.getELExpression()); }
### Question: LazyExpression implements PrettyExpression { public String getELExpression() { if (expression == null) { expression = "#{" + finder.findBeanName(beanClass) + "." + component + "}"; if (log.isTraceEnabled()) { log.trace("Lazy expression resolved to: " + expression); } } return expression; } LazyExpression(LazyBeanNameFinder finder, Class<?> beanClass, String component); String getELExpression(); @Override String toString(); Class<?> getBeanClass(); String getComponent(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSimpleLazyExpression() { LazyBeanNameFinder beanNameFinder = EasyMock.createNiceMock(LazyBeanNameFinder.class); EasyMock.expect(beanNameFinder.findBeanName(SomeTestBean.class)).andReturn("someTestBean").once(); EasyMock.replay(beanNameFinder); PrettyExpression expr = new LazyExpression(beanNameFinder, SomeTestBean.class, "property"); assertEquals("#{someTestBean.property}", expr.getELExpression()); assertEquals("#{someTestBean.property}", expr.getELExpression()); EasyMock.verify(beanNameFinder); } @Test(expected = IllegalStateException.class) public void testUnresolvableLazyExpression() { LazyBeanNameFinder beanNameFinder = EasyMock.createNiceMock(LazyBeanNameFinder.class); EasyMock.expect(beanNameFinder.findBeanName(SomeTestBean.class)).andThrow(new IllegalStateException()).once(); EasyMock.replay(beanNameFinder); PrettyExpression expr = new LazyExpression(beanNameFinder, SomeTestBean.class, "property"); expr.getELExpression(); }
### Question: PrettyPhaseListener implements PhaseListener { public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; } PhaseId getPhaseId(); void beforePhase(final PhaseEvent event); void afterPhase(final PhaseEvent event); }### Answer: @Test public void testGetPhaseId() { assertEquals(PhaseId.ANY_PHASE, new PrettyPhaseListener().getPhaseId()); }
### Question: UrlPatternParser { public UrlPatternParser(final String pattern) { setUrlPattern(pattern); } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testUrlPatternParser() { assertTrue(parser instanceof UrlPatternParser); }
### Question: UrlPatternParser { public boolean matches(final String url) { return Pattern.compile(urlPattern).matcher(url).matches(); } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testMatches() { assertTrue(parser.matches("/project/starfish1/starfish2/story1")); assertFalse(parser.matches("project/starfish1/starfish2/story1")); assertFalse(parser.matches("/project/starfish1/starfish2/story1/")); assertFalse(parser.matches("project/starfish1/starfish2/story1/test")); assertFalse(parser.matches("project/starfish2/story1")); assertFalse(parser.matches("project/starfish1/starfish2")); assertFalse(parser.matches("project/starfish1/starfish2/")); }
### Question: UrlPatternParser { public Map<String, String> getMappedParameters(final String url) { Map<String, String> result = new HashMap<String, String>(); Matcher matcher = Pattern.compile(urlPattern).matcher(url); if (matcher.matches()) { for (int i = 0; i < expressions.size(); i++) { String el = expressions.get(i); String value = matcher.group(i + 1); result.put(el, value); } } return result; } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testGetMappedParameters() { Map<String, String> params = parser.getMappedParameters("/project/starfish1/starfish2/story1"); assertEquals(2, params.size()); }
### Question: UrlPatternParser { public String getMappedUrl(final Object... params) { StringBuffer result = new StringBuffer(); if (params != null) { Matcher matcher = FacesElUtils.elPattern.matcher(originalPattern); Object[] parameters = params; if ((params.length == 1) && (params[0] != null) && (params[0] instanceof List)) { List list = ((List) params[0]); if (list.size() == 0) { parameters = new Object[0]; } else { parameters = list.toArray(params); } } else if ((params.length == 1) && (params[0] == null)) { parameters = new Object[0]; } int i = 0; if (getParameterCount() != parameters.length) { throw new PrettyException("Invalid number of parameters supplied for pattern: " + originalPattern + ", expected <" + getParameterCount() + ">, got <" + parameters.length + ">"); } while (matcher.find()) { matcher.appendReplacement(result, parameters[i].toString()); i++; } matcher.appendTail(result); } else if (getParameterCount() > 0) { throw new PrettyException("Invalid number of parameters supplied: " + originalPattern + ", expected <" + getParameterCount() + ">, got <0>"); } return result.toString(); } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testGetMappedUrl() { String mappedUrl = parser.getMappedUrl("p1", 22, 55); assertEquals("/project/p1/22/55", mappedUrl); }
### Question: UrlPatternParser { public void setUrlPattern(final String urlPattern) { originalPattern = urlPattern; expressions.clear(); Matcher matcher = FacesElUtils.elPattern.matcher(urlPattern); while (matcher.find()) { expressions.add(matcher.group()); } this.urlPattern = matcher.replaceAll("([^/]+)"); } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testSetUrlPattern() { UrlPatternParser parser = new UrlPatternParser( "/project/#{paramsBean.project}/#{paramsBean.project}/#{paramsBean.story}"); assertEquals(3, parser.getParameterCount()); parser.setUrlPattern("/public/home"); assertEquals(0, parser.getParameterCount()); }
### Question: UrlPatternParser { public int getParameterCount() { return expressions.size(); } UrlPatternParser(final String pattern); boolean matches(final String url); Map<String, String> getMappedParameters(final String url); String getMappedUrl(final Object... params); void setUrlPattern(final String urlPattern); int getParameterCount(); }### Answer: @Test public void testGetParameterCount() { assertEquals(3, parser.getParameterCount()); }
### Question: HTTPDecoder { public String decode(final String value) { String result = value; if (value != null) { try { result = URLDecoder.decode(value, "UTF-8"); } catch (Exception e) { throw new PrettyException("Could not URLDecode value <" + value + ">", e); } } return result; } String decode(final String value); }### Answer: @Test public void testDecodeValidInputReturnsDecodedInput() { String value = "foo+bar"; assertEquals("foo bar", decoder.decode(value)); } @Test(expected = PrettyException.class) public void testDecodeInvalidInputThrowsException() { String value = "foo+bar%"; assertEquals("foo+bar%", decoder.decode(value)); } @Test public void testDecodeNullProducesNull() { String value = null; assertEquals(null, decoder.decode(value)); }
### Question: FacesElUtils { public Object invokeMethod(final FacesContext context, final String expression) throws ELException { MethodBinding methodBinding = context.getApplication().createMethodBinding(expression, null); return methodBinding.invoke(context, null); } boolean isEl(final String viewId); Object invokeMethod(final FacesContext context, final String expression); void setValue(final FacesContext context, final String expression, final Object value); Object getValue(final FacesContext context, final String expression); Class<?> getExpectedType(final FacesContext context, final String expression); static final String EL_REGEX; static final Pattern elPattern; }### Answer: @Test public void testCallElMethodWithNoArguments() throws SecurityException, NoSuchMethodException { FacesContext context = createMock(FacesContext.class, new Method[] { FacesContext.class.getMethod("getApplication") }); Application application = createMock(Application.class, new Method[] { Application.class.getMethod("createMethodBinding", String.class, Class[].class) }); MethodBinding methodBinding = createMock(MethodBinding.class); String expression = "aGivenExpression"; expect(context.getApplication()).andReturn(application); expect(application.createMethodBinding(expression, null)).andReturn(methodBinding); expect(methodBinding.invoke(context, null)).andReturn(new Object()); replay(context, application, methodBinding); FacesElUtils facesElUtils = new FacesElUtils(); facesElUtils.invokeMethod(context, expression); verify(context); }
### Question: PrettyConfig { public PrettyUrlMapping getMappingById(String id) { if (id != null) { if (id.startsWith(PrettyContext.PRETTY_PREFIX)) { id = id.substring(PrettyContext.PRETTY_PREFIX.length()); } for (PrettyUrlMapping mapping : getMappings()) { if (mapping.getId().equals(id)) { return mapping; } } } return null; } List<PrettyUrlMapping> getMappings(); void setMappings(final List<PrettyUrlMapping> mappings); void addMapping(final PrettyUrlMapping mapping); PrettyUrlMapping getMappingForUrl(final String url); boolean isMappingId(final String action); boolean isURLMapped(final String url); boolean isViewMapped(String viewId); PrettyUrlMapping getMappingById(String id); static final String CONFIG_REQUEST_KEY; }### Answer: @Test public void testGetMappingById() { PrettyUrlMapping mapping2 = config.getMappingById("testid"); assertEquals(mapping, mapping2); } @Test public void testGetMappingByNullIdReturnsNull() { PrettyUrlMapping mapping2 = config.getMappingById(null); assertEquals(null, mapping2); }
### Question: PrettyConfig { public PrettyUrlMapping getMappingForUrl(final String url) { for (PrettyUrlMapping mapping : getMappings()) { String urlPattern = mapping.getPattern(); UrlPatternParser um = new UrlPatternParser(urlPattern); if (um.matches(url)) { return mapping; } } return null; } List<PrettyUrlMapping> getMappings(); void setMappings(final List<PrettyUrlMapping> mappings); void addMapping(final PrettyUrlMapping mapping); PrettyUrlMapping getMappingForUrl(final String url); boolean isMappingId(final String action); boolean isURLMapped(final String url); boolean isViewMapped(String viewId); PrettyUrlMapping getMappingById(String id); static final String CONFIG_REQUEST_KEY; }### Answer: @Test public void testGetMappingForUrl() { PrettyUrlMapping mapping2 = config.getMappingForUrl("/home/en/test/"); assertEquals(mapping, mapping2); }
### Question: PrettyConfig { public boolean isViewMapped(String viewId) { if (viewId != null) { viewId = viewId.trim(); PrettyUrlMapping needle = new PrettyUrlMapping(); needle.setViewId(viewId); if (viewId.startsWith("/")) { if (getMappings().contains(needle)) { return true; } needle.setViewId(viewId.substring(1)); } return getMappings().contains(needle); } return false; } List<PrettyUrlMapping> getMappings(); void setMappings(final List<PrettyUrlMapping> mappings); void addMapping(final PrettyUrlMapping mapping); PrettyUrlMapping getMappingForUrl(final String url); boolean isMappingId(final String action); boolean isURLMapped(final String url); boolean isViewMapped(String viewId); PrettyUrlMapping getMappingById(String id); static final String CONFIG_REQUEST_KEY; }### Answer: @Test public void isViewMapped() throws Exception { assertTrue(config.isViewMapped("/faces/view.jsf")); assertFalse(config.isViewMapped("/faces/view2.jsf")); } @Test public void isNullViewMappedReturnsFalse() throws Exception { assertFalse(config.isViewMapped(null)); }
### Question: PrettyConfig { public boolean isURLMapped(final String url) { PrettyUrlMapping mapping = getMappingForUrl(url); return (mapping != null); } List<PrettyUrlMapping> getMappings(); void setMappings(final List<PrettyUrlMapping> mappings); void addMapping(final PrettyUrlMapping mapping); PrettyUrlMapping getMappingForUrl(final String url); boolean isMappingId(final String action); boolean isURLMapped(final String url); boolean isViewMapped(String viewId); PrettyUrlMapping getMappingById(String id); static final String CONFIG_REQUEST_KEY; }### Answer: @Test public void testIsURLMapped() throws Exception { assertTrue(config.isURLMapped("/home/en/test/")); assertFalse(config.isViewMapped("/home/en/notmapped/okthen")); }
### Question: DigesterPrettyConfigParser implements PrettyConfigParser { public void parse(final PrettyConfigBuilder builder, final InputStream resource) throws IOException, SAXException { if (builder == null) { throw new IllegalArgumentException("Builder must not be null."); } if (resource == null) { throw new IllegalArgumentException("Input stream must not be null."); } final Digester digester = configureDigester(new Digester()); digester.push(builder); digester.parse(resource); } void parse(final PrettyConfigBuilder builder, final InputStream resource); }### Answer: @Test public void testParse() { PrettyUrlMapping mapping = config.getMappingById("0"); assertEquals("0", mapping.getId()); assertEquals("/project/#{viewProjectBean.projectId}/", mapping.getPattern()); assertEquals("#{viewProjectBean.getPrettyTarget}", mapping.getViewId()); List<UrlAction> actions = mapping.getActions(); assertTrue(actions.contains(new UrlAction("#{viewProjectBean.load}"))); assertTrue(actions.contains(new UrlAction("#{viewProjectBean.authorize}"))); }
### Question: ValidationController { public <T> void processBeanValidation(final T entity) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> errors = validator.validate(entity); if (!errors.isEmpty()) { throw new ConstraintViolationException(errors); } } private ValidationController(); static ValidationController get(final Class<T> clazz); void processBeanValidation(final T entity); void processBeanValidationForProperty(final T entity, String propertyName); void processBeanValidationForGroup(final T entity, Class<?>... groupClasses); }### Answer: @Test public void processBeanValidation() throws Exception { TestEntity testEntity = new TestEntity(); testEntity.futureDate = ZonedDateTime.now().minusDays(1); try { ValidationController.get(TestEntity.class).processBeanValidation(testEntity); fail("Wrong values are not recognized"); } catch (Exception ex) { ex.printStackTrace(); assertThat(ex, instanceOf(ConstraintViolationException.class)); assertThat(((ConstraintViolationException)ex).getConstraintViolations().size(), is(3)); } }
### Question: Lottery { public void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket) { ZonedDateTime lastDrawing = calculateEndingDateForCancelledPermaTicket(mainTicket); mainTicket.setPermaTicket(false); mainTicket.setEndingDate(lastDrawing); datastore.update( datastore.createQuery(MainTicket.class).field("_id").equal(mainTicket.getId()), datastore.createUpdateOperations(MainTicket.class) .set("endingDate", lastDrawing).set("permaTicket", false) ); } abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void setTicketStateAfterSubscriptionCancelled() throws Exception { }
### Question: Lottery { protected int getMaxNumberOfDrawingsPerWeek(DrawingType drawingType) { return 1; } abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getMaxNumberOfDrawingsPerWeek() throws Exception { }
### Question: Lottery { public ZonedDateTime getDateTimeNow() { return getDateTimeService().getDateTimeNowEurope(); } abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getDateTimeNow() throws Exception { }
### Question: Lottery { public DateTimeService getDateTimeService() { return dateTimeService; } abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getDateTimeService() throws Exception { }
### Question: Lottery { public abstract Jackpot getCurrentJackpot(); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getCurrentJackpot() throws Exception { }
### Question: ValidationController { public <T> void processBeanValidationForProperty(final T entity, String propertyName) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> errors = validator.validateProperty(entity, propertyName); if (!errors.isEmpty()) { throw new ConstraintViolationException(errors); } } private ValidationController(); static ValidationController get(final Class<T> clazz); void processBeanValidation(final T entity); void processBeanValidationForProperty(final T entity, String propertyName); void processBeanValidationForGroup(final T entity, Class<?>... groupClasses); }### Answer: @Test public void processBeanValidationForProperty() throws Exception { TestEntity testEntity = new TestEntity(); testEntity.emptyOrSize = "abc"; try { ValidationController.get(TestEntity.class).processBeanValidationForProperty(testEntity, "emptyOrSize"); } catch (Exception ex) { fail("Correct values for the specified group are not recognized."); } testEntity.emptyOrSize = "abcdef"; try { ValidationController.get(TestEntity.class).processBeanValidationForProperty(testEntity, "emptyOrSize"); fail("Wrong value in 'emptyOrSize' is not recognized"); } catch (Exception ex) { assertThat(ex, instanceOf(ConstraintViolationException.class)); assertThat(((ConstraintViolationException)ex).getConstraintViolations().size(), is(1)); } }
### Question: PasswordService { public String createMD5(String password) { if (password == null) { return null; } MessageDigest md; String result = null; try { md = MessageDigest.getInstance("MD5"); md.update(fromHex(PasswordService.SALT)); byte[] bytes = md.digest(password.getBytes()); StringBuilder sb = new StringBuilder(); for (byte aByte : bytes) { sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1)); } result = sb.toString(); } catch (NoSuchAlgorithmException ignore) {} return result; } PasswordService(); void setupPasswordToUser(final Player player, final String password); boolean isPasswordValid(final Player player, final String pwHashToCheck); String createMD5(String password); static final String SALT; }### Answer: @Test public void createMD5() { PasswordService cut = new PasswordService(); assertThat(cut.createMD5("123456"), Is.is("6dbeca3ec141a1759896c9e191fd2dca")); }
### Question: EncryptionService { public byte[] encryptData(byte[] data) { try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, getAesKey()); return cipher.doFinal(data); } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException ex) { throw new SecurityException(ex); } } EncryptionService(); byte[] encryptData(byte[] data); byte[] decryptData(byte[] encryptedData); Key getAesKey(); }### Answer: @Test public void encryptData() throws NoSuchFieldException, IllegalAccessException { final String base64Encoded = "hfZcGLKmy9Q9iPRR+3XfmV7TzHoYU+6NKvJk4gSZfI0="; EncryptionService cut = new EncryptionService(); cut.encryptionKey = createEncryptionKey("01234567890123456789012345678912"); final Charset charset = Charset.forName("UTF-8"); final byte[] bytes = cut.encryptData("test@example.com".getBytes(charset)); assertThat(new String(Base64.getEncoder().encode(bytes)), CoreMatchers.is(base64Encoded)); final EncryptionService encryptionService = getEncryptedFieldConverter().getEncryptionService(); final Field encryptionKeyField = encryptionService.getClass().getDeclaredField("encryptionKey"); encryptionKeyField.setAccessible(true); encryptionKeyField.set(encryptionService, cut.encryptionKey); TestPlayer testPlayer = new TestPlayer(); testPlayer.setEmail("test@example.com"); getDatastore().save(testPlayer); final List<Player> foundPlayerList = getDatastore().find(Player.class).field("email").equal(new EncryptedFieldValueWrapper("test@example.com")).asList(); assertThat(foundPlayerList.size(), CoreMatchers.is(1)); }
### Question: EncryptionService { public byte[] decryptData(byte[] encryptedData) { try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, getAesKey()); return cipher.doFinal(encryptedData); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { throw new SecurityException(ex); } } EncryptionService(); byte[] encryptData(byte[] data); byte[] decryptData(byte[] encryptedData); Key getAesKey(); }### Answer: @Test public void decryptData() throws Exception { final String base64Encoded = "hfZcGLKmy9Q9iPRR+3XfmV7TzHoYU+6NKvJk4gSZfI0="; EncryptionService cut = new EncryptionService(); cut.encryptionKey = createEncryptionKey("01234567890123456789012345678912"); assertThat(new String(cut.decryptData(Base64.getDecoder().decode(base64Encoded))), Is.is("test@example.com")); }
### Question: ZonedDateTimeUTCtoEuropeConverter extends TypeConverter implements SimpleValueConverter { @Override public Object encode(Object value, MappedField optionalExtraInfo) { if (value == null || !(value instanceof ZonedDateTime)) { return null; } ZonedDateTime zonedDateTimeEurope = (ZonedDateTime) value; Date date = new Date(); date.setTime(zonedDateTimeEurope.toInstant().toEpochMilli()); return date; } ZonedDateTimeUTCtoEuropeConverter(); @Override Object encode(Object value, MappedField optionalExtraInfo); @Override Object decode(Class<?> targetClass, Object fromDBObject, MappedField optionalExtraInfo); }### Answer: @Test public void testEncodingTheZonedDateToUTC() { ZonedDateTime testDateTime = ZonedDateTime.of(2017, 6, 20, 0, 0, 0, 0, ZoneId.of("Europe/Paris")); ZonedDateTimeUTCtoEuropeConverter cut = new ZonedDateTimeUTCtoEuropeConverter(); final Object encode = cut.encode(testDateTime, null); assertThat(encode, instanceOf(Date.class)); assertThat(((Date)encode).getTime(), is(testDateTime.toInstant().atZone(ZoneId.of("UTC")).toEpochSecond()*1000)); }
### Question: ZonedDateTimeUTCtoEuropeConverter extends TypeConverter implements SimpleValueConverter { @Override public Object decode(Class<?> targetClass, Object fromDBObject, MappedField optionalExtraInfo) { if (fromDBObject == null || !(fromDBObject instanceof Date)) { return null; } Date date = (Date) fromDBObject; ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC")); if (optionalExtraInfo != null && optionalExtraInfo.getField().isAnnotationPresent(ZonedDateTimeEurope.class)) { zonedDateTime = zonedDateTime.toInstant().atZone(ZoneId.of("Europe/Paris")); } return zonedDateTime; } ZonedDateTimeUTCtoEuropeConverter(); @Override Object encode(Object value, MappedField optionalExtraInfo); @Override Object decode(Class<?> targetClass, Object fromDBObject, MappedField optionalExtraInfo); }### Answer: @Test public void testDecodeUTCtoZonedDateEurope() { ZonedDateTime expected = ZonedDateTime.of(2017, 6, 20, 0, 0, 0, 0, ZoneId.of("Europe/Paris")); ZonedDateTimeUTCtoEuropeConverter cut = new ZonedDateTimeUTCtoEuropeConverter(); Field mockedField = mock(Field.class); when(mockedField.isAnnotationPresent(ZonedDateTimeEurope.class)).thenReturn(true); MappedField mockedMappedField = mock(MappedField.class); when(mockedMappedField.getField()).thenReturn(mockedField); Date date = new Date(); date.setTime(1497909600000L); final Object decode = cut.decode(ZonedDateTime.class, date, mockedMappedField); assertThat(decode, instanceOf(ZonedDateTime.class)); assertThat(decode, is(expected)); assertThat(((ZonedDateTime)decode).getZone(), is(ZoneId.of("Europe/Paris"))); }
### Question: DateTimeService { public ZonedDateTime getDateTimeNowEurope() { return ZonedDateTime.now(ZoneId.of("Europe/Paris")); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getDateTimeNowEurope() { DateTimeService cut = new DateTimeService(); long currentTime = System.currentTimeMillis(); final ZonedDateTime dateTimeNowEurope = cut.getDateTimeNowEurope(); assertThat(dateTimeNowEurope.getZone(), is(ZoneId.of("Europe/Paris"))); assertThat(currentTime - dateTimeNowEurope.toEpochSecond() * 1000, lessThan(ACCEPTABLE_TIME_IN_MILLIS_DIFF)); }
### Question: DateTimeService { public ZonedDateTime getDateTimeNowUTC() { return ZonedDateTime.now(ZoneId.of("UTC")); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getDateTimeNowUTC() { DateTimeService cut = new DateTimeService(); final ZonedDateTime dateTimeNowUTC = cut.getDateTimeNowUTC(); long currentTime = System.currentTimeMillis(); assertThat(dateTimeNowUTC.getZone(), is(ZoneId.of("UTC"))); assertThat(currentTime - dateTimeNowUTC.toEpochSecond() * 1000, lessThan(ACCEPTABLE_TIME_IN_MILLIS_DIFF)); }
### Question: ValidationController { public <T> void processBeanValidationForGroup(final T entity, Class<?>... groupClasses) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> errors = validator.validate(entity, groupClasses); if (!errors.isEmpty()) { throw new ConstraintViolationException(errors); } } private ValidationController(); static ValidationController get(final Class<T> clazz); void processBeanValidation(final T entity); void processBeanValidationForProperty(final T entity, String propertyName); void processBeanValidationForGroup(final T entity, Class<?>... groupClasses); }### Answer: @Test public void processBeanValidationForGroup() throws Exception { TestEntity testEntity = new TestEntity(); testEntity.emptyOrSize = "abc"; testEntity.noSpace = "abc"; testEntity.notEmpty = "abcd"; try { ValidationController.get(TestEntity.class).processBeanValidationForGroup(testEntity, PasswordGroup.class); } catch (Exception ex) { fail("Correct values for the specified group are not recognized."); } testEntity.noSpace = "ab c"; try { ValidationController.get(TestEntity.class).processBeanValidationForGroup(testEntity, PasswordGroup.class); fail("Wrong value in 'noSpace' is not recognized"); } catch (Exception ex) { assertThat(ex, instanceOf(ConstraintViolationException.class)); assertThat(((ConstraintViolationException)ex).getConstraintViolations().size(), is(1)); } }
### Question: DateTimeService { public ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime) { return zonedDateTime.toInstant().atZone(ZoneId.of("UTC")).withHour(0).withMinute(0).withSecond(0).withNano(0); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getBeginningTimestampOfDay() throws Exception { DateTimeService cut = new DateTimeService(); ZonedDateTime expected = ZonedDateTime.now(ZoneId.of("UTC")).withYear(2017).withMonth(6).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0); ZonedDateTime current = ZonedDateTime.of(2017, 6, 1, 12, 23, 45, 800, ZoneId.of("UTC")); assertThat(cut.getBeginningTimestampOfDayUTC(current), is(expected)); }
### Question: DateTimeService { public ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime) { return zonedDateTime.toInstant() .atZone(ZoneId.of("UTC")) .plusDays(1) .withHour(0).withMinute(0).withSecond(0).withNano(0) .minus(1, ChronoUnit.SECONDS); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getEndingTimestampOfDay() throws Exception { DateTimeService cut = new DateTimeService(); ZonedDateTime expected = ZonedDateTime.now(ZoneId.of("UTC")).withYear(2017).withMonth(6).withDayOfMonth(1).withHour(23).withMinute(59).withSecond(59).withNano(0); ZonedDateTime current = ZonedDateTime.of(2017, 6, 1, 12, 23, 45, 800, ZoneId.of("UTC")); assertThat(cut.getEndingTimestampOfDayUTC(current), is(expected)); }
### Question: DateTimeService { public ZonedDateTime getBeginningOfCurrentYear() { return getDateTimeNowUTC().withDayOfYear(1).withHour(0).withMinute(0).withSecond(0).withNano(0); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getBeginningOfCurrentYear() { DateTimeService cut = new DateTimeService(); final DateTimeService spyCut = Mockito.spy(cut); final ZonedDateTime now = cut.getDateTimeNowEurope(); ZonedDateTime current = ZonedDateTime.of(now.getYear(), 6, 1, 12, 23, 45, 800, ZoneId.of("UTC")); ZonedDateTime expected = ZonedDateTime.of(now.getYear(), 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")); when(spyCut.getDateTimeNowUTC()).thenReturn(current); assertThat(cut.getBeginningOfCurrentYear(), is(expected)); }
### Question: DateTimeService { public ZonedDateTime getEndingOfCurrentYear() { ZonedDateTime dateTimeNowUTC = getDateTimeNowUTC(); dateTimeNowUTC = dateTimeNowUTC.withYear(dateTimeNowUTC.getYear() + 1).withDayOfYear(1).withHour(0).withMinute(0).withSecond(0).withNano(0); return dateTimeNowUTC.minusSeconds(1); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getEndingOfCurrentYear() { DateTimeService cut = new DateTimeService(); final DateTimeService spyCut = Mockito.spy(cut); final ZonedDateTime now = cut.getDateTimeNowEurope(); ZonedDateTime current = ZonedDateTime.of(now.getYear(), 6, 1, 12, 23, 45, 800, ZoneId.of("UTC")); ZonedDateTime expected = ZonedDateTime.of(now.getYear(), 12, 31, 23, 59, 59, 0, ZoneId.of("UTC")); when(spyCut.getDateTimeNowUTC()).thenReturn(current); assertThat(cut.getEndingOfCurrentYear(), is(expected)); }
### Question: DateTimeService { public ZonedDateTime convertDateToZonedDateTimeEurope(Date date) { return ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("Europe/Paris")); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void testConvertDateToZonedDateTimeEurope() { DateTimeService cut = new DateTimeService(); ZonedDateTime utc = ZonedDateTime.of(2017, 6, 19, 22, 0, 0, 0, ZoneId.of("UTC")); Date date = new Date(utc.toEpochSecond() * 1000L); ZonedDateTime expected = ZonedDateTime.of(2017, 6, 20, 0, 0, 0, 0, ZoneId.of("Europe/Paris")); assertThat(cut.convertDateToZonedDateTimeEurope(date), is(expected)); }
### Question: DateTimeService { public String getMonthNameFor(ZonedDateTime dateTime) { return dateTime.getMonth().getDisplayName(TextStyle.FULL, Locale.GERMANY); } ZonedDateTime getFutureDate(ZonedDateTime timestamp, int numberOfDays, boolean endOfDay); ZonedDateTime getDateTimeNowEurope(); ZonedDateTime getDateTimeNowUTC(); ZonedDateTime getBeginningTimestampOfMonthUTC(final ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfMonthUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfWeekUTC(ZonedDateTime zonedDateTime); ZonedDateTime getBeginningTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime getEndingTimestampOfDayUTC(ZonedDateTime zonedDateTime); ZonedDateTime convertDateToZonedDateTimeEurope(Date date); ZonedDateTime getBeginningOfCurrentYear(); ZonedDateTime getEndingOfCurrentYear(); String getMonthNameFor(ZonedDateTime dateTime); }### Answer: @Test public void getMonthNameFor() { DateTimeService cut = new DateTimeService(); ZonedDateTime current = ZonedDateTime.of(2017, 6, 20, 12, 23, 45, 800, ZoneId.of("UTC")); assertThat(cut.getMonthNameFor(current), is("Juni")); current = ZonedDateTime.of(2017, 1, 20, 12, 23, 45, 800, ZoneId.of("UTC")); assertThat(cut.getMonthNameFor(current), is("Januar")); }
### Question: CurrencyConverter extends TypeConverter implements SimpleValueConverter { @Override public Object encode(Object value, MappedField optionalExtraInfo) { if (value == null) { return null; } return ((Currency) value).getCurrencyCode(); } @Override Object decode(Class<?> aClass, Object o, MappedField mappedField); @Override Object encode(Object value, MappedField optionalExtraInfo); }### Answer: @Test public void testEncode() { CurrencyConverter cut = new CurrencyConverter(); final Object encode = cut.encode(Currency.getInstance(Locale.GERMANY)); assertThat(encode.toString(), is("EUR")); }
### Question: CurrencyConverter extends TypeConverter implements SimpleValueConverter { @Override public Object decode(Class<?> aClass, Object o, MappedField mappedField) { if (o == null) { return null; } String currencyCode = o.toString(); return Currency.getInstance(currencyCode); } @Override Object decode(Class<?> aClass, Object o, MappedField mappedField); @Override Object encode(Object value, MappedField optionalExtraInfo); }### Answer: @Test public void testDecode() { CurrencyConverter cut = new CurrencyConverter(); final Object decode = cut.decode(Currency.class, "EUR"); assertThat(decode instanceof Currency, is(true)); assertThat(((Currency) decode).getCurrencyCode(), is("EUR")); }
### Question: CurrencyFormatter { public String convertCentToEuroFormatted(int amountInCent) { Price price = new Price(amountInCent); return convertCentToEuroFormatted(price); } String convertCentToEuroFormatted(int amountInCent); String convertCentToEuroFormatted(final Price price); }### Answer: @Test public void convertCentToEuroFormatted() { CurrencyFormatter cut = new CurrencyFormatter(); assertThat(cut.convertCentToEuroFormatted(18250), is("182,50 EUR")); }
### Question: ActivityLogController implements Serializable { public void saveActivityLog(final Player player, final ActivityType activityType, String... data) { saveActivityLog(((player != null) ? player.getId() : null), activityType, data); } @SuppressWarnings({"WeakerAccess"}) ActivityLogController(); void saveActivityLog(final Player player, final ActivityType activityType, String... data); void saveActivityLog(final ObjectId objectId, final ActivityType activityType, String... data); static final int DATA_COMPONENT_SIZE_WITH_KEY_VALUE; }### Answer: @Test public void saveActivityLog() throws Exception { ActivityLogController cut = new ActivityLogController(); cut.datastore = getDatastore(); cut.dateTimeService = dateTimeService; cut.saveActivityLog(getPlayer(), ActivityType.LOGIN_SUCCESS, "data1", "testdata1", "data2", "testdata2"); final List<ActivityLog> activityLogList = getDatastore().createQuery(ActivityLog.class).asList(); assertThat(activityLogList, notNullValue()); assertThat(activityLogList.size(), is(1)); assertThat(activityLogList.get(0).getActivityType(), is(ActivityType.LOGIN_SUCCESS)); assertThat(activityLogList.get(0).getActivityFamily(), is(ActivityFamily.LOGIN)); assertThat(activityLogList.get(0).getPlayerId(), is(TEST_PLAYER_ID)); assertThat(activityLogList.get(0).getData().containsKey("data1"), is(true)); assertThat(activityLogList.get(0).getData().containsValue("testdata1"), is(true)); assertThat(activityLogList.get(0).getData().containsKey("data2"), is(true)); assertThat(activityLogList.get(0).getData().containsValue("testdata2"), is(true)); }
### Question: CDIBeanService { public static CDIBeanService getInstance() { return INSTANCE; } private CDIBeanService(); static CDIBeanService getInstance(); T getCDIBean(final Class<T> clazz); T getCDIBeanByName(final String name, Class<T> clazz); void injectManual(Object obj); }### Answer: @Test public void testGetInstance() throws Exception { final CDIBeanService cut = CDIBeanService.getInstance(); assertThat(cut, CoreMatchers.notNullValue()); }
### Question: CDIBeanService { public <T> T getCDIBean(final Class<T> clazz) { BeanManager manager = getBeanManager(); if (manager != null) { Bean<T> bean = (Bean<T>) manager.getBeans(clazz).iterator().next(); CreationalContext<T> ctx = manager.createCreationalContext(bean); return (T) manager.getReference(bean, clazz, ctx); } else { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.warning("Could not create instance of class <" + clazz + ">."); } return null; } } private CDIBeanService(); static CDIBeanService getInstance(); T getCDIBean(final Class<T> clazz); T getCDIBeanByName(final String name, Class<T> clazz); void injectManual(Object obj); }### Answer: @Test public void getCDIBean() throws Exception { final CDIBeanService cut = CDIBeanService.getInstance(); final CDITestBean cdiTestBean = cut.getCDIBean(CDITestBean.class); final CDITestBean cdiTestBean2 = cut.getCDIBean(CDITestBean.class); assertThat(cdiTestBean, notNullValue()); assertThat(cdiTestBean == cdiTestBean2, is(true)); assertThat(cdiTestBean.getName(), is("I am a singleton bean")); assertThat(cdiTestBean.getCdiTestInjected(), notNullValue()); assertThat(cdiTestBean.getCdiTestInjected().getLabel(), is("I am a manuel injected bean")); }
### Question: Lottery { public abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getNextClosingDate() throws Exception { }
### Question: CDIBeanService { public <T> T getCDIBeanByName(final String name, Class<T> clazz) { BeanManager bm = getBeanManager(); Bean<T> bean = (Bean<T>) bm.getBeans(name).iterator().next(); CreationalContext<T> ctx = bm.createCreationalContext(bean); return (T) bm.getReference(bean, clazz, ctx); } private CDIBeanService(); static CDIBeanService getInstance(); T getCDIBean(final Class<T> clazz); T getCDIBeanByName(final String name, Class<T> clazz); void injectManual(Object obj); }### Answer: @Test public void getCDIBeanByName() throws Exception { final CDIBeanService cut = CDIBeanService.getInstance(); final CDITestBean cdiTestBean = cut.getCDIBeanByName("cDITestBean", CDITestBean.class); assertThat(cdiTestBean, notNullValue()); assertThat(cdiTestBean.getName(), is("I am a singleton bean")); }
### Question: CDIBeanService { public void injectManual(Object obj) { BeanManager beanManager = getBeanManager(); AnnotatedType type = (AnnotatedType) beanManager.createAnnotatedType(obj.getClass()); InjectionTarget it = beanManager.createInjectionTarget(type); CreationalContext instanceContext = beanManager.createCreationalContext(null); it.inject(obj, instanceContext); it.postConstruct(obj); } private CDIBeanService(); static CDIBeanService getInstance(); T getCDIBean(final Class<T> clazz); T getCDIBeanByName(final String name, Class<T> clazz); void injectManual(Object obj); }### Answer: @Test public void injectManual() throws Exception { final CDIBeanService cut = CDIBeanService.getInstance(); NoCdiBean noCdiBean = new NoCdiBean(); assertThat(noCdiBean.getCdiTestInjected(), nullValue()); cut.injectManual(noCdiBean); assertThat(noCdiBean.getCdiTestInjected(), notNullValue()); assertThat(noCdiBean.getCdiTestInjected().getLabel(), is("I am a manuel injected bean")); }
### Question: V_000004 implements Migrateable { @Override public void executeMigration(Datastore datastore) { PriceList priceList = datastore.createQuery(PriceList.class).field("lotteryIdentifier").equal(EuroJackpotLottery.IDENTIFIER).get(); if (priceList == null) { priceList = new PriceList(); } priceList.setLotteryIdentifier(EuroJackpotLottery.IDENTIFIER); priceList.setPricePerField(200); priceList.setPriceSuper6(125); priceList.setPriceSpiel77(250); priceList.setPriceGluecksspirale(500); priceList.setFeeGluecksspirale(60); priceList.setFeeFirstDrawing(60); priceList.setFeeSecondDrawing(40); priceList.setValidFrom(getInitialDate()); datastore.save(priceList); } @Override void executeMigration(Datastore datastore); }### Answer: @Test public void executeMigration() throws Exception { V_000004 cut = new V_000004(); cut.executeMigration(getDatastore()); PriceList priceList = getDatastore().createQuery(PriceList.class).field("lotteryIdentifier").equal(EuroJackpotLottery.IDENTIFIER).get(); assertThat(priceList, notNullValue()); assertThat(priceList.getValidFrom(), is(cut.getInitialDate())); assertThat(priceList.getPricePerField(), is(200)); assertThat(priceList.getPriceSuper6(), is(125)); assertThat(priceList.getPriceSpiel77(), is(250)); assertThat(priceList.getPriceGluecksspirale(), is(500)); assertThat(priceList.getFeeFirstDrawing(), is(60)); assertThat(priceList.getFeeSecondDrawing(), is(40)); }
### Question: V_000002 implements Migrateable { @Override public void executeMigration(Datastore datastore) throws IOException { BufferedReader in = getBufferedReader(); String line; List<PlzCityState> plzCityStateList = new LinkedList<>(); while ((line = in.readLine()) != null) { final String[] strings = line.split("\\t"); PlzCityState plzCityState = new PlzCityState(strings[1], strings[2], strings[0]); plzCityStateList.add(plzCityState); } datastore.save(plzCityStateList); } @Override void executeMigration(Datastore datastore); }### Answer: @Test public void testExecuteMigration() throws Exception { V_000002 cut = new V_000002(); final V_000002 spyCut = Mockito.spy(cut); InputStream is = getInputStream(); Mockito.doReturn(is).when(spyCut).getInputStream(); spyCut.executeMigration(getDatastore()); final List<PlzCityState> cities = getDatastore().createQuery(PlzCityState.class).asList(); assertThat(cities, notNullValue()); assertThat(cities.size(), is(6)); assertThat(cities.get(3).getCity(), is("Ratzeburg")); assertThat(cities.get(3).getCityCode(), is("23909")); assertThat(cities.get(3).getState(), is("Schleswig-Holstein")); }
### Question: V_000001 implements Migrateable { @Override public void executeMigration(Datastore datastore) throws IOException { final BufferedReader in = getBufferedReaderForFile(); String line; String lastBic = ""; List<Bank> bankList = new LinkedList<>(); while ((line = in.readLine()) != null) { String bic = line.substring(139, 150).trim(); if (bic.length() == 0) { bic = lastBic; } else { lastBic = bic; } Bank bank = new Bank(line.substring(0, 8), line.substring(9, 67).trim(), line.substring(67, 72).trim(), line.substring(72, 107).trim(), line.substring(107, 134).trim(), bic); bankList.add(bank); } datastore.save(bankList); } @Override void executeMigration(Datastore datastore); }### Answer: @Test public void testExecuteMigration() throws Exception { V_000001 cut = new V_000001(); final V_000001 spyCut = Mockito.spy(cut); InputStream is = getInputStream(); Mockito.doReturn(is).when(spyCut).getInputStream(); spyCut.executeMigration(getDatastore()); final List<Bank> banks = getDatastore().createQuery(Bank.class).asList(); assertThat(banks, notNullValue()); assertThat(banks.size(), is(4)); assertThat(banks.get(0).getBlz(), is("10000000")); assertThat(banks.get(0).getDescription(), is("Bundesbank")); assertThat(banks.get(0).getPlz(), is("10591")); assertThat(banks.get(0).getCity(), is("Berlin")); assertThat(banks.get(0).getShortDescription(), is("BBk Berlin")); assertThat(banks.get(0).getBic(), is("MARKDEF1100")); }
### Question: V_000000 implements Migrateable { @Override public void executeMigration(Datastore datastore) { PriceList priceList = datastore.createQuery(PriceList.class).field("lotteryIdentifier").equal(German6aus49Lottery.IDENTIFIER).get(); if (priceList == null) { priceList = new PriceList(); } priceList.setLotteryIdentifier(German6aus49Lottery.IDENTIFIER); priceList.setPricePerField(100); priceList.setPriceSuper6(125); priceList.setPriceSpiel77(250); priceList.setPriceGluecksspirale(500); priceList.setFeeGluecksspirale(60); priceList.setFeeFirstDrawing(60); priceList.setFeeSecondDrawing(40); priceList.setValidFrom(getInitialDate()); datastore.save(priceList); } @Override void executeMigration(Datastore datastore); }### Answer: @Test public void executeMigration() throws Exception { V_000000 cut = new V_000000(); cut.executeMigration(getDatastore()); PriceList priceList = getDatastore().createQuery(PriceList.class).field("lotteryIdentifier").equal(German6aus49Lottery.IDENTIFIER).get(); assertThat(priceList, notNullValue()); assertThat(priceList.getValidFrom(), is(cut.getInitialDate())); assertThat(priceList.getPricePerField(), is(100)); assertThat(priceList.getPriceSuper6(), is(125)); assertThat(priceList.getPriceSpiel77(), is(250)); assertThat(priceList.getPriceGluecksspirale(), is(500)); assertThat(priceList.getFeeFirstDrawing(), is(60)); assertThat(priceList.getFeeSecondDrawing(), is(40)); }
### Question: Lottery { public abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getNextDrawing() throws Exception { }
### Question: Lottery { public abstract List<String> getPossibleAdditionalLotteries(); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getPossibleAdditionalLotteries() throws Exception { }
### Question: Lottery { public abstract String getIdentifier(); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getIdentifier() throws Exception { }
### Question: Lottery { public abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void createNewEmbeddedTicket() throws Exception { }
### Question: Lottery { public abstract WinCalculator getWinCalculator(); abstract ZonedDateTime getNextClosingDate(); abstract ZonedDateTime getNextDrawing(ZonedDateTime current, DrawingType drawingType); abstract List<String> getPossibleAdditionalLotteries(); abstract String getIdentifier(); abstract Ticket createNewEmbeddedTicket(MainTicket parentTicket, String newAdditionalLotteries); abstract WinCalculator getWinCalculator(); void setTicketStateAfterSubscriptionCancelled(MainTicket mainTicket); ZonedDateTime getDateTimeNow(); DateTimeService getDateTimeService(); abstract Jackpot getCurrentJackpot(); }### Answer: @Test public void getWinCalculator() throws Exception { }
### Question: CucumberMojo extends AbstractJRubyMojo { String allCucumberArgs() { List<String> allCucumberArgs = new ArrayList<String>(); if (cucumberArgs != null) allCucumberArgs.addAll(cucumberArgs); if (extraCucumberArgs != null) allCucumberArgs.add(extraCucumberArgs); allCucumberArgs.add(features); return Utils.join(allCucumberArgs.toArray(), " "); } void execute(); CucumberTask cucumber(String args); }### Answer: @Test public void shouldAddCucumberArgs() { String cucumberArg = "testArg"; mojo.cucumberArgs = new ArrayList<String>(); mojo.cucumberArgs.add(cucumberArg); assertTrue(mojo.allCucumberArgs().contains(cucumberArg)); } @Test public void shouldAllowZeroAddCucumberArgs() { mojo.extraCucumberArgs = null; mojo.allCucumberArgs(); } @Test public void shouldSplitAddCucumberArgsIntoRealCucumberArgs() { mojo.extraCucumberArgs = "arg1 arg2 arg3"; assertEquals("arg1 arg2 arg3 features", mojo.allCucumberArgs()); }
### Question: Utils { public static Locale localeFor(String isoString) { String[] languageAndCountry = isoString.split("-"); if (languageAndCountry.length == 1) { return new Locale(isoString); } else { return new Locale(languageAndCountry[0], languageAndCountry[1]); } } static String join(Object[] objects, String separator); static Class<?>[] objectClassArray(int n); static Locale localeFor(String isoString); }### Answer: @Test public void shouldCreateUSLocale() { assertEquals(Locale.US, Utils.localeFor("en-US")); } @Test public void shouldFormatLolcatDoubles() throws ParseException { assertEquals(10.4, NumberFormat.getInstance(Utils.localeFor("en-LOL")).parse("10.4").doubleValue(), 0.0); } @Test public void shouldFormatEnglishDoubles() throws ParseException { assertEquals(10.4, NumberFormat.getInstance(Utils.localeFor("en-US")).parse("10.4").doubleValue(), 0.0); } @Test public void shouldFormatNorwegianDoubles() throws ParseException { assertEquals(10.4, NumberFormat.getInstance(Utils.localeFor("no")).parse("10,4").doubleValue(), 0.0); } @Test public void shouldFormatNorwegianDoublesWithEnglishLocaleDifferently() throws ParseException { assertEquals(104.0, NumberFormat.getInstance(Utils.localeFor("en-US")).parse("10,4").doubleValue(), 0.0); } @Test public void shouldCreateEnglishLocale() { assertEquals(Locale.ENGLISH, Utils.localeFor("en")); }
### Question: CucumberMojo extends AbstractJRubyMojo { public CucumberTask cucumber(String args) throws MojoExecutionException { CucumberTask cucumber = new CucumberTask(); cucumber.setProject(getProject()); for (String jvmArg : getJvmArgs()) { if (jvmArg != null) { Commandline.Argument arg = cucumber.createJvmarg(); arg.setValue(jvmArg); } } cucumber.setArgs(args); return cucumber; } void execute(); CucumberTask cucumber(String args); }### Answer: @Test public void shouldIgnoreNullJvmArg() throws MojoExecutionException { mojo.jvmArgs = Arrays.asList("-Dfoo=bar", null, ""); assertEquals(Arrays.asList("-Dfoo=bar", ""), Arrays.asList(mojo.cucumber("").getCommandLine().getVmCommand().getArguments())); }
### Question: MethodFormat { public String format(Method method) { String signature = method.toGenericString(); Matcher matcher = METHOD_PATTERN.matcher(signature); if (matcher.find()) { String M = matcher.group(1); String r = matcher.group(2); String qc = matcher.group(3); String m = matcher.group(4); String qa = matcher.group(5); String qe = matcher.group(6); String c = qc.replaceAll(PACKAGE_PATTERN, ""); String a = qa.replaceAll(PACKAGE_PATTERN, ""); String e = qe.replaceAll(PACKAGE_PATTERN, ""); return format.format(new Object[]{ M, r, qc, m, qa, qe, c, a, e }); } else { throw new RuntimeException("Cuke4Duke bug: Couldn't format " + signature); } } MethodFormat(String format); String format(Method method); }### Answer: @Test public void shouldUseSimpleFormatWhenMethodHasException() { assertEquals("MethodFormatTest.methodWithArgsAndException(String,Map)", new MethodFormat("%c.%m(%a)").format(methodWithArgsAndException)); } @Test public void shouldUseSimpleFormatWhenMethodHasNoException() { assertEquals("MethodFormatTest.methodWithoutArgs()", new MethodFormat("%c.%m(%a)").format(methodWithoutArgs)); }
### Question: MethodInvoker { public Object invoke(Method method, Object target, Object[] javaArgs) throws Throwable { try { if (method.isAnnotationPresent(Pending.class)) { throw exceptionFactory.cucumberPending(method.getAnnotation(Pending.class).value()); } else { return method.invoke(target, javaArgs); } } catch (IllegalArgumentException e) { String m = "Couldn't invokeWithArgs " + method.toGenericString() + " with " + cuke4duke.internal.Utils.join(javaArgs, ","); throw exceptionFactory.cucumberArityMismatchError(m); } catch (InvocationTargetException e) { throw e.getTargetException(); } } MethodInvoker(ExceptionFactory exceptionFactory); Object invoke(Method method, Object target, Object[] javaArgs); }### Answer: @Test(expected = org.jruby.exceptions.RaiseException.class) public void shouldRaiseCucumberPendingWhenAnnotatedWithPending() throws Throwable { Method dontExecuteMe = SomethingWithPending.class.getDeclaredMethod("dontExecuteMe"); MethodInvoker mi = new MethodInvoker(new JRubyExceptionFactory()); mi.invoke(dontExecuteMe, new SomethingWithPending(), new Object[0]); }
### Question: ClassLanguage extends AbstractProgrammingLanguage { @Override public void load_code_file(String classFile) throws Throwable { Class<?> clazz = loadClass(classFile); addClass(clazz); } ClassLanguage(ClassLanguageMixin languageMixin, ExceptionFactory exceptionFactory, StepMother stepMother, List<ClassAnalyzer> analyzers); ClassLanguage(ClassLanguageMixin languageMixin, ExceptionFactory exceptionFactory, StepMother stepMother, List<ClassAnalyzer> analyzers, ObjectFactory objectFactory); void addTransform(Class<?> returnType, Transformable javaTransform); @Override void load_code_file(String classFile); void addClass(Class<?> clazz); @Override void begin_scenario(Scenario scenario); @Override void end_scenario(); Object invokeHook(Method method, Scenario scenario); Object invoke(Method method, Object[] args, Locale locale); List<Class<?>> getClasses(); }### Answer: @Test public void shouldLoadExistingClassFromJavaFileName() throws Throwable { language.load_code_file("foo/java/lang/String.class"); } @Test(expected = ClassNotFoundException.class) public void shouldFailToLoadMissingClassFromJavaFileName() throws Throwable { language.load_code_file("foo/java/lang/Strix.class"); }
### Question: SubjectMapperDecorator implements SubjectMapper { @Override public List<SubjectDto> questionsToSubjectsDto(List<Question> questions) { Assert.notNull(questions, "Cannot map a null list of questions to a list of subject dtos"); Multimap<Subject, Question> multimap = Multimaps.index(questions, Question::getSubject); return multimap.keySet().stream().map(subject -> { SubjectDto subjectDto = delegate.toDto(subject); List<QuestionDto> questionsDtos = multimap.get(subject).stream() .map(question -> questionMapper.questionToQuestionDto(question)).collect(Collectors.toList()); subjectDto.addQuestions(questionsDtos); return subjectDto; }).collect(Collectors.toList()); } @Override List<SubjectDto> questionsToSubjectsDto(List<Question> questions); }### Answer: @Test public void questionsToSubjectsDto() throws Exception { Question q1 = new Question().id(1L).label("question1").subject(new Subject().id(1L)); Question q2 = new Question().id(2L).label("question2").subject(new Subject().id(1L)); Question q3 = new Question().id(3L).label("question3").subject(new Subject().id(2L)); List<SubjectDto> subjects = subjectMapper.questionsToSubjectsDto(Arrays.asList(q1, q2, q3)); Assert.assertNotNull(subjects); Assert.assertEquals(subjects.size(), 2); subjects.forEach((this::assertSubjectDtoAndItsQuestionsNotNull)); }
### Question: Timing { public void start() { if (!started) { cur = systemTime(); started = true; } } Timing(); void start(); void stop(); void restart(); void pause(); void unpause(); boolean elapsed(long time); long elapsed(); void set(long value); long get(); boolean isStarted(); }### Answer: @Test void testStart() { assertFalse(timing.isStarted()); assertEquals(0L, timing.elapsed()); assertFalse(timing.elapsed(-1L)); assertFalse(timing.elapsed(0L)); assertFalse(timing.elapsed(1L)); assertEquals(0L, timing.get()); timing.start(); final long time = timing.get(); assertTrue(timing.isStarted()); UtilTests.pause(PAUSE); assertFalse(timing.elapsed(PAUSE * Constant.HUNDRED), String.valueOf(timing.elapsed())); assertTrue(timing.elapsed() >= PAUSE, String.valueOf(timing.elapsed())); assertTrue(timing.elapsed(PAUSE), String.valueOf(timing.elapsed())); assertEquals(time, timing.get(), time + " " + timing.elapsed()); timing.start(); UtilTests.pause(PAUSE); assertTrue(timing.elapsed() >= PAUSE, String.valueOf(timing.elapsed())); assertTrue(timing.elapsed(PAUSE), String.valueOf(timing.elapsed())); assertEquals(time, timing.get(), time + " " + timing.elapsed()); }
### Question: AudioFactory { public static synchronized void clearFormats() { FACTORIES.forEach((extension, format) -> format.close()); FACTORIES.clear(); } private AudioFactory(); static synchronized Audio loadAudio(Media media); static synchronized A loadAudio(Media media, Class<A> type); static synchronized void addFormat(AudioFormat format); static synchronized void clearFormats(); static final String ERROR_FORMAT; }### Answer: @Test void testClearFormats() { AudioFactory.addFormat(new AudioVoidFormat(Arrays.asList("png"))); assertNotNull(AudioFactory.loadAudio(Medias.create("image.png"))); AudioFactory.clearFormats(); assertThrows(() -> AudioFactory.loadAudio(Medias.create("image.png")), "[image.png] " + AudioFactory.ERROR_FORMAT); }
### Question: UtilColor { public static double getDelta(ColorRgba a, ColorRgba b) { Check.notNull(a); Check.notNull(b); final int dr = a.getRed() - b.getRed(); final int dg = a.getGreen() - b.getGreen(); final int db = a.getBlue() - b.getBlue(); return Math.sqrt(dr * dr + dg * dg + db * db); } private UtilColor(); static int getRgbaValue(int r, int g, int b, int a); static int multiplyRgb(int rgb, double fr, double fg, double fb); static int inc(int value, int r, int g, int b); static double getDelta(ColorRgba a, ColorRgba b); static ColorRgba getWeightedColor(ImageBuffer surface, int sx, int sy, int width, int height); static boolean isOpaqueTransparentExclusive(ColorRgba colorA, ColorRgba colorB); static boolean isOpaqueTransparentExclusive(int colorA, int colorB); }### Answer: @Test void testDelta() { assertEquals(Math.sqrt(255 * 255 + 255 * 255 + 255 * 255), UtilColor.getDelta(ColorRgba.BLACK, ColorRgba.WHITE)); assertEquals(0.0, UtilColor.getDelta(ColorRgba.GRAY, ColorRgba.GRAY)); }
### Question: Raster { public static Raster load(Media media) { Check.notNull(media); final Xml root = new Xml(media); final RasterData dataRed = RasterData.load(root, ATT_RED); final RasterData dataGreen = RasterData.load(root, ATT_GREEN); final RasterData dataBlue = RasterData.load(root, ATT_BLUE); return new Raster(dataRed, dataGreen, dataBlue); } Raster(RasterData red, RasterData green, RasterData blue); static Raster load(Media media); RasterData getRed(); RasterData getGreen(); RasterData getBlue(); }### Answer: @Test void testLoad() { assertNotNull(Raster.load(Medias.create("raster.xml"))); } @Test void testLoadFailure() { assertThrows(() -> Raster.load(Medias.create("rasterError.xml")), "Node not found: lionengine:red"); }
### Question: UtilSequence { public static Sequencable create(Class<? extends Sequencable> nextSequence, Context context, Object... arguments) { Check.notNull(nextSequence); Check.notNull(context); Check.notNull(arguments); try { final Class<?>[] params = getParamTypes(context, arguments); return UtilReflection.create(nextSequence, params, getParams(context, arguments)); } catch (final NoSuchMethodException exception) { throw new LionEngineException(exception); } } private UtilSequence(); static Sequencable create(Class<? extends Sequencable> nextSequence, Context context, Object... arguments); static void pause(long delay); }### Answer: @Test void testCreateSequence() { assertNotNull(UtilSequence.create(SequenceSingleMock.class, CONTEXT)); } @Test void testCreateSequenceArgument() { assertNotNull(UtilSequence.create(SequenceArgumentsMock.class, CONTEXT, new Object())); } @Test void testCreateSequenceArgumentFail() { final String message = NoSuchMethodException.class.getName() + ": No compatible constructor found for " + SequenceSingleMock.class.getName() + " with: [class com.b3dgs.lionengine.graphic.engine.UtilSequenceTest$1, " + "class java.lang.Object]"; assertThrows(() -> UtilSequence.create(SequenceSingleMock.class, CONTEXT, new Object()), message); }
### Question: UtilSequence { public static void pause(long delay) { try { Thread.sleep(delay); } catch (@SuppressWarnings("unused") final InterruptedException exception) { Thread.currentThread().interrupt(); } } private UtilSequence(); static Sequencable create(Class<? extends Sequencable> nextSequence, Context context, Object... arguments); static void pause(long delay); }### Answer: @Test void testPause() { final Timing timing = new Timing(); assertTrue(timing.elapsed() == 0, String.valueOf(timing.elapsed())); timing.start(); UtilSequence.pause(Constant.HUNDRED); assertTrue(timing.elapsed() > 0, String.valueOf(timing.elapsed())); } @Test void testPauseInterrupted() { final Timing timing = new Timing(); timing.start(); final Thread thread = new Thread(() -> UtilSequence.pause(Constant.THOUSAND)); thread.start(); thread.interrupt(); assertTrue(timing.elapsed() < Constant.THOUSAND, String.valueOf(timing.elapsed())); }
### Question: LoopUnlocked implements Loop { @Override public void start(Screen screen, Frame frame) { Check.notNull(screen); Check.notNull(frame); isRunning = true; while (isRunning) { if (screen.isReady()) { final long lastTime = System.nanoTime(); frame.update(Constant.EXTRP); screen.preUpdate(); frame.render(); screen.update(); frame.computeFrameRate(lastTime, Math.max(lastTime + 1, System.nanoTime())); } else { frame.check(); UtilSequence.pause(Constant.DECADE); } } } LoopUnlocked(); @Override void start(Screen screen, Frame frame); @Override void stop(); @Override void notifyRateChanged(int rate); }### Answer: @Test void testLoop() { ScreenMock.setScreenWait(false); final Screen screen = new ScreenMock(new Config(new Resolution(320, 240, 50), 16, true)); final Thread thread = getTask(screen); thread.start(); assertTimeout(1000L, thread::join); assertEquals(maxTick.get(), tick.get()); assertEquals(tick.get(), rendered.get()); assertTrue(computed.get() >= screen.getConfig().getOutput().getRate(), String.valueOf(computed.get())); }
### Question: RenderableVoid { public static Renderable getInstance() { return INSTANCE; } private RenderableVoid(); static Renderable getInstance(); }### Answer: @Test void testGetInstance() { assertNotNull(RenderableVoid.getInstance()); } @Test void testRender() { RenderableVoid.getInstance().render(null); }
### Question: ImageInfo { private ImageInfo() { throw new LionEngineException(LionEngineException.ERROR_PRIVATE_CONSTRUCTOR); } private ImageInfo(); static ImageHeader get(Media media); static boolean isImage(Media media); }### Answer: @Test void testImageInfo() { testImageInfo(ImageFormat.PNG, 1); testImageInfo(ImageFormat.GIF, 1); testImageInfo(ImageFormat.BMP, 1); testImageInfo(ImageFormat.JPG, 3); testImageInfo(ImageFormat.TIFF, 2); final ImageHeader info = ImageInfo.get(Medias.create("image.tif")); assertEquals(64, info.getWidth()); assertEquals(32, info.getHeight()); assertEquals(ImageFormat.TIFF, info.getFormat()); assertThrows(() -> ImageInfo.get(Medias.create("image2.tiff")), "[image2.tiff] " + ImageInfo.ERROR_READ); assertFalse(ImageInfo.isImage(Medias.create("raster.xml"))); }
### Question: Graphics { public static ImageBuffer createImageBuffer(int width, int height) { return factoryGraphic.createImageBuffer(width, height); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testInvalidImageWidth() { assertThrows(() -> Graphics.createImageBuffer(0, 1), "Invalid argument: 0 is not strictly superior to 0"); } @Test void testInvalidImageHeight() { assertThrows(() -> Graphics.createImageBuffer(1, 0), "Invalid argument: 0 is not strictly superior to 0"); } @Test void testCreateImageBuffer() { final ImageBuffer imageBuffer = Graphics.createImageBuffer(16, 32); assertEquals(16, imageBuffer.getWidth()); assertEquals(32, imageBuffer.getHeight()); imageBuffer.dispose(); } @Test void testCreateImageBufferTransparentColor() { final ImageBuffer imageBuffer = Graphics.createImageBuffer(16, 32, ColorRgba.TRANSPARENT); assertEquals(16, imageBuffer.getWidth()); assertEquals(32, imageBuffer.getHeight()); assertEquals(Transparency.BITMASK, imageBuffer.getTransparency()); imageBuffer.dispose(); }
### Question: Graphics { public static Screen createScreen(Config config) { return factoryGraphic.createScreen(config); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testCreateScreen() { assertNotNull(Graphics.createScreen(new Config(UtilTests.RESOLUTION_320_240, 32, true))); }
### Question: Graphics { public static Text createText(int size) { return factoryGraphic.createText(Constant.FONT_SANS_SERIF, size, TextStyle.NORMAL); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testCreateText() { assertNotNull(Graphics.createText("test", 10, TextStyle.NORMAL)); assertNotNull(Graphics.createText(10)); }
### Question: Graphics { public static Transform createTransform() { return factoryGraphic.createTransform(); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testCreateTransform() { assertNotNull(Graphics.createTransform()); }
### Question: Graphics { public static ImageBuffer getImageBuffer(Media media) { return factoryGraphic.getImageBuffer(media); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testGetImageBufferFromMedia() { final Media media = Medias.create("image.png"); final ImageBuffer imageA = Graphics.getImageBuffer(media); final ImageBuffer imageB = Graphics.getImageBuffer(media); assertNotEquals(imageA, imageB); assertEquals(imageB.getWidth(), imageA.getWidth()); assertEquals(imageB.getHeight(), imageA.getHeight()); imageA.dispose(); imageB.dispose(); } @Test void testGetImageBufferFailureMedia() { assertThrows(() -> Graphics.getImageBuffer(Medias.create("null")), "[null] Error on reading image !"); } @Test void testGetImageBufferFailureWrongImage() { assertThrows(() -> Graphics.getImageBuffer(Medias.create("wrong_image.png")), "[wrong_image.png] Error on reading image !"); }
### Question: Graphics { public static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor) { return factoryGraphic.applyMask(imageBuffer, maskColor); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testApplyMask() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer mask = Graphics.applyMask(image, ColorRgba.BLACK); assertNotEquals(image, mask); assertEquals(image.getWidth(), mask.getWidth()); assertEquals(image.getHeight(), mask.getHeight()); mask.dispose(); image.dispose(); }
### Question: Graphics { public static ImageBuffer rotate(ImageBuffer image, int angle) { return factoryGraphic.rotate(image, angle); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testRotate() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer rotate = Graphics.rotate(image, 90); assertNotEquals(image, rotate); assertEquals(image.getWidth(), rotate.getWidth()); assertEquals(image.getHeight(), rotate.getHeight()); rotate.dispose(); image.dispose(); }
### Question: Graphics { public static ImageBuffer resize(ImageBuffer image, int width, int height) { return factoryGraphic.resize(image, width, height); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testResize() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer resized = Graphics.resize(image, 1, 2); assertNotEquals(image, resized); assertEquals(1, resized.getWidth()); assertEquals(2, resized.getHeight()); resized.dispose(); image.dispose(); }
### Question: Graphics { public static ImageBuffer flipHorizontal(ImageBuffer image) { return factoryGraphic.flipHorizontal(image); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testFlipHorizontal() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer horizontal = Graphics.flipHorizontal(image); assertNotEquals(image, horizontal); assertEquals(image.getWidth(), horizontal.getWidth()); assertEquals(image.getHeight(), horizontal.getHeight()); horizontal.dispose(); image.dispose(); }
### Question: Graphics { public static ImageBuffer flipVertical(ImageBuffer image) { return factoryGraphic.flipVertical(image); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testFlipVertical() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer vertical = Graphics.flipVertical(image); assertNotEquals(image, vertical); assertEquals(image.getWidth(), vertical.getWidth()); assertEquals(image.getHeight(), vertical.getHeight()); vertical.dispose(); image.dispose(); }
### Question: Graphics { public static ImageBuffer[] splitImage(ImageBuffer image, int h, int v) { return factoryGraphic.splitImage(image, h, v); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testSplitImage() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer[] split = Graphics.splitImage(image, 2, 2); for (final ImageBuffer img1 : split) { for (final ImageBuffer img2 : split) { assertEquals(img1.getWidth(), img2.getWidth()); assertEquals(img1.getHeight(), img2.getHeight()); } } assertEquals(image.getWidth() / 2, split[0].getWidth()); assertEquals(image.getHeight() / 2, split[0].getHeight()); for (final ImageBuffer current : split) { current.dispose(); } image.dispose(); }
### Question: Graphics { public static void saveImage(ImageBuffer image, Media media) { factoryGraphic.saveImage(image, media); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testSaveImage() throws IOException { final File temp = File.createTempFile("save", ".png"); UtilFile.deleteFile(temp); final Media media = Medias.create(temp.getName()); final ImageBuffer image = Graphics.createImageBuffer(16, 32); Graphics.saveImage(image, media); assertTrue(media.exists()); image.dispose(); UtilFile.deleteFile(media.getFile()); }
### Question: Graphics { public static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb) { return factoryGraphic.getRasterBuffer(img, fr, fg, fb); } private Graphics(); static void setFactoryGraphic(FactoryGraphic factoryGraphic); static Screen createScreen(Config config); static Graphic createGraphic(); static Transform createTransform(); static Text createText(int size); static Text createText(String fontName, int size, TextStyle style); static ImageBuffer createImageBuffer(int width, int height); static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency); static ImageBuffer getImageBuffer(Media media); static ImageBuffer getImageBuffer(ImageBuffer imageBuffer); static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor); static ImageBuffer[] splitImage(ImageBuffer image, int h, int v); static ImageBuffer rotate(ImageBuffer image, int angle); static ImageBuffer resize(ImageBuffer image, int width, int height); static ImageBuffer flipHorizontal(ImageBuffer image); static ImageBuffer flipVertical(ImageBuffer image); static void saveImage(ImageBuffer image, Media media); static ImageBuffer getRasterBuffer(ImageBuffer img, double fr, double fg, double fb); }### Answer: @Test void testGetRasterBuffer() { final ImageBuffer image = Graphics.getImageBuffer(Medias.create("image.png")); final ImageBuffer raster = Graphics.getRasterBuffer(image, 0, 0, 0); assertNotEquals(image, raster); assertEquals(image.getWidth(), raster.getWidth()); assertEquals(image.getHeight(), raster.getHeight()); raster.dispose(); image.dispose(); }
### Question: ColorRgba { @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || object.getClass() != getClass()) { return false; } final ColorRgba color = (ColorRgba) object; return color.value == value; } ColorRgba(int r, int g, int b); ColorRgba(int r, int g, int b, int a); ColorRgba(int value); int getRgba(); int getRed(); int getGreen(); int getBlue(); int getAlpha(); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); static final ColorRgba RED; static final ColorRgba GREEN; static final ColorRgba BLUE; static final ColorRgba CYAN; static final ColorRgba PURPLE; static final ColorRgba YELLOW; static final ColorRgba WHITE; static final ColorRgba GRAY_LIGHT; static final ColorRgba GRAY; static final ColorRgba GRAY_DARK; static final ColorRgba BLACK; static final ColorRgba TRANSPARENT; static final ColorRgba OPAQUE; }### Answer: @Test void testEquals() { final int step = 654_321; for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE - step; i += step) { final ColorRgba color = new ColorRgba(i); for (int j = Integer.MIN_VALUE; j < Integer.MAX_VALUE - step; j += step) { if (i != j) { assertNotEquals(color, new ColorRgba(j)); } } } assertEquals(ColorRgba.BLACK, ColorRgba.BLACK); assertNotEquals(ColorRgba.WHITE, null); assertNotEquals(ColorRgba.WHITE, new Object()); assertNotEquals(ColorRgba.WHITE, ColorRgba.BLACK); }
### Question: ColorRgba { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value; return result; } ColorRgba(int r, int g, int b); ColorRgba(int r, int g, int b, int a); ColorRgba(int value); int getRgba(); int getRed(); int getGreen(); int getBlue(); int getAlpha(); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); static final ColorRgba RED; static final ColorRgba GREEN; static final ColorRgba BLUE; static final ColorRgba CYAN; static final ColorRgba PURPLE; static final ColorRgba YELLOW; static final ColorRgba WHITE; static final ColorRgba GRAY_LIGHT; static final ColorRgba GRAY; static final ColorRgba GRAY_DARK; static final ColorRgba BLACK; static final ColorRgba TRANSPARENT; static final ColorRgba OPAQUE; }### Answer: @Test void testHashCode() { assertHashEquals(ColorRgba.BLACK, ColorRgba.BLACK); assertHashNotEquals(ColorRgba.WHITE, new Object()); assertHashNotEquals(ColorRgba.WHITE, ColorRgba.BLACK); }
### Question: ColorRgba { @Override public String toString() { return new StringBuilder(MIN_LENGHT).append(getClass().getSimpleName()) .append(" [r=") .append(valueRed) .append(", g=") .append(valueGreen) .append(", b=") .append(valueBlue) .append(", a=") .append(valueAlpha) .append("]") .toString(); } ColorRgba(int r, int g, int b); ColorRgba(int r, int g, int b, int a); ColorRgba(int value); int getRgba(); int getRed(); int getGreen(); int getBlue(); int getAlpha(); @Override int hashCode(); @Override boolean equals(Object object); @Override String toString(); static final ColorRgba RED; static final ColorRgba GREEN; static final ColorRgba BLUE; static final ColorRgba CYAN; static final ColorRgba PURPLE; static final ColorRgba YELLOW; static final ColorRgba WHITE; static final ColorRgba GRAY_LIGHT; static final ColorRgba GRAY; static final ColorRgba GRAY_DARK; static final ColorRgba BLACK; static final ColorRgba TRANSPARENT; static final ColorRgba OPAQUE; }### Answer: @Test void testToString() { assertEquals("ColorRgba [r=100, g=150, b=200, a=255]", new ColorRgba(100, 150, 200, 255).toString()); }
### Question: UtilReflection { public static <T> T create(Class<T> type, Class<?>[] paramTypes, Object... params) throws NoSuchMethodException { Check.notNull(type); Check.notNull(paramTypes); Check.notNull(params); final Constructor<T> constructor = getCompatibleConstructor(type, paramTypes); return create(type, constructor, params); } private UtilReflection(); static T create(Class<T> type, Class<?>[] paramTypes, Object... params); @SuppressWarnings("unchecked") static T createReduce(Class<T> type, Object... params); static Class<?>[] getParamTypes(Object... arguments); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructor(Class<T> type, Class<?>... paramTypes); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes); static T getMethod(Object object, String name, Object... params); static T getField(Object object, String name); static void setAccessible(AccessibleObject object, boolean accessible); static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base); }### Answer: @Test void testCreate() throws NoSuchMethodException { assertEquals("1", UtilReflection.create(String.class, UtilReflection.getParamTypes(String.class), "1")); } @Test void testCreateConstructorNotAccessible() { assertThrows(() -> UtilReflection.create(UtilMath.class, new Class[0]), UtilReflection.ERROR_CONSTRUCTOR + UtilMath.class); }
### Question: UtilReflection { public static void setAccessible(AccessibleObject object, boolean accessible) { Check.notNull(object); if (object.isAccessible() != accessible) { java.security.AccessController.doPrivileged((PrivilegedAction<Void>) () -> { object.setAccessible(accessible); return null; }); } } private UtilReflection(); static T create(Class<T> type, Class<?>[] paramTypes, Object... params); @SuppressWarnings("unchecked") static T createReduce(Class<T> type, Object... params); static Class<?>[] getParamTypes(Object... arguments); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructor(Class<T> type, Class<?>... paramTypes); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes); static T getMethod(Object object, String name, Object... params); static T getField(Object object, String name); static void setAccessible(AccessibleObject object, boolean accessible); static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base); }### Answer: @Test void testSetAccessible() { final AccessibleObject accessible = AccessibleTest.class.getDeclaredFields()[0]; assertFalse(accessible.isAccessible()); UtilReflection.setAccessible(accessible, true); assertTrue(accessible.isAccessible()); UtilReflection.setAccessible(accessible, false); assertFalse(accessible.isAccessible()); UtilReflection.setAccessible(accessible, false); assertFalse(accessible.isAccessible()); }
### Question: UtilReflection { public static Class<?>[] getParamTypes(Object... arguments) { Check.notNull(arguments); final Collection<Object> types = new ArrayList<>(arguments.length); for (final Object argument : arguments) { if (argument.getClass() == Class.class) { types.add(argument); } else { types.add(argument.getClass()); } } final Class<?>[] typesArray = new Class<?>[types.size()]; return types.toArray(typesArray); } private UtilReflection(); static T create(Class<T> type, Class<?>[] paramTypes, Object... params); @SuppressWarnings("unchecked") static T createReduce(Class<T> type, Object... params); static Class<?>[] getParamTypes(Object... arguments); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructor(Class<T> type, Class<?>... paramTypes); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes); static T getMethod(Object object, String name, Object... params); static T getField(Object object, String name); static void setAccessible(AccessibleObject object, boolean accessible); static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base); }### Answer: @Test void testGetParamTypes() { final Collection<Object> params = new ArrayList<>(); params.add(Integer.valueOf(1)); params.add("test"); params.add(Double.valueOf(5.2)); params.add(Float.class); final Class<?>[] types = UtilReflection.getParamTypes(params.toArray()); assertEquals(Integer.class, types[0]); assertEquals(String.class, types[1]); assertEquals(Double.class, types[2]); assertEquals(Float.class, types[3]); }
### Question: UtilReflection { public static <T> T getField(Object object, String name) { Check.notNull(object); Check.notNull(name); try { final Class<?> clazz = getClass(object); final Field field = getDeclaredFieldSuper(clazz, name); setAccessible(field, true); @SuppressWarnings("unchecked") final T value = (T) field.get(object); return value; } catch (final NoSuchFieldException | IllegalAccessException exception) { throw new LionEngineException(exception, ERROR_FIELD + name); } } private UtilReflection(); static T create(Class<T> type, Class<?>[] paramTypes, Object... params); @SuppressWarnings("unchecked") static T createReduce(Class<T> type, Object... params); static Class<?>[] getParamTypes(Object... arguments); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructor(Class<T> type, Class<?>... paramTypes); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes); static T getMethod(Object object, String name, Object... params); static T getField(Object object, String name); static void setAccessible(AccessibleObject object, boolean accessible); static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base); }### Answer: @Test void testGetField() { assertNotNull(UtilReflection.getField(new Config(new Resolution(320, 240, 32), 16, false), "output")); } @Test void testGetFieldAccessible() { assertNotNull(UtilReflection.getField(LionEngineException.class, "ERROR_PRIVATE_CONSTRUCTOR")); } @Test void testGetFieldNotAccessible() { assertNotNull(UtilReflection.getField(Verbose.class, "LOGGER")); } @Test void testGetFieldSuperClass() { final String accessible = UtilReflection.getField(FieldTest2.class, "test"); assertNotNull(accessible); } @Test void testGetFieldUnknown() { assertThrows(() -> UtilReflection.getField(new Object(), "0"), UtilReflection.ERROR_FIELD + "0"); }
### Question: UtilReflection { @SuppressWarnings("unchecked") public static <T> Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes) throws NoSuchMethodException { Check.notNull(type); Check.notNull(paramTypes); for (final Constructor<?> current : type.getDeclaredConstructors()) { final Class<?>[] constructorTypes = current.getParameterTypes(); if (constructorTypes.length == paramTypes.length && hasCompatibleConstructorParent(paramTypes, constructorTypes)) { return (Constructor<T>) current; } } throw new NoSuchMethodException(ERROR_NO_CONSTRUCTOR_COMPATIBLE + type.getName() + ERROR_WITH + Arrays.asList(paramTypes)); } private UtilReflection(); static T create(Class<T> type, Class<?>[] paramTypes, Object... params); @SuppressWarnings("unchecked") static T createReduce(Class<T> type, Object... params); static Class<?>[] getParamTypes(Object... arguments); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructor(Class<T> type, Class<?>... paramTypes); @SuppressWarnings("unchecked") static Constructor<T> getCompatibleConstructorParent(Class<T> type, Class<?>[] paramTypes); static T getMethod(Object object, String name, Object... params); static T getField(Object object, String name); static void setAccessible(AccessibleObject object, boolean accessible); static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base); }### Answer: @Test void testGetCompatibleConstructorParent() throws NoSuchMethodException { assertNotNull(UtilReflection.getCompatibleConstructorParent(String.class, UtilReflection.getParamTypes(new Object()))); }
### Question: Timing { public void stop() { cur = 0L; started = false; } Timing(); void start(); void stop(); void restart(); void pause(); void unpause(); boolean elapsed(long time); long elapsed(); void set(long value); long get(); boolean isStarted(); }### Answer: @Test void testStop() { timing.start(); UtilTests.pause(PAUSE); timing.stop(); assertFalse(timing.isStarted()); assertEquals(0L, timing.get()); assertFalse(timing.elapsed(PAUSE), String.valueOf(timing.elapsed())); }
### Question: UtilStream { public static void copy(InputStream source, OutputStream destination) throws IOException { Check.notNull(source); Check.notNull(destination); final byte[] buffer = new byte[BUFFER_COPY]; while (true) { final int read = source.read(buffer); if (read == -1) { break; } destination.write(buffer, 0, read); } } private UtilStream(); static void copy(InputStream source, OutputStream destination); static File getCopy(String name, InputStream input); }### Answer: @Test void testCopy() throws IOException { final Path temp1 = Files.createTempFile("temp", ".tmp"); final Path temp2 = Files.createTempFile("temp", ".tmp"); try (InputStream input = new FileInputStream(temp1.toFile()); OutputStream output = new FileOutputStream(temp2.toFile())) { output.write(1); output.flush(); UtilStream.copy(input, output); } finally { Files.delete(temp1); Files.delete(temp2); } } @Test void testCopyNullInput() throws IOException { try (OutputStream output = new OutputStreamMock()) { assertThrows(() -> UtilStream.copy(null, output), Check.ERROR_NULL); } } @Test void testCopyNullOutput() throws IOException { try (InputStream input = new InputStreamMock()) { assertThrows(() -> UtilStream.copy(input, null), Check.ERROR_NULL); } }
### Question: UtilStream { public static File getCopy(String name, InputStream input) { Check.notNull(name); Check.notNull(input); final String prefix; final String suffix; final int minimumPrefix = 3; final int i = name.lastIndexOf(Constant.DOT); if (i > minimumPrefix) { prefix = name.substring(0, i); suffix = name.substring(i); } else { if (name.length() > minimumPrefix) { prefix = name; } else { prefix = PREFIX_TEMP; } suffix = null; } try { final File temp = File.createTempFile(prefix, suffix); try (OutputStream output = new BufferedOutputStream(new FileOutputStream(temp))) { copy(input, output); } return temp; } catch (final IOException exception) { throw new LionEngineException(exception, ERROR_TEMP_FILE + name); } } private UtilStream(); static void copy(InputStream source, OutputStream destination); static File getCopy(String name, InputStream input); }### Answer: @Test void testGetCopy() throws IOException { try (InputStream input = new InputStreamMock()) { assertTrue(UtilStream.getCopy("te", input).delete()); assertTrue(UtilStream.getCopy("temp", input).delete()); assertTrue(UtilStream.getCopy("temp.tmp", input).delete()); } } @Test void testGetCopyNullName() throws IOException { try (InputStream input = new InputStreamMock()) { assertThrows(() -> UtilStream.getCopy(null, input), Check.ERROR_NULL); } } @Test void testGetCopyNullStream() throws IOException { assertThrows(() -> UtilStream.getCopy("temp", null), Check.ERROR_NULL); } @Test void testGetCopyError() { assertThrows(() -> UtilStream.getCopy("copy", new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }), UtilStream.ERROR_TEMP_FILE + "copy"); }
### Question: UtilRandom { public static int getRandomInteger() { return RANDOM.nextInt(); } private UtilRandom(); static void setSeed(long seed); static int getRandomInteger(); static int getRandomInteger(int max); static int getRandomInteger(Range range); static int getRandomInteger(int min, int max); static boolean getRandomBoolean(); static double getRandomDouble(); }### Answer: @Test void testGetRandomIntegerNullRange() { assertThrows(() -> UtilRandom.getRandomInteger(null), Check.ERROR_NULL); }
### Question: Medias { public static Media getWithSuffix(Media media, String suffix) { Check.notNull(media); Check.notNull(suffix); final String path = media.getPath(); final int dotIndex = path.lastIndexOf(Constant.DOT); if (dotIndex > -1) { return Medias.create(path.substring(0, dotIndex) + Constant.UNDERSCORE + suffix + path.substring(dotIndex)); } return Medias.create(path + Constant.UNDERSCORE + suffix); } private Medias(); static synchronized Media create(String... path); static synchronized void setFactoryMedia(FactoryMedia factoryMedia); static synchronized void setResourcesDirectory(String directory); static synchronized void setLoadFromJar(Class<?> clazz); static synchronized Media get(File file); static synchronized List<Media> getByExtension(String extension, Media folder); static List<Media> getByExtension(File jar, String fullPath, int prefixLength, String extension); static Media getWithSuffix(Media media, String suffix); static synchronized String getResourcesDirectory(); static synchronized Optional<Class<?>> getResourcesLoader(); static synchronized File getJarResources(); static synchronized String getJarResourcesPrefix(); static String getSeparator(); }### Answer: @Test void testGetWithSuffix() { Medias.setResourcesDirectory(oldDir); final Media folder = Medias.create("folder", "foo"); final Media file = Medias.create("folder", "file.txt"); assertEquals(Medias.create("folder", "foo_suffix"), Medias.getWithSuffix(folder, "suffix")); assertEquals(Medias.create("folder", "file_suffix.txt"), Medias.getWithSuffix(file, "suffix")); }
### Question: Medias { public static synchronized File getJarResources() { if (!loader.isPresent()) { throw new LionEngineException(JAR_LOADER_ERROR); } final Media media = Medias.create(Constant.EMPTY_STRING); final String path = media.getFile().getPath().replace(File.separator, Constant.SLASH); final String prefix = loader.get().getPackage().getName().replace(Constant.DOT, Constant.SLASH); final int jarSeparatorIndex = path.indexOf(prefix); final String jar = path.substring(0, jarSeparatorIndex); return new File(jar); } private Medias(); static synchronized Media create(String... path); static synchronized void setFactoryMedia(FactoryMedia factoryMedia); static synchronized void setResourcesDirectory(String directory); static synchronized void setLoadFromJar(Class<?> clazz); static synchronized Media get(File file); static synchronized List<Media> getByExtension(String extension, Media folder); static List<Media> getByExtension(File jar, String fullPath, int prefixLength, String extension); static Media getWithSuffix(Media media, String suffix); static synchronized String getResourcesDirectory(); static synchronized Optional<Class<?>> getResourcesLoader(); static synchronized File getJarResources(); static synchronized String getJarResourcesPrefix(); static String getSeparator(); }### Answer: @Test void testGetJarResources() { Medias.setLoadFromJar(MediasTest.class); final File folder = Medias.create(com.b3dgs.lionengine.Constant.EMPTY_STRING).getFile(); final String prefix = Medias.getResourcesLoader() .get() .getPackage() .getName() .replace(Constant.DOT, Constant.SLASH); final String jarPath = folder.getPath().replace(File.separator, Constant.SLASH); final int jarSeparatorIndex = jarPath.indexOf(prefix); final File jar = Medias.getJarResources(); assertEquals(new File(jarPath.substring(0, jarSeparatorIndex)), jar); }
### Question: Medias { public static synchronized String getJarResourcesPrefix() { if (!loader.isPresent()) { throw new LionEngineException(JAR_LOADER_ERROR); } final Media media = Medias.create(Constant.EMPTY_STRING); final String path = media.getFile().getPath().replace(File.separator, Constant.SLASH); final String prefix = loader.get().getPackage().getName().replace(Constant.DOT, Constant.SLASH); final int jarSeparatorIndex = path.indexOf(prefix); return path.substring(jarSeparatorIndex).replace(File.separator, Constant.SLASH); } private Medias(); static synchronized Media create(String... path); static synchronized void setFactoryMedia(FactoryMedia factoryMedia); static synchronized void setResourcesDirectory(String directory); static synchronized void setLoadFromJar(Class<?> clazz); static synchronized Media get(File file); static synchronized List<Media> getByExtension(String extension, Media folder); static List<Media> getByExtension(File jar, String fullPath, int prefixLength, String extension); static Media getWithSuffix(Media media, String suffix); static synchronized String getResourcesDirectory(); static synchronized Optional<Class<?>> getResourcesLoader(); static synchronized File getJarResources(); static synchronized String getJarResourcesPrefix(); static String getSeparator(); }### Answer: @Test void testGetJarResourcesPrefix() { Medias.setLoadFromJar(MediasTest.class); final File folder = Medias.create(com.b3dgs.lionengine.Constant.EMPTY_STRING).getFile(); final String prefix = Medias.getResourcesLoader() .get() .getPackage() .getName() .replace(Constant.DOT, Constant.SLASH); final String jarPath = folder.getPath().replace(File.separator, Constant.SLASH); final int jarSeparatorIndex = jarPath.indexOf(prefix); final String resourcesPrefix = Medias.getJarResourcesPrefix(); assertEquals(jarPath.substring(jarSeparatorIndex), resourcesPrefix); }