method2testcases
stringlengths
118
6.63k
### Question: WebDavMessage extends MimeMessage { @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(Collections.singletonList(this), Collections.singleton(flag), set); } WebDavMessage(String uid, Folder folder); void setUrl(String url); String g...
### Question: ResponseCodeExtractor { public static String getResponseCode(ImapResponse response) { if (response.size() < 2 || !response.isList(1)) { return null; } ImapList responseTextCode = response.getList(1); return responseTextCode.size() != 1 ? null : responseTextCode.getString(0); } private ResponseCodeExtract...
### Question: NamespaceResponse { public static NamespaceResponse parse(List<ImapResponse> responses) { for (ImapResponse response : responses) { NamespaceResponse prefix = parse(response); if (prefix != null) { return prefix; } } return null; } private NamespaceResponse(String prefix, String hierarchyDelimiter); stat...
### Question: ListResponse { public static List<ListResponse> parseList(List<ImapResponse> responses) { return parse(responses, Responses.LIST); } private ListResponse(List<String> attributes, String hierarchyDelimiter, String name); static List<ListResponse> parseList(List<ImapResponse> responses); static List<ListRe...
### Question: ListResponse { public static List<ListResponse> parseLsub(List<ImapResponse> responses) { return parse(responses, Responses.LSUB); } private ListResponse(List<String> attributes, String hierarchyDelimiter, String name); static List<ListResponse> parseList(List<ImapResponse> responses); static List<ListRe...
### Question: ImapConnection { public boolean isConnected() { return inputStream != null && outputStream != null && socket != null && socket.isConnected() && !socket.isClosed(); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory, ConnectivityManager connectivityManager, OAuth2TokenPr...
### Question: ImapConnection { public void close() { open = false; stacktraceForClose = new Exception(); untagQuietly(socket); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(socket); inputStream = null; outputStream = null; socket = null; } ImapConnection(ImapSettings settin...
### Question: ImapConnection { protected boolean isIdleCapable() { if (K9MailLib.isDebug()) { Timber.v("Connection %s has %d capabilities", getLogId(), capabilities.size()); } return capabilities.contains(Capabilities.IDLE); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory, Connect...
### Question: ImapConnection { public void sendContinuation(String continuation) throws IOException { outputStream.write(continuation.getBytes()); outputStream.write('\r'); outputStream.write('\n'); outputStream.flush(); if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) { Timber.v("%s>>> %s", getLogId(), continuation); }...
### Question: ImapConnection { public List<ImapResponse> executeSimpleCommand(String command) throws IOException, MessagingException { return executeSimpleCommand(command, false); } ImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory, ConnectivityManager connectivityManager, OAuth2Token...
### Question: FolderNameCodec { public String encode(String folderName) { ByteBuffer byteBuffer = modifiedUtf7Charset.encode(folderName); byte[] bytes = new byte[byteBuffer.limit()]; byteBuffer.get(bytes); return new String(bytes, asciiCharset); } private FolderNameCodec(); static FolderNameCodec newInstance(); String...
### Question: FolderNameCodec { public String decode(String encodedFolderName) throws CharacterCodingException { CharsetDecoder decoder = modifiedUtf7Charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT); ByteBuffer byteBuffer = ByteBuffer.wrap(encodedFolderName.getBytes(asciiCharset)); CharBuffer charBuffer ...
### Question: ImapStore extends RemoteStore { @Override @NonNull public ImapFolder getFolder(String folderId) { ImapFolder folder; synchronized (folderCache) { folder = folderCache.get(folderId); if (folder == null) { folder = new ImapFolder(this, folderId); folderCache.put(folderId, folder); } } return folder; } ImapS...
### Question: ImapStore extends RemoteStore { @Override public void checkSettings() throws MessagingException { try { ImapConnection connection = createImapConnection(); connection.open(); autoconfigureFolders(connection); connection.close(); } catch (IOException ioe) { throw new MessagingException("Unable to connect",...
### Question: ImapStore extends RemoteStore { ImapConnection getConnection() throws MessagingException { ImapConnection connection; while ((connection = pollConnection()) != null) { try { connection.executeSimpleCommand(Commands.NOOP); break; } catch (IOException ioe) { connection.close(); } } if (connection == null) {...
### Question: ImapUtility { public static List<String> getImapSequenceValues(String set) { List<String> list = new ArrayList<String>(); if (set != null) { String[] setItems = set.split(","); for (String item : setItems) { if (item.indexOf(':') == -1) { if (isNumberValid(item)) { list.add(item); } } else { list.addAll(g...
### Question: ImapUtility { public static List<String> getImapRangeValues(String range) { List<String> list = new ArrayList<String>(); try { if (range != null) { int colonPos = range.indexOf(':'); if (colonPos > 0) { long first = Long.parseLong(range.substring(0, colonPos)); long second = Long.parseLong(range.substring...
### Question: ImapPushState { public static ImapPushState parse(String pushState) { if (pushState == null || !pushState.startsWith(PUSH_STATE_PREFIX)) { return createDefaultImapPushState(); } String value = pushState.substring(PUSH_STATE_PREFIX_LENGTH); try { long newUidNext = Long.parseLong(value); return new ImapPush...
### Question: ImapPushState { @Override public String toString() { return "uidNext=" + uidNext; } ImapPushState(long uidNext); static ImapPushState parse(String pushState); @Override String toString(); final long uidNext; }### Answer: @Test public void toString_shouldReturnExpectedResult() throws Exception { ImapPushSt...
### Question: AlertResponse { public static String getAlertText(ImapResponse response) { if (response.size() < 3 || !response.isList(1)) { return null; } ImapList responseTextCode = response.getList(1); if (responseTextCode.size() != 1 || !equalsIgnoreCase(responseTextCode.get(0), ALERT_RESPONSE_CODE)) { return null; }...
### Question: CapabilityResponse { public static CapabilityResponse parse(List<ImapResponse> responses) { for (ImapResponse response : responses) { CapabilityResponse result; if (!response.isEmpty() && equalsIgnoreCase(response.get(0), Responses.OK) && response.isList(1)) { ImapList capabilityList = response.getList(1)...
### Question: PermanentFlagsResponse { public static PermanentFlagsResponse parse(ImapResponse response) { if (response.isTagged() || !equalsIgnoreCase(response.get(0), Responses.OK) || !response.isList(1)) { return null; } ImapList responseTextList = response.getList(1); if (responseTextList.size() < 2 || !equalsIgnor...
### Question: ImapResponseParser { private Object parseLiteral() throws IOException { expect('{'); int size = Integer.parseInt(readStringUntil('}')); expect('\r'); expect('\n'); if (size == 0) { return ""; } if (response.getCallback() != null) { FixedLengthInputStream fixed = new FixedLengthInputStream(inputStream, siz...
### Question: ImapResponseParser { private String parseQuoted() throws IOException { expect('"'); StringBuilder sb = new StringBuilder(); int ch; boolean escape = false; while ((ch = inputStream.read()) != -1) { if (!escape && ch == '\\') { escape = true; } else if (!escape && ch == '"') { return sb.toString(); } else ...
### Question: ImapPusher implements Pusher { @Override public void start(List<String> folderNames) { synchronized (folderPushers) { stop(); setLastRefresh(currentTimeMillis()); for (String folderName : folderNames) { ImapFolderPusher pusher = createImapFolderPusher(folderName); folderPushers.add(pusher); pusher.start()...
### Question: ImapPusher implements Pusher { @Override public void stop() { if (K9MailLib.isDebug()) { Timber.i("Requested stop of IMAP pusher"); } synchronized (folderPushers) { for (ImapFolderPusher folderPusher : folderPushers) { try { if (K9MailLib.isDebug()) { Timber.i("Requesting stop of IMAP folderPusher %s", fo...
### Question: ImapPusher implements Pusher { @Override public int getRefreshInterval() { return (store.getStoreConfig().getIdleRefreshMinutes() * 60 * 1000); } ImapPusher(ImapStore store, PushReceiver pushReceiver); @Override void start(List<String> folderNames); @Override void refresh(); @Override void stop(); @Overri...
### Question: ImapPusher implements Pusher { @Override public long getLastRefresh() { return lastRefresh; } ImapPusher(ImapStore store, PushReceiver pushReceiver); @Override void start(List<String> folderNames); @Override void refresh(); @Override void stop(); @Override int getRefreshInterval(); @Override long getLastR...
### Question: ImapList extends ArrayList<Object> { public boolean containsKey(String key) { if (key == null) { return false; } for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return true; } } return false; } ImapList getList(int index); boolean isList(int i...
### Question: ImapList extends ArrayList<Object> { public Object getKeyedValue(String key) { for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return get(i + 1); } } return null; } ImapList getList(int index); boolean isList(int index); Object getObject(int i...
### Question: ImapList extends ArrayList<Object> { public int getKeyIndex(String key) { for (int i = 0, count = size() - 1; i < count; i++) { if (ImapResponseParser.equalsIgnoreCase(get(i), key)) { return i; } } throw new IllegalArgumentException("getKeyIndex() only works for keys that are in the collection."); } Imap...
### Question: ImapList extends ArrayList<Object> { public Date getDate(int index) throws MessagingException { return getDate(getString(index)); } ImapList getList(int index); boolean isList(int index); Object getObject(int index); String getString(int index); boolean isString(int index); long getLong(int index); int g...
### Question: ImapList extends ArrayList<Object> { public Date getKeyedDate(String key) throws MessagingException { return getDate(getKeyedString(key)); } ImapList getList(int index); boolean isList(int index); Object getObject(int index); String getString(int index); boolean isString(int index); long getLong(int inde...
### Question: SelectOrExamineResponse { public static SelectOrExamineResponse parse(ImapResponse response) { if (!response.isTagged() || !equalsIgnoreCase(response.get(0), Responses.OK)) { return null; } if (!response.isList(1)) { return noOpenModeInResponse(); } ImapList responseTextList = response.getList(1); if (!re...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public void open(int mode) throws MessagingException { internalOpen(mode); if (messageCount == -1) { throw new MessagingException("Did not find message count during open"); } } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String i...
### Question: ImapFolder extends Folder<ImapMessage> { private boolean exists(String escapedFolderName) throws MessagingException { try { connection.executeSimpleCommand(String.format("STATUS %s (RECENT)", escapedFolderName)); return true; } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } catch (...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public boolean create(FolderType type) throws MessagingException { ImapConnection connection; synchronized (this) { if (this.connection == null) { connection = store.getConnection(); } else { connection = this.connection; } } try { String encodedFolderNam...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public Map<String, String> moveMessages(List<? extends Message> messages, Folder folder) throws MessagingException { if (messages.isEmpty()) { return null; } Map<String, String> uidMapping = copyMessages(messages, folder); setFlags(messages, Collections.s...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public void delete(List<? extends Message> messages, String trashFolderName) throws MessagingException { if (messages.isEmpty()) { return; } if (trashFolderName == null || getId().equalsIgnoreCase(trashFolderName)) { setFlags(messages, Collections.singlet...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public int getUnreadMessageCount() throws MessagingException { return getRemoteMessageCount("UNSEEN NOT DELETED"); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(int...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public int getFlaggedMessageCount() throws MessagingException { return getRemoteMessageCount("FLAGGED NOT DELETED"); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(i...
### Question: ImapFolder extends Folder<ImapMessage> { protected long getHighestUid() throws MessagingException { try { String command = "UID SEARCH *:*"; List<ImapResponse> responses = executeSimpleCommand(command); SearchResponse searchResponse = SearchResponse.parse(responses); return extractHighestUid(searchRespons...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public List<ImapMessage> getMessages(int start, int end, Date earliestDate, MessageRetrievalListener<ImapMessage> listener) throws MessagingException { return getMessages(start, end, earliestDate, false, listener); } ImapFolder(ImapStore store, String id)...
### Question: ImapFolder extends Folder<ImapMessage> { protected List<ImapMessage> getMessagesFromUids(final List<String> mesgUids) throws MessagingException { ImapSearcher searcher = new ImapSearcher() { @Override public List<ImapResponse> search() throws IOException, MessagingException { String command = String.forma...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public boolean areMoreMessagesAvailable(int indexOfOldestMessage, Date earliestDate) throws IOException, MessagingException { checkOpen(); if (indexOfOldestMessage == 1) { return false; } String dateSearchString = getDateSearchString(earliestDate); int en...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public String getNewPushState(String oldSerializedPushState, Message message) { try { String uid = message.getUid(); long messageUid = Long.parseLong(uid); ImapPushState oldPushState = ImapPushState.parse(oldSerializedPushState); if (messageUid >= oldPush...
### Question: ImapFolder extends Folder<ImapMessage> { @Override public ImapMessage getMessage(String uid) throws MessagingException { return new ImapMessage(uid, this); } ImapFolder(ImapStore store, String id); ImapFolder(ImapStore store, String id, FolderNameCodec folderNameCodec); @Override void open(int mode); @O...
### Question: BoundaryGenerator { public String generateBoundary() { StringBuilder builder = new StringBuilder(4 + BOUNDARY_CHARACTER_COUNT); builder.append("----"); for (int i = 0; i < BOUNDARY_CHARACTER_COUNT; i++) { builder.append(BASE36_MAP[random.nextInt(36)]); } return builder.toString(); } @VisibleForTesting Bo...
### Question: Message implements Part, Body { @Override public boolean equals(Object o) { if (o == null || !(o instanceof Message)) { return false; } Message other = (Message)o; return (getUid().equals(other.getUid()) && getFolder().getId().equals(other.getFolder().getId())); } boolean olderThan(Date earliestDate); @O...
### Question: HttpUriParser implements UriParser { @Override public int linkifyUri(String text, int startPos, StringBuffer outputBuffer) { int currentPos = startPos; String shortScheme = text.substring(currentPos, Math.min(currentPos + 7, text.length())); String longScheme = text.substring(currentPos, Math.min(currentP...
### Question: StringCalculator { public int add(String input) { if ("".equals(input)) { return 0; } String numbers = extractNumbers(input); String delimiter = extractDelimiter(input); return stringSum(numbers, delimiter); } int add(String input); }### Answer: @Test public void TestEmptyStringReturnZero() { Assert.ass...
### Question: StringCalculator { public int add(String input) { if ("".equals(input)) return 0; String delimiter = extractDelimiter(input); String[] numberArray = extractNumbers(input, delimiter); return sumNumberArray(numberArray); } int add(String input); }### Answer: @Test public void comma_or_return_line_separate...
### Question: StringCalculator { public int add(String input) { if (input.isEmpty()) return 0; String delimiter = getDelimiter(input); String numbers = getNumbers(input); return calculateSum(numbers.split(delimiter)); } int add(String input); }### Answer: @Test public void emptyStringReturnsZero() { assertEquals(0, t...
### Question: RockPaper { public final int play(final String playerOne, final String playerTwo) { int response = DRAW; if (isDraw(playerOne, playerTwo)) { response = DRAW; } else if (PAPER.equals(playerOne)) { return checkPaperRulesPlayerOne(playerTwo); } else if (ROCK.equals(playerOne) && PAPER.equals(playerTwo)) { re...
### Question: PageAnalyzer { public static HtmlAnalysisResult analyze(Map<String, String> config, String url) { try { String userAgent = config.getOrDefault(CONFIG_USER_AGENT, DEFAULT_USER_AGENT); HttpResponse<String> response = Unirest.get(url) .header("User-Agent", userAgent) .asString(); return analyze(config, url, ...
### Question: DateParser { private static MatchedDate parseWithTimewords(MatchedDate matchedText, HttpSource source) { Timewords timewords = new Timewords(); try { Date parse = timewords.parse(matchedText.getValue(), new Date(), source.getLanguage()); if (parse != null) { matchedText.setDate(new DateTime(parse)); match...
### Question: DataUtils implements Serializable { public static List<String> parseStringList(Object object) { if (object == null) { return null; } return Splitter.onPattern("(?:\r?\n)+") .splitToList(object.toString()) .stream() .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); } static Inte...
### Question: DataUtils implements Serializable { public static String formatInUTC(DateTime date) { return date != null ? FORMATTER.print(date.toDateTime(DateTimeZone.UTC)) : null; } static Integer tryParseInteger(Object object); static Long tryParseLong(Object object); static List<String> parseStringList(Object objec...
### Question: EsHttpSourceOperations extends BaseElasticOps { public PageableList<HttpSource> filter(String text) { return filter(text, 0); } protected EsHttpSourceOperations(ElasticConnection connection, String index, String type); static EsHttpSourceOperations getInstance(ElasticConnection connection, String index, ...
### Question: ElasticConnection { public static Builder builder() { return new Builder(); } private ElasticConnection(BulkProcessor processor, RestHighLevelClient restHighLevelClient, RestClientBuilder restClient); static Builder builder(); RestHighLevelClient getRestHighLevelClient(); BulkProcessor getProcessor(); st...
### Question: QueryParser { public static List<String> parseQuery(String query) { List<String> result = Lists.newArrayList(); if (!Strings.isNullOrEmpty(query)) { query = query.replaceAll("(\\s*[+-]\\s*)", "#SPLIT#$1"); return Arrays.stream(query.split("(#SPLIT#| )")) .map(String::trim) .filter(s -> !s.isEmpty()) .coll...
### Question: UrlExtractor { private static Set<String> extract(Document document) { Set<String> canonicalUrls = new HashSet<>(); if (document == null) { return canonicalUrls; } Elements elements = document.select("meta[property=og:url]"); elements.forEach(element -> { String attr = element.attr("content"); if (attr !=...
### Question: JsonUtil { public static Map<String, String> getJsonPathsForTemplating(Set<Map.Entry<String, JsonElement>> root) { Map<String, String> paths = new HashMap<>(); searchJsonForTemplate(root, paths, "$"); return paths; } private JsonUtil(/* empty */); static boolean updateField(JsonElement json, String field...
### Question: HazelcastMapMetricsReporter extends AbstractReportingTask { boolean isValid(ObjectName name, Set<String> mapNames, String clusterName) { if (!"com.hazelcast".equals(name.getDomain())) { return false; } String propertyName = name.getKeyProperty("name"); if (!mapNames.isEmpty() && !mapNames.contains(propert...
### Question: InfluxNiFiClusterMetricsReporter extends AbstractNiFiClusterMetricsReporter { void collectMeasurements(long now, SystemMetricsSnapshot snapshot, BatchPoints points) { collectMemoryMetrics(now, snapshot, points); collectJvmMetrics(now, snapshot, points); collectDiskUsageMetrics(now, snapshot, points); coll...
### Question: CloudwatchNiFiClusterMetricsReporter extends AbstractNiFiClusterMetricsReporter { List<MetricDatum> collectMeasurements(Date now, SystemMetricsSnapshot snapshot, List<Dimension> dimensions) { List<MetricDatum> toCloudwatch = new ArrayList<>(); if (collectsMemory) { getMetrics("System Memory", snapshot.get...
### Question: ByteCode { public static void printOpCode(InstructionHandle insHandle, ConstantPoolGen cpg) { System.out.print("[" + String.format("%02d", insHandle.getPosition()) + "] "); printOpCode(insHandle.getInstruction(),cpg); } static void printOpCode(InstructionHandle insHandle, ConstantPoolGen cpg); static voi...
### Question: DoubleLinkedCountingSet { public void increment(int key) { int index = sparse[key]; if (index < elementsCount && dense[index] == key) { counts[index]++; } else { index = elementsCount++; sparse[key] = index; dense[index] = key; counts[index] = 1; } } DoubleLinkedCountingSet(int maxValue, int maxValues); v...
### Question: LangIdV3 implements ILangIdClassifier { @Override public DetectedLanguage classify(CharSequence str, boolean normalizeConfidence) { reset(); append(str); return classify(normalizeConfidence); } LangIdV3(); LangIdV3(Model model); @Override DetectedLanguage classify(CharSequence str, boolean normalizeConfi...
### Question: Model { public static Model detectOnly(Set<String> langCodes) { final Model source = defaultModel(); Set<String> newClasses = new LinkedHashSet<String>(Arrays.asList(source.langClasses)); newClasses.retainAll(langCodes); if (newClasses.size() < 2) { throw new IllegalArgumentException("A model must contain...
### Question: UserService { public User create(String name, String currency) { final User user = new User(name, currency); return userRepository.save(user); } @Autowired UserService(UserRepository userRepository, UserManagementProperties userManagementProperties); List<User> list(); User create(String name, String cur...
### Question: AccountService { public List<Account> list(long userId) { return accountRepository.findByUserId(userId); } @Autowired AccountService(AccountRepository accountRepository, UserRepository userRepository); List<Account> list(long userId); Account get(long id); Account create(long userId, String description, ...
### Question: AccountService { public Account get(long id) { return accountRepository.findOne(Example.of(new Account().setId(id))).orElse(null); } @Autowired AccountService(AccountRepository accountRepository, UserRepository userRepository); List<Account> list(long userId); Account get(long id); Account create(long us...
### Question: AccountService { public Account create(long userId, String description, boolean onBudget) { User user = userRepository.getOne(userId); Account account = new Account(description, onBudget, user); return accountRepository.saveAndFlush(account); } @Autowired AccountService(AccountRepository accountRepositor...
### Question: AccountResourceValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "description.empty"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "onBudget", "onBudget.empty"); } @Override boolean suppor...
### Question: AccountController { @GetMapping("/{accountId}") public Resource<AccountResource> get(@PathVariable("userId") long userId, @PathVariable("accountId") long accountId) { Account account = accountService.get(accountId); final AccountResource accountResource = accountResourceAssembler.toResource(account); retu...
### Question: AccountController { @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<AccountResource> create(@PathVariable("userId") long userId, @RequestBody @Valid AccountResource accountResource) { Account account = accountService.create(userId, accountResource.getDescription(), accountR...
### Question: AccountResourceAssembler extends ResourceAssemblerSupport<Account, AccountResource> { @Override public AccountResource toResource(Account entity) { final AccountResource accountResource = new AccountResource(entity.getDescription(), entity.isOnBudget()); accountResource.add(linkTo(methodOn(AccountControll...
### Question: CategorySpecifications { public Specification<Category> byUser(User user) { return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get(Category_.masterCategory).get(MasterCategory_.user), user); } Specification<Category> byUser(User user); }### Answer: @Test public void byUser() { User user...
### Question: UserService { public List<User> list() { return userRepository.findAll(); } @Autowired UserService(UserRepository userRepository, UserManagementProperties userManagementProperties); List<User> list(); User create(String name, String currency); User get(long id); String getTestProperty(); }### Answer: @T...
### Question: UserService { public User get(long id) { return userRepository.findOne(Example.of(new User().setId(id))).orElse(null); } @Autowired UserService(UserRepository userRepository, UserManagementProperties userManagementProperties); List<User> list(); User create(String name, String currency); User get(long id...
### Question: UserService { public String getTestProperty() { return userManagementProperties.getTestProperty(); } @Autowired UserService(UserRepository userRepository, UserManagementProperties userManagementProperties); List<User> list(); User create(String name, String currency); User get(long id); String getTestPro...
### Question: UserResourceAssembler extends ResourceAssembler<User, UserResource> { @Override protected UserResource createResource(User user) { return new UserResource(user.getName(), user.getCurrency()); } @Autowired UserResourceAssembler(List<ResourceLinks<User>> resourceLinks); }### Answer: @Test public void cre...
### Question: UserResourceValidator implements Validator { @Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "currency", "currency.empty"); } @Override boolean supports(Class<?> clazz...
### Question: UserControllerUserLinks extends ResourceLinks<User> { @Override public Collection<Link> generateLinks(User entity) { Link self = linkTo(methodOn(UserController.class).get(entity.getId())).withSelfRel(); Link users = linkTo(methodOn(UserController.class).list()).withRel("users"); return Arrays.asList(self,...
### Question: UserController { @GetMapping("/{userId}") public Resource<UserResource> get(@PathVariable("userId") long userId) { User user = userService.get(userId); final UserResource userResource = userResourceAssembler.toResource(user); return new Resource<>(userResource); } @Autowired UserController(UserService us...
### Question: UserController { @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<UserResource> create(@RequestBody @Valid UserResource userResource) { User user = userService.create(userResource.getName(), userResource.getCurrency()); final UserResource createdUserResource = userResourceAs...
### Question: Order implements Serializable { @Override public String toString() { return "Order{" + "type=" + type + ", index=" + index + ", price=" + pricePerAsset + ", amount=" + amount + '}'; } protected Order(int index, BarSeries series, OrderType type); protected Order(int index, BarSeries series, OrderType typ...
### Question: NumberOfBarsCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isLessThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries series,...
### Question: AverageProfitCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { Num bars = numberOfBars.calculate(series, tradingRecord); if (bars.isEqual(series.numOf(0))) { return series.numOf(1); } return totalProfit.calculate(series, tradingRe...
### Question: AverageProfitCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override Num calculate(BarSeries ser...
### Question: RewardRiskRatioCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { return totalProfit.calculate(series, tradingRecord).dividedBy(maxDrawdown.calculate(series, tradingRecord)); } @Override Num calculate(BarSeries series, TradingReco...
### Question: CrossedDownIndicatorRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = cross.getValue(index); traceIsSatisfied(index, satisfied); return satisfied; } CrossedDownIndicatorRule(Indicator<Num> indicator, Number threshold); Cro...
### Question: RewardRiskRatioCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } @Override Num calculate(BarSeries series, TradingRecord tradingRecord); @Override boolean betterThan(Num cr...
### Question: ExpectedShortfallCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { Returns returns = new Returns(series, tradingRecord, Returns.ReturnType.LOG); return calculateES(returns, confidence); } ExpectedShortfallCriterion(Double confiden...
### Question: ExpectedShortfallCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } ExpectedShortfallCriterion(Double confidence); @Override Num calculate(BarSeries series, TradingRecord tra...
### Question: AverageProfitableTradesCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, Trade trade) { return isProfitableTrade(series, trade) ? series.numOf(1) : series.numOf(0); } @Override Num calculate(BarSeries series, Trade trade); @Override Num calculate(BarSeries ser...
### Question: IsEqualRule extends AbstractRule { @Override public boolean isSatisfied(int index, TradingRecord tradingRecord) { final boolean satisfied = first.getValue(index).isEqual(second.getValue(index)); traceIsSatisfied(index, satisfied); return satisfied; } IsEqualRule(Indicator<Num> indicator, Number value); I...
### Question: AverageProfitableTradesCriterion extends AbstractAnalysisCriterion { @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } @Override Num calculate(BarSeries series, Trade trade); @Override Num calculate(BarSeries series, T...
### Question: NumberOfBreakEvenTradesCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { long numberOfLosingTrades = tradingRecord.getTrades().stream().filter(Trade::isClosed) .filter(trade -> isBreakEvenTrade(series, trade)).count(); return seri...