method2testcases
stringlengths
118
6.63k
### Question: RegexUtil { public static Pattern getRegex(String input) { Matcher matcher = pattern.matcher(input); if (!matcher.find()) { return null; } try { return Pattern.compile(input); } catch (PatternSyntaxException e) { return null; } } static Pattern getRegex(String input); static Pattern env(); static boolean...
### Question: JavaMethod { public static SyncFilter build(String consumerId, SyncerFilterMeta filterMeta, String method) { String source = "import com.github.zzt93.syncer.data.*;\n" + "import com.github.zzt93.syncer.data.util.*;\n" + "import java.util.*;\n" + "import java.math.BigDecimal;\n" + "import java.sql.Timestam...
### Question: FileBasedMap { public boolean flush() { T toFlush = getToFlush(); if (toFlush == null) { return false; } byte[] bytes = toFlush.toString().getBytes(StandardCharsets.UTF_8); putBytes(file, bytes); file.force(); return true; } FileBasedMap(Path path); static byte[] readData(Path path); boolean append(T data...
### Question: SyncKafkaSerializer implements Serializer<SyncResult> { @Override public byte[] serialize(String topic, SyncResult data) { return gson.toJson(data).getBytes(); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] serialize(String topic, SyncResult data); @Override void clos...
### Question: MongoV4MasterConnector extends MongoConnectorBase { static Map getUpdatedFields(Document fullDocument, BsonDocument updatedFields, boolean bsonConversion) { if (bsonConversion) { if (fullDocument == null) { return (Map) MongoTypeUtil.convertBson(updatedFields); } HashMap<String, Object> res = new HashMap<...
### Question: DocTimestamp implements SyncInitMeta<DocTimestamp> { @Override public int compareTo(DocTimestamp o) { if (o == this) { return 0; } if (this == earliest) { return -1; } else if (o == earliest) { return 1; } return timestamp.compareTo(o.timestamp); } DocTimestamp(BsonTimestamp data); @Override int compareTo...
### Question: BinlogInfo implements SyncInitMeta<BinlogInfo> { @Override public int compareTo(BinlogInfo o) { if (o == this) { return 0; } if (this == latest || o == earliest) { return 1; } else if (this == earliest || o == latest) { return -1; } int seq = Integer.parseInt(binlogFilename.split("\\.")[1]); int oSeq = In...
### Question: BinlogInfo implements SyncInitMeta<BinlogInfo> { static int checkFilename(String binlogFilename) { try { return Integer.parseInt(binlogFilename.split("\\.")[1]); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { throw new InvalidBinlogException(e, binlogFilename, 0); } } BinlogInfo(Stri...
### Question: WadlZipper { public void saveTo(String zipPathName) throws IOException, URISyntaxException { saveTo(new File(zipPathName)); } WadlZipper(String wadlUri); void saveTo(String zipPathName); void saveTo(File zipFile); }### Answer: @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGram...
### Question: SingleType extends ClassType { @Override public String toSchema() { try { return tryBuildSchemaFromJaxbAnnotatedClass(); } catch (Exception e) { logger.warn("Cannot generate schema from JAXB annotations for class: " + clazz.getName() + ". Preparing generic Schema.\n" + e, e); return schemaForNonAnnotatedC...
### Question: ClassUtils { public static boolean isArrayOrCollection(Class<?> clazz) { return clazz.isArray() || Collection.class.isAssignableFrom(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz...
### Question: ClassUtils { public static boolean isVoid(Class<?> clazz) { return Void.class.equals(clazz) || void.class.equals(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }### Answer: @Te...
### Question: ClassUtils { public static Class<?> getElementsClassOf(Class<?> clazz) { if (clazz.isArray()) { return clazz.getComponentType(); } if (Collection.class.isAssignableFrom(clazz)) { logger.warn("In Java its not possible to discover de Generic type of a collection like: {}", clazz); return Object.class; } ret...
### Question: RepresentationBuilder { Collection<Representation> build(MethodContext ctx) { final Collection<Representation> representations = new ArrayList<Representation>(); final Method javaMethod = ctx.getJavaMethod(); final GrammarsDiscoverer grammarsDiscoverer = ctx.getParentContext().getGrammarsDiscoverer(); for...
### Question: GrammarsDiscoverer { public List<String> getSchemaUrlsForComplexTypes() { final List<String> urls = new ArrayList<String>(); for (String localPart : classTypeDiscoverer.getAllByLocalPart().keySet()) { urls.add("schema/" + localPart); } return urls; } GrammarsDiscoverer(ClassTypeDiscoverer classTypeDiscove...
### Question: IncludeBuilder { Collection<Include> build() { final List<Include> includes = new ArrayList<Include>(); for (String schemaUrl : grammarsDiscoverer.getSchemaUrlsForComplexTypes()) { includes.add(new Include().withHref(schemaUrl)); } return includes; } IncludeBuilder(GrammarsDiscoverer grammarsDiscoverer); ...
### Question: GrammarsUrisExtractor { List<String> extractFrom(String wadl) { final List<String> uris = new ArrayList<String>(); final String[] includeElements = BY_INCLUDE.split(extractGrammarsElement(wadl)); for (int i = 1; i < includeElements.length; i++) { uris.add(extractIncludeUriFrom(includeElements[i])); } retu...
### Question: CollectionType extends ClassType { @Override public String toSchema() { return COLLECTION_COMPLEX_TYPE_SCHEMA .replace("???type???", elementsQName.getLocalPart()) .replace("???name???", elementsQName.getLocalPart()) .replace("???collectionType???", qName.getLocalPart()) .replace("???collectionName???", qN...
### Question: ClassTypeDiscoverer { public ClassType getBy(String localPart) { final ClassType classType = classTypeStore.findBy(localPart); if (classType == null) { throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); } return classType; } ClassTypeDiscoverer(QNameBuilder qNameBu...
### Question: SchemaBuilder { public String buildFor(final String localPart) { return classTypeDiscoverer.getBy(localPart).toSchema(); } SchemaBuilder(ClassTypeDiscoverer classTypeDiscoverer); String buildFor(final String localPart); }### Answer: @Test public void givenExistingLocalPart_whenBuildSchema_thenReturnSchem...
### Question: UpperCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("UCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Lit...
### Question: LowerCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("LCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Lit...
### Question: HashFunction implements Function { @Override public abstract Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException; @Override abstract Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate() { try { Literal hash =...
### Question: QueryModelNormalizer extends AbstractQueryModelVisitor<RuntimeException> implements QueryOptimizer { @Override public void meet(Join join) { super.meet(join); TupleExpr leftArg = join.getLeftArg(); TupleExpr rightArg = join.getRightArg(); if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { ...
### Question: ShaclSailFactory implements SailFactory { @Override public String getSailType() { return SAIL_TYPE; } @Override String getSailType(); @Override SailImplConfig getConfig(); @Override Sail getSail(SailImplConfig config); static final String SAIL_TYPE; }### Answer: @Test public void getSailTypeReturnsCorrec...
### Question: ShaclSailFactory implements SailFactory { @Override public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } ShaclSail sail = new ShaclSail(); if (config instanceof ShaclSai...
### Question: Buffer implements Function { @Override public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 3) { throw new ValueExprEvaluationException(getURI() + " requires exactly 3 arguments, got " + args.length); } SpatialContext geoContext = Spatial...
### Question: ProxyRepository extends AbstractRepository implements RepositoryResolverClient { @Override public RepositoryConnection getConnection() throws RepositoryException { return getProxiedRepository().getConnection(); } ProxyRepository(); ProxyRepository(String proxiedIdentity); ProxyRepository(RepositoryResol...
### Question: SPARQLUpdateDataBlockParser extends TriGParser { @Override protected void parseGraph() throws RDFParseException, RDFHandlerException, IOException { super.parseGraph(); skipOptionalPeriod(); } SPARQLUpdateDataBlockParser(); SPARQLUpdateDataBlockParser(ValueFactory valueFactory); @Override RDFFormat getRDF...
### Question: ProxyRepositoryFactory implements RepositoryFactory { @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { ProxyRepository result = null; if (config instanceof ProxyRepositoryConfig) { result = new ProxyRepository(((ProxyRepositoryConfig) config).getPro...
### Question: ValueComparator implements Comparator<Value> { @Override public int compare(Value o1, Value o2) { if (ObjectUtil.nullEquals(o1, o2)) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } boolean b1 = o1 instanceof BNode; boolean b2 = o2 instanceof BNode; if (b1 && b2) { return compare...
### Question: Rand implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 0) { throw new ValueExprEvaluationException("RAND requires 0 arguments, got " + args.length); } Random randomGenerator = new Random(); double rand...
### Question: Round implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("ROUND requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal...
### Question: Tz implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TZ requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Liter...
### Question: Timezone implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TIMEZONE requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue inst...
### Question: SpinParser { public SpinParser() { this(Input.TEXT_FIRST); } SpinParser(); SpinParser(Input input); SpinParser(Input input, Function<IRI, String> wellKnownVarsMapper, Function<IRI, String> wellKnownFuncMapper); List<FunctionParser> getFunctionParsers(); void setFunctionParsers(List<FunctionParser> fu...
### Question: Concat implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length == 0) { throw new ValueExprEvaluationException("CONCAT requires at least 1 argument, got " + args.length); } StringBuilder concatBuilder = new Stri...
### Question: Util { public static Resource[] getContexts(String[] tokens, int pos, Repository repository) throws IllegalArgumentException { Resource[] contexts = new Resource[] {}; if (tokens.length > pos) { contexts = new Resource[tokens.length - pos]; for (int i = pos; i < tokens.length; i++) { contexts[i - pos] = g...
### Question: Verify extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length != 2 && tokens.length != 4) { consoleIO.writeln(getHelpLong()); return; } String dataPath = parseDataPath(tokens[1]); verify(dataPath); if (tokens.length == 4) { String shaclPath = parseDataPath(tokens[2]);...
### Question: Export extends ConsoleCommand { @Override public void execute(String... tokens) { Repository repository = state.getRepository(); if (repository == null) { consoleIO.writeUnopenedError(); return; } if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); return; } String fileName = tokens[1]; Resource[] ...
### Question: Convert extends ConsoleCommand { private void convert(String fileFrom, String fileTo) { Path pathFrom = Util.getPath(fileFrom); if (pathFrom == null) { consoleIO.writeError("Invalid file name (from) " + fileFrom); return; } if (Files.notExists(pathFrom)) { consoleIO.writeError("File not found (from) " + f...
### Question: Convert extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } Convert(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override ...
### Question: SetParameters extends ConsoleCommand { @Override public void execute(String... tokens) { switch (tokens.length) { case 0: consoleIO.writeln(getHelpLong()); break; case 1: for (String setting : settings.keySet()) { showSetting(setting); } break; default: String param = tokens[1]; int eqIdx = param.indexOf(...
### Question: ValueDecoder { protected Value decodeValue(String string) throws BadRequestException { Value result = null; try { if (string != null) { String value = string.trim(); if (!value.isEmpty() && !"null".equals(value)) { if (value.startsWith("_:")) { String label = value.substring("_:".length()); result = facto...
### Question: Util { @Deprecated public static String formatToWidth(int width, String padding, String str, String separator) { if (str.isEmpty()) { return ""; } int padLen = padding.length(); int strLen = str.length(); int sepLen = separator.length(); if (strLen + padLen <= width) { return padding + str; } String[] val...
### Question: Drop extends ConsoleCommand { @Override public void execute(String... tokens) throws IOException { if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); } else { final String repoID = tokens[1]; try { dropRepository(repoID); } catch (RepositoryConfigException e) { consoleIO.writeError("Unable to drop...
### Question: InfoServlet extends TransformationServlet { @Override protected void service(WorkbenchRequest req, HttpServletResponse resp, String xslPath) throws Exception { String id = info.getId(); if (null != id && !manager.hasRepositoryConfig(id)) { throw new RepositoryConfigException(id + " does not exist."); } Tu...
### Question: DBDecryptor implements Decryptor { public void decryptDB(File input, File output) throws IOException, GeneralSecurityException { if (input == null) throw new IllegalArgumentException("input cannot be null"); if (output == null) throw new IllegalArgumentException("output cannot be null"); decryptStream(new...
### Question: Whassup { public long getMostRecentTimestamp(boolean ignoreGroups) throws IOException { File currentDB = dbProvider.getDBFile(); if (currentDB == null) { return DEFAULT_MOST_RECENT; } else { SQLiteDatabase db = getSqLiteDatabase(decryptDB(currentDB)); Cursor cursor = null; try { String query = "SELECT MAX...
### Question: Whassup { public List<WhatsAppMessage> getMessages(long timestamp, int max) throws IOException { Cursor cursor = queryMessages(timestamp, max); try { if (cursor != null) { List<WhatsAppMessage> messages = new ArrayList<WhatsAppMessage>(cursor.getCount()); while (cursor.moveToNext()) { messages.add(new Wha...
### Question: Whassup { public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ign...
### Question: Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(b...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public Date getTimestamp() { return new Date(timestamp); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); do...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public String getNumber() { if (TextUtils.isEmpty(key_remote_jid)) return null; String[] components = key_remote_jid.split("@", 2); if (components.length > 1) { if (!isGroupMessage()) { return components[0]; } else { return components[0].split("-")[...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String ...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean hasText() { return !TextUtils.isEmpty(data); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude();...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean isReceived() { return key_from_me == 0; } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); doub...
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { static String filterPrivateBlock(String s) { if (s == null) return null; final StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); ) { int codepoint = s.codePointAt(i); Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoi...
### Question: Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } Media(); Media(Cursor c); byte[] getRawData(); String getMimeType(); String getUrl(); int getSize(); File getFile(); long getFileSize(); @Override String toString(); }### Answer: @Test public void s...
### Question: DBDecryptor implements Decryptor { protected void decryptStream(InputStream in, OutputStream out) throws GeneralSecurityException, IOException { Cipher cipher = getCipher(Cipher.DECRYPT_MODE); CipherInputStream cis = null; try { cis = new CipherInputStream(in, cipher); byte[] buffer = new byte[8192]; int ...
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); return personRepository.findPersonsForPage(searchTerm, pageIndex); } @Transactiona...
### Question: PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb...
### Question: RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.g...
### Question: PersonController extends AbstractController { @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody public Long count(@RequestBody SearchDTO searchCriteria) { String searchTerm = searchCriteria.getSearchTerm(); LOGGER.debug("Finding person count for search term: " + searchTerm)...
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) public String delete(@PathVariable("id") Long id, RedirectAttributes attributes) { LOGGER.debug("Deleting person with id: " + id); try { Person deleted = personService.delete(id); addFe...
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody public List<PersonDTO> search(@RequestBody SearchDTO searchCriteria) { LOGGER.debug("Searching persons with search criteria: " + searchCriteria); String searchTerm = sear...
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/create", method = RequestMethod.GET) public String showCreatePersonForm(Model model) { LOGGER.debug("Rendering create person form"); model.addAttribute(MODEL_ATTIRUTE_PERSON, new PersonDTO()); return PERSON_ADD_FORM_VIEW; } @R...
### Question: Person { @PrePersist public void prePersist() { Date now = new Date(); creationTime = now; modificationTime = now; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModifi...
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) public String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes) { LOGGER.debug("Rendering edit person form for person with id: " + id); Person pe...
### Question: Person { @PreUpdate public void preUpdate() { modificationTime = new Date(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void ...
### Question: PersonController extends AbstractController { @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) public String showList(Model model) { LOGGER.debug("Rendering person list page"); List<Person> persons = personService.findAll(); model.addAttribute(MODEL_ATTRIBUTE_PERSONS, persons); mo...
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/search", method=RequestMethod.POST) public String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model) { LOGGER.debug("Rendering search result page for search criteria: " ...
### Question: AbstractController { protected void addErrorMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("adding error message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String localize...
### Question: AbstractController { protected void addFeedbackMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("Adding feedback message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String lo...
### Question: AbstractController { protected String createRedirectViewPath(String path) { StringBuilder builder = new StringBuilder(); builder.append(VIEW_REDIRECT_PREFIX); builder.append(path); return builder.toString(); } }### Answer: @Test public void createRedirectViewPath() { String redirectView = controller.cr...
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findAllPersons() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long fin...
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public long findPersonCount(String searchTerm) { LOGGER.debug("Finding person count with search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } PaginatingPersonRepositoryImpl(); @Override L...
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findPersonsForPage(String searchTerm, int page) { LOGGER.debug("Finding persons for page " + page + " with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchT...
### Question: PreCondition { public static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments) { isTrue(expression, String.format(errorMessageTemplate, errorMessageArguments)); } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object...
### Question: Person { public void update(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getMo...
### Question: PreCondition { public static void notEmpty(String string, String errorMessage) { if (string.isEmpty()) { throw new IllegalArgumentException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(b...
### Question: PreCondition { public static void notNull(Object reference, String errorMessage) { if (reference == null) { throw new NullPointerException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(bo...
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.findPersonCount(searchTerm); } @Transactional @Override Person create(PersonDTO created); @Transa...
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public Person create(PersonDTO created) { LOGGER.debug("Creating a new person with information: " + created); Person person = Person.getBuilder(created.getFirstName(), created.getLastName()).build(); return personRepository.save(p...
### Question: RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person delete(Long personId) throws PersonNotFoundException { LOGGER.debug("Deleting person with id: " + personId); Person deleted = personRepository.findOne(personId); if (delet...
### Question: Person { @Transient public String getName() { StringBuilder name = new StringBuilder(); name.append(firstName); name.append(" "); name.append(lastName); return name.toString(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); Str...
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } @Transactional @Override Person create(PersonDTO created); @...
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override lon...
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchTerm), construct...
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAllPersons(); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(Stri...
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public Person findById(Long id) { LOGGER.debug("Finding person by id: " + id); return personRepository.findOne(id); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count...
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void registerUser(User user, String plainPassword) { entryptPassword(user, plainPassword); generateActKey(user); user.setRoles("user"); user.setRegisterDate(Calendar.getInstance().getTime()); user.setNiceName(user.getLoginName()); u...
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void updateUser(User user, String plainPassword) { if (StringUtils.isNotBlank(plainPassword)) { entryptPassword(user, plainPassword); } userRepository.save(user); } User getUser(Long id); User findUserByLoginName(String loginName);...
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void deleteUser(Long id) { if (isSupervisor(id)) { logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName()); throw new ServiceException("不能删除超级管理员用户"); } userRepository.delete(id); } User getUser(Long id); User findUserByLoginName(Str...
### Question: UserService extends BaseService { void entryptPassword(User user, String plainPassword) { byte[] salt = Digests.generateSalt(SALT_SIZE); user.setSalt(Encodes.encodeHex(salt)); byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS); user.setPassword(Encodes.encodeHex(hashPassw...
### Question: MD5DigestCalculatingInputStream extends SdkFilterInputStream { @Override public boolean markSupported() { return super.markSupported() && digestCanBeCloned; } MD5DigestCalculatingInputStream(InputStream in); @Override boolean markSupported(); byte[] getMd5Digest(); @Override void mark(int readlimit); @Ove...
### Question: StringUtils { public static String fromByteBuffer(ByteBuffer byteBuffer) { return Base64.encodeAsString(copyBytesFrom(byteBuffer)); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Intege...
### Question: StringUtils { public static String fromByte(Byte b) { return Byte.toString(b); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static ...
### Question: StringUtils { public static String replace( String originalString, String partToMatch, String replacement ) { StringBuilder buffer = new StringBuilder( originalString.length() ); buffer.append( originalString ); int indexOf = buffer.indexOf( partToMatch ); while (indexOf != -1) { buffer = buffer.replace(i...
### Question: StringUtils { public static String lowerCase(String str) { if(isNullOrEmpty(str)) { return str; } return str.toLowerCase(LOCALE_ENGLISH); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(...