instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private boolean isGenerateForVendor(int C_BPartner_ID) { // No filter group was set => generate for all vendors if (p_C_BP_Group_ID <= 0) return true; if (m_excludedVendors.contains(C_BPartner_ID)) return false; // boolean match = new Query(getCtx(), MBPartner.Table_Name, "C_BPartner_ID=? AND C_BP_Group_ID=?", get_TrxName()) .setParameters(new Object[] { C_BPartner_ID, p_C_BP_Group_ID }) .anyMatch(); if (!match) { m_excludedVendors.add(C_BPartner_ID); } return match; } private List<Integer> m_excludedVendors = new ArrayList<>(); /** * check if the partner is vendor for specific product * * @param C_BPartner_ID * @param product
* @return */ private boolean isVendorForProduct(final int C_BPartner_ID, final MProduct product) { return Services.get(IQueryBL.class).createQueryBuilder(I_C_BPartner_Product.class, product) .addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_C_BPartner_ID, C_BPartner_ID) .addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_M_Product_ID, product.getM_Product_ID()) .create() .anyMatch(); } private boolean isPOPriceList(final int M_PriceList_ID) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_PriceList.class, getProcessInfo()) .addEqualsFilter(I_M_PriceList.COLUMNNAME_M_PriceList_ID, M_PriceList_ID) .addEqualsFilter(I_M_PriceList.COLUMNNAME_IsSOPriceList, false) .create() .anyMatch(); } } // RequisitionPOCreate
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\RequisitionPOCreate.java
1
请完成以下Java代码
public String getName() { return "Excel (XML)"; } @Override public Workbook createWorkbook(final boolean useStreamingImplementation) { if (useStreamingImplementation) { return new SXSSFWorkbook(); } else { return new XSSFWorkbook(); } } @Override public String getCurrentPageMarkupTag() { // see XSSFHeaderFooter javadoc return "&P";
} @Override public String getTotalPagesMarkupTag() { // see XSSFHeaderFooter javadoc return "&N"; } @Override public int getLastRowIndex() { return SpreadsheetVersion.EXCEL2007.getLastRowIndex(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelOpenXMLFormat.java
1
请完成以下Java代码
public class JavaSerDesUtil { @SuppressWarnings("unchecked") public static <T> T decode(byte[] byteArray) { if (byteArray == null || byteArray.length == 0) { return null; } InputStream is = new ByteArrayInputStream(byteArray); try (ObjectInputStream ois = new ObjectInputStream(is)) { return (T) ois.readObject(); } catch (IOException | ClassNotFoundException e) { log.error("Error during deserialization", e); return null; } }
public static <T> byte[] encode(T msq) { if (msq == null) { return null; } ByteArrayOutputStream boas = new ByteArrayOutputStream(); try (ObjectOutputStream ois = new ObjectOutputStream(boas)) { ois.writeObject(msq); return boas.toByteArray(); } catch (IOException e) { log.error("Error during serialization", e); throw new RuntimeException(e); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\JavaSerDesUtil.java
1
请完成以下Java代码
public class DocumentType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected byte[] base64; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") @XmlSchemaType(name = "anyURI") protected String url; @XmlAttribute(name = "filename", required = true) protected String filename; @XmlAttribute(name = "mimeType", required = true) protected String mimeType; @XmlAttribute(name = "viewer") @XmlSchemaType(name = "anyURI") protected String viewer; /** * Gets the value of the base64 property. * * @return * possible object is * byte[] */ public byte[] getBase64() { return base64; } /** * Sets the value of the base64 property. * * @param value * allowed object is * byte[] */ public void setBase64(byte[] value) { this.base64 = value; } /** * Gets the value of the url property. * * @return * possible object is * {@link String } * */ public String getUrl() { return url; } /** * Sets the value of the url property. * * @param value * allowed object is * {@link String } * */ public void setUrl(String value) { this.url = value; } /** * Gets the value of the filename property. * * @return * possible object is * {@link String } *
*/ public String getFilename() { return filename; } /** * Sets the value of the filename property. * * @param value * allowed object is * {@link String } * */ public void setFilename(String value) { this.filename = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * Gets the value of the viewer property. * * @return * possible object is * {@link String } * */ public String getViewer() { return viewer; } /** * Sets the value of the viewer property. * * @param value * allowed object is * {@link String } * */ public void setViewer(String value) { this.viewer = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DocumentType.java
1
请在Spring Boot框架中完成以下Java代码
static class JerseyAdditionalHealthEndpointPathsResourcesRegistrar implements ResourceConfigCustomizer { private final @Nullable ExposableWebEndpoint endpoint; private final HealthEndpointGroups groups; JerseyAdditionalHealthEndpointPathsResourcesRegistrar(@Nullable ExposableWebEndpoint endpoint, HealthEndpointGroups groups) { this.endpoint = endpoint; this.groups = groups; } @Override public void customize(ResourceConfig config) { register(config); } private void register(ResourceConfig config) { EndpointMapping mapping = new EndpointMapping(""); JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.SERVER, this.groups); Collection<Resource> endpointResources = resourceFactory
.createEndpointResources(mapping, (this.endpoint != null) ? Collections.singletonList(this.endpoint) : Collections.emptyList()) .stream() .filter(Objects::nonNull) .toList(); register(endpointResources, config); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\endpoint\web\HealthEndpointJerseyExtensionAutoConfiguration.java
2
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.domain.hashCode(); result = prime * result + this.name.hashCode(); return result; } @Override public String toString() { return this.string; } private String getDomainOrDefault(@Nullable String domain) { if (domain == null || LEGACY_DOMAIN.equals(domain)) { return DEFAULT_DOMAIN; } return domain; } private String getNameWithDefaultPath(String domain, String name) { if (DEFAULT_DOMAIN.equals(domain) && !name.contains("/")) { return OFFICIAL_REPOSITORY_NAME + "/" + name; } return name; }
static @Nullable String parseDomain(String value) { int firstSlash = value.indexOf('/'); String candidate = (firstSlash != -1) ? value.substring(0, firstSlash) : null; if (candidate != null && Regex.DOMAIN.matcher(candidate).matches()) { return candidate; } return null; } static ImageName of(String value) { Assert.hasText(value, "'value' must not be empty"); String domain = parseDomain(value); String path = (domain != null) ? value.substring(domain.length() + 1) : value; Assert.isTrue(Regex.PATH.matcher(path).matches(), () -> "'value' path must contain an image reference in the form '[domainHost:port/][path/]name' " + "(with 'path' and 'name' containing only [a-z0-9][.][_][-]) [" + value + "]"); return new ImageName(domain, path); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ImageName.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getId() { return id; } public void setId(Long customerId) { this.id = customerId; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\java\com\baeldung\spring\data\jpa\nestedobject\Customer.java
2
请完成以下Java代码
public String toString() { if (label == null) return value; return value + '/' + label; } public Word(String value, String label) { this.value = value; this.label = label; } /** * 通过参数构造一个单词 * @param param 比如 人民网/nz * @return 一个单词 */ public static Word create(String param) { if (param == null) return null; int cutIndex = param.lastIndexOf('/'); if (cutIndex <= 0 || cutIndex == param.length() - 1) { Predefine.logger.warning("使用 " + param + "创建单个单词失败"); return null; } return new Word(param.substring(0, cutIndex), param.substring(cutIndex + 1)); }
@Override public String getValue() { return value; } @Override public String getLabel() { return label; } @Override public void setLabel(String label) { this.label = label; } @Override public void setValue(String value) { this.value = value; } @Override public int length() { return value.length(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\Word.java
1
请完成以下Java代码
public int getConsumerCount() { return this.consumerCount; } /** * Return a queue type. * {@code classic} by default since AMQP 0.9.1 protocol does not return this info in {@code DeclareOk} reply. * @return a queue type * @since 4.0 */ public String getType() { return this.type; } /** * Set a queue type. * @param type the queue type: {@code quorum}, {@code classic} or {@code stream} * @since 4.0 */ public void setType(String type) { this.type = type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.name.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; }
if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } QueueInformation other = (QueueInformation) obj; return this.name.equals(other.name); } @Override public String toString() { return "QueueInformation [name=" + this.name + ", messageCount=" + this.messageCount + ", consumerCount=" + this.consumerCount + "]"; } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\QueueInformation.java
1
请完成以下Java代码
ScriptEngine createScriptEngine(TbContext ctx, TbLogNodeConfiguration config) { return ctx.createScriptEngine(config.getScriptLang(), ScriptLanguage.TBEL.equals(config.getScriptLang()) ? config.getTbelScript() : config.getJsScript()); } @Override public void onMsg(TbContext ctx, TbMsg msg) { if (!log.isInfoEnabled()) { ctx.tellSuccess(msg); return; } if (standard) { logStandard(ctx, msg); return; } Futures.addCallback(scriptEngine.executeToStringAsync(msg), new FutureCallback<>() { @Override public void onSuccess(@Nullable String result) { log.info(result); ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }, MoreExecutors.directExecutor()); //usually js responses runs on js callback executor } boolean isStandard(TbLogNodeConfiguration conf) { Objects.requireNonNull(conf, "node config is null"); final TbLogNodeConfiguration defaultConfig = new TbLogNodeConfiguration().defaultConfiguration(); if (conf.getScriptLang() == null || conf.getScriptLang().equals(ScriptLanguage.JS)) { return defaultConfig.getJsScript().equals(conf.getJsScript()); } else if (conf.getScriptLang().equals(ScriptLanguage.TBEL)) { return defaultConfig.getTbelScript().equals(conf.getTbelScript()); } else { log.warn("No rule to define isStandard script for script language [{}], assuming that is non-standard", conf.getScriptLang()); return false; } }
void logStandard(TbContext ctx, TbMsg msg) { log.info(toLogMessage(msg)); ctx.tellSuccess(msg); } String toLogMessage(TbMsg msg) { return "\n" + "Incoming message:\n" + msg.getData() + "\n" + "Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData()); } @Override public void destroy() { if (scriptEngine != null) { scriptEngine.destroy(); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbLogNode.java
1
请在Spring Boot框架中完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()//配置权限 // .antMatchers("/").access("hasRole('TEST')")//该路径需要TEST角色 // .antMatchers("/brand/list").hasAuthority("TEST")//该路径需要TEST权限 .antMatchers("/**").permitAll() .and()//启用基于http的认证 .httpBasic() .realmName("/") .and()//配置登录页面 .formLogin() .loginPage("/login") .failureUrl("/login?error=true") .and()//配置退出路径 .logout() .logoutSuccessUrl("/") // .and()//记住密码功能 // .rememberMe() // .tokenValiditySeconds(60*60*24) // .key("rememberMeKey") .and()//关闭跨域伪造 .csrf() .disable() .headers()//去除X-Frame-Options .frameOptions() .disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder()); } @Bean public UserDetailsService userDetailsService() { //获取登录用户信息 return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UmsAdminExample example = new UmsAdminExample(); example.createCriteria().andUsernameEqualTo(username); List<UmsAdmin> umsAdminList = umsAdminMapper.selectByExample(example); if (umsAdminList != null && umsAdminList.size() > 0) { return new AdminUserDetails(umsAdminList.get(0)); } throw new UsernameNotFoundException("用户名或密码错误"); } }; } }
repos\mall-master\mall-demo\src\main\java\com\macro\mall\demo\config\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { //每个请求记录一个traceId,可以根据traceId搜索出本次请求的全部相关日志 MDC.put("traceId", UUID.randomUUID().toString().replace("-", "").substring(0, 12)); setUsername(request); setProductId(request); //使request中的body可以重复读取 https://juejin.im/post/6858037733776949262#heading-4 request = new ContentCachingRequestWrapper(request); filterChain.doFilter(request, response); } catch (Exception e) { throw e; } finally { //清理ThreadLocal MDC.clear(); } } /** * 将url参数中的productId放入ThreadLocal */ private void setProductId(HttpServletRequest request) { String productIdStr = request.getParameter("productId");
if (!StringTools.isNullOrEmpty(productIdStr)) { log.debug("url中productId = {}", productIdStr); MDC.put("productId", productIdStr); } } private void setUsername(HttpServletRequest request) { //通过token解析出username String token = request.getHeader("token"); if (!StringTools.isNullOrEmpty(token)) { MDC.put("token", token); try { SessionUserInfo info = tokenService.getUserInfo(); if (info != null) { String username = info.getUsername(); MDC.put("username", username); } } catch (CommonJsonException e) { log.info("无效的token:{}", token); } } } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\filter\RequestFilter.java
2
请完成以下Java代码
protected final void prepare() { importProcess = newInstance(IFAInitialImportProcess2.class); importProcess.setCtx(getCtx()); importProcess.setParameters(getParameterAsIParams()); importProcess.setLoggable(this); importProcess.notifyUserId(getUserId()); } // NOTE: we shall run this process out of transaction because the actual import process is managing the transaction @Override @RunOutOfTrx protected final String doIt() throws Exception { importProcess.run(); return MSG_OK; }
private IImportProcess<I_I_Pharma_Product> newInstance(final Class<?> importProcessClass) { try { @SuppressWarnings("unchecked") final IImportProcess<I_I_Pharma_Product> importProcess = (IImportProcess<I_I_Pharma_Product>)importProcessClass.newInstance(); return importProcess; } catch (Exception e) { throw new AdempiereException("Failed instantiating " + importProcessClass, e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAInitialImportProcess.java
1
请完成以下Java代码
public class StringFilenameValidationUtils { public static final Character[] INVALID_WINDOWS_SPECIFIC_CHARS = {'"', '*', '<', '>', '?', '|'}; public static final Character[] INVALID_UNIX_SPECIFIC_CHARS = {'\000'}; public static final String REGEX_PATTERN = "^[A-Za-z0-9.]{1,255}$"; private StringFilenameValidationUtils() { } public static boolean validateStringFilenameUsingIO(String filename) throws IOException { File file = new File(filename); boolean created = false; try { created = file.createNewFile(); return created; } finally { if (created) { file.delete(); } } } public static boolean validateStringFilenameUsingNIO2(String filename) { Paths.get(filename); return true; } public static boolean validateStringFilenameUsingContains(String filename) { if (filename == null || filename.isEmpty() || filename.length() > 255) { return false;
} return Arrays.stream(getInvalidCharsByOS()) .noneMatch(ch -> filename.contains(ch.toString())); } public static boolean validateStringFilenameUsingRegex(String filename) { if (filename == null) { return false; } return filename.matches(REGEX_PATTERN); } private static Character[] getInvalidCharsByOS() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) { return INVALID_WINDOWS_SPECIFIC_CHARS; } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { return INVALID_UNIX_SPECIFIC_CHARS; } else { return new Character[]{}; } } }
repos\tutorials-master\core-java-modules\core-java-string-operations-3\src\main\java\com\baeldung\stringfilenamevalidaiton\StringFilenameValidationUtils.java
1
请完成以下Java代码
public void setPAPeriodType (String PAPeriodType) { set_Value (COLUMNNAME_PAPeriodType, PAPeriodType); } /** Get Period Type. @return PA Period Type */ public String getPAPeriodType () { return (String)get_Value(COLUMNNAME_PAPeriodType); } /** Set Report Line. @param PA_ReportLine_ID Report Line */ public void setPA_ReportLine_ID (int PA_ReportLine_ID) { if (PA_ReportLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID)); } /** Get Report Line. @return Report Line */ public int getPA_ReportLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_ReportLineSet getPA_ReportLineSet() throws RuntimeException { return (I_PA_ReportLineSet)MTable.get(getCtx(), I_PA_ReportLineSet.Table_Name) .getPO(getPA_ReportLineSet_ID(), get_TrxName()); } /** Set Report Line Set. @param PA_ReportLineSet_ID Report Line Set */ public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID) { if (PA_ReportLineSet_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID)); } /** Get Report Line Set. @return Report Line Set */ public int getPA_ReportLineSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID); if (ii == null) return 0; return ii.intValue(); } /** PostingType AD_Reference_ID=125 */ public static final int POSTINGTYPE_AD_Reference_ID=125; /** Actual = A */ public static final String POSTINGTYPE_Actual = "A"; /** Budget = B */ public static final String POSTINGTYPE_Budget = "B"; /** Commitment = E */ public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */ public static final String POSTINGTYPE_Statistical = "S"; /** Reservation = R */ public static final String POSTINGTYPE_Reservation = "R"; /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportLine.java
1
请完成以下Java代码
public static class DateValueImpl extends PrimitiveTypeValueImpl<Date> implements DateValue { private static final long serialVersionUID = 1L; public DateValueImpl(Date value) { super(value, ValueType.DATE); } public DateValueImpl(Date value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class DoubleValueImpl extends PrimitiveTypeValueImpl<Double> implements DoubleValue { private static final long serialVersionUID = 1L; public DoubleValueImpl(Double value) { super(value, ValueType.DOUBLE); } public DoubleValueImpl(Double value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class IntegerValueImpl extends PrimitiveTypeValueImpl<Integer> implements IntegerValue { private static final long serialVersionUID = 1L; public IntegerValueImpl(Integer value) { super(value, ValueType.INTEGER); } public IntegerValueImpl(Integer value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class LongValueImpl extends PrimitiveTypeValueImpl<Long> implements LongValue { private static final long serialVersionUID = 1L; public LongValueImpl(Long value) { super(value, ValueType.LONG); } public LongValueImpl(Long value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class ShortValueImpl extends PrimitiveTypeValueImpl<Short> implements ShortValue {
private static final long serialVersionUID = 1L; public ShortValueImpl(Short value) { super(value, ValueType.SHORT); } public ShortValueImpl(Short value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class StringValueImpl extends PrimitiveTypeValueImpl<String> implements StringValue { private static final long serialVersionUID = 1L; public StringValueImpl(String value) { super(value, ValueType.STRING); } public StringValueImpl(String value, boolean isTransient) { this(value); this.isTransient = isTransient; } } public static class NumberValueImpl extends PrimitiveTypeValueImpl<Number> implements NumberValue { private static final long serialVersionUID = 1L; public NumberValueImpl(Number value) { super(value, ValueType.NUMBER); } public NumberValueImpl(Number value, boolean isTransient) { this(value); this.isTransient = isTransient; } } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\value\PrimitiveTypeValueImpl.java
1
请完成以下Java代码
public Article writeArticle(ArticleContents contents) { return new Article(this, contents); } public Article updateArticle(Article article, ArticleUpdateRequest request) { if (article.getAuthor() != this) { throw new IllegalAccessError("Not authorized to update this article"); } article.updateArticle(request); return article; } public Comment writeCommentToArticle(Article article, String body) { return article.addComment(this, body); } public Article favoriteArticle(Article articleToFavorite) { articleFavorited.add(articleToFavorite); return articleToFavorite.afterUserFavoritesArticle(this); } public Article unfavoriteArticle(Article articleToUnfavorite) { articleFavorited.remove(articleToUnfavorite); return articleToUnfavorite.afterUserUnFavoritesArticle(this); } User followUser(User followee) { followingUsers.add(followee); return this; } User unfollowUser(User followee) { followingUsers.remove(followee); return this; } public void deleteArticleComment(Article article, long commentId) { article.removeCommentByUser(this, commentId); } public Set<Comment> viewArticleComments(Article article) { return article.getComments().stream() .map(this::viewComment) .collect(toSet()); } Comment viewComment(Comment comment) { viewProfile(comment.getAuthor()); return comment; } Profile viewProfile(User user) { return user.profile.withFollowing(followingUsers.contains(user)); } public Profile getProfile() { return profile; } boolean matchesPassword(String rawPassword, PasswordEncoder passwordEncoder) { return password.matchesPassword(rawPassword, passwordEncoder); } void changeEmail(Email email) { this.email = email; } void changePassword(Password password) { this.password = password; } void changeName(UserName userName) { profile.changeUserName(userName); } void changeBio(String bio) { profile.changeBio(bio); } void changeImage(Image image) { profile.changeImage(image);
} public Long getId() { return id; } public Email getEmail() { return email; } public UserName getName() { return profile.getUserName(); } String getBio() { return profile.getBio(); } Image getImage() { return profile.getImage(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final var user = (User) o; return email.equals(user.email); } @Override public int hashCode() { return Objects.hash(email); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java
1
请在Spring Boot框架中完成以下Java代码
public User signup(UserRegistry registry) { if (userRepository.existsBy(registry.email(), registry.username())) { throw new IllegalArgumentException("email or username is already exists."); } var requester = new User(registry); requester.encryptPassword(passwordEncoder, registry.password()); return userRepository.save(requester); } /** * Login to the system. * * @param email users email * @param password users password * @return Returns the logged-in user */ public User login(String email, String password) { if (email == null || email.isBlank()) { throw new IllegalArgumentException("email is required."); } if (password == null || password.isBlank()) { throw new IllegalArgumentException("password is required."); } return userRepository .findByEmail(email) .filter(user -> passwordEncoder.matches(password, user.getPassword())) .orElseThrow(() -> new IllegalArgumentException("invalid email or password.")); } /** * Update user information. * * @param userId The user who requested the update
* @param email users email * @param username users username * @param password users password * @param bio users bio * @param imageUrl users imageUrl * @return Returns the updated user */ public User updateUserDetails( UUID userId, String email, String username, String password, String bio, String imageUrl) { if (userId == null) { throw new IllegalArgumentException("user id is required."); } return userRepository.updateUserDetails(userId, passwordEncoder, email, username, password, bio, imageUrl); } }
repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
private static void initializeValidators() { HibernateValidatorConfiguration validatorConfiguration = Validation.byProvider(HibernateValidator.class).configure(); ConstraintMapping constraintMapping = getCustomConstraintMapping(); validatorConfiguration.addMapping(constraintMapping); try (var validatorFactory = validatorConfiguration.buildValidatorFactory()) { fieldsValidator = validatorFactory.getValidator(); } } @Bean public LocalValidatorFactoryBean validatorFactoryBean() { LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); localValidatorFactoryBean.setConfigurationInitializer(configuration -> { ((ConfigurationImpl) configuration).addMapping(getCustomConstraintMapping());
}); return localValidatorFactoryBean; } private static ConstraintMapping getCustomConstraintMapping() { ConstraintMapping constraintMapping = new DefaultConstraintMapping(null); constraintMapping.constraintDefinition(NoXss.class).validatedBy(NoXssValidator.class); constraintMapping.constraintDefinition(Length.class).validatedBy(StringLengthValidator.class); constraintMapping.constraintDefinition(RateLimit.class).validatedBy(RateLimitValidator.class); constraintMapping.constraintDefinition(NoNullChar.class).validatedBy(NoNullCharValidator.class); constraintMapping.constraintDefinition(ValidJsonSchema.class).validatedBy(JsonSchemaValidator.class); return constraintMapping; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\ConstraintValidator.java
2
请完成以下Java代码
protected Object evaluateFeelSimpleExpression(String expressionText, VariableContext variableContext) { return feelEngine.evaluateSimpleExpression(expressionText, variableContext); } // helper /////////////////////////////////////////////////////////////////// protected String getExpressionTextForLanguage(DmnExpressionImpl expression, String expressionLanguage) { String expressionText = expression.getExpression(); if (expressionText != null) { if (isJuelExpression(expressionLanguage) && !StringUtil.isExpression(expressionText)) { return "${" + expressionText + "}"; } else { return expressionText; } } else { return null; } } private boolean isJuelExpression(String expressionLanguage) { return DefaultDmnEngineConfiguration.JUEL_EXPRESSION_LANGUAGE.equalsIgnoreCase(expressionLanguage); } protected ScriptEngine getScriptEngineForName(String expressionLanguage) { ensureNotNull("expressionLanguage", expressionLanguage); ScriptEngine scriptEngine = scriptEngineResolver.getScriptEngineForLanguage(expressionLanguage); if (scriptEngine != null) { return scriptEngine;
} else { throw LOG.noScriptEngineFoundForLanguage(expressionLanguage); } } protected boolean isElExpression(String expressionLanguage) { return isJuelExpression(expressionLanguage); } public boolean isFeelExpressionLanguage(String expressionLanguage) { ensureNotNull("expressionLanguage", expressionLanguage); return expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE) || expressionLanguage.toLowerCase().equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_ALTERNATIVE) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14) || expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\ExpressionEvaluationHandler.java
1
请完成以下Java代码
public boolean hasFieldValue(final String fieldName) { return po.get_ColumnIndex(fieldName) >= 0; } @Override public Object getFieldValue(final String fieldName) { return po.get_Value(fieldName); } } @AllArgsConstructor private static final class GridTabSourceDocument implements SourceDocument { @NonNull
private final GridTab gridTab; @Override public boolean hasFieldValue(final String fieldName) { return gridTab.getField(fieldName) != null; } @Override public Object getFieldValue(final String fieldName) { return gridTab.getValue(fieldName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java
1
请完成以下Java代码
public long getAnfragePzn() { return anfragePzn; } /** * Sets the value of the anfragePzn property. * */ public void setAnfragePzn(long value) { this.anfragePzn = value; } /** * Gets the value of the substitution property. * * @return * possible object is * {@link VerfuegbarkeitSubstitution } * */ public VerfuegbarkeitSubstitution getSubstitution() { return substitution; } /** * Sets the value of the substitution property. * * @param value * allowed object is * {@link VerfuegbarkeitSubstitution } * */ public void setSubstitution(VerfuegbarkeitSubstitution value) { this.substitution = value; } /** * Gets the value of the anteile property.
* * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the anteile property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAnteile().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link VerfuegbarkeitAnteil } * * */ public List<VerfuegbarkeitAnteil> getAnteile() { if (anteile == null) { anteile = new ArrayList<VerfuegbarkeitAnteil>(); } return this.anteile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsantwortArtikel.java
1
请在Spring Boot框架中完成以下Java代码
private String getSenderId() { final CustomerType customerType = document.getCustomer(); if (customerType == null) { throw new RuntimeException("No customer found for document! doc: " + document); } return getGLNFromBusinessEntityType(customerType); } @NonNull private String getRecipientId() { return getGLNFromBusinessEntityType(document.getSupplier()); } private String getGLNFromBusinessEntityType(@NonNull final BusinessEntityType businessEntityType) { if (Check.isNotBlank(businessEntityType.getGLN())) { return GLN_PREFIX + businessEntityType.getGLN(); } final String gln = businessEntityType.getFurtherIdentification() .stream() .filter(furtherIdentificationType -> furtherIdentificationType.getIdentificationType().equals("GLN")) .findFirst() .map(FurtherIdentificationType::getValue) .orElseThrow(() -> new RuntimeException("No GLN found for businessEntity!businessEntity: " + businessEntityType)); return GLN_PREFIX + gln; } private String getDocumentDate() { return document.getDocumentDate() .toGregorianCalendar() .toZonedDateTime() .withZoneSameLocal(ZoneId.of(DOCUMENT_ZONE_ID)) .toInstant() .toString();
} private Optional<BigDecimal> asBigDecimal(@Nullable final String value) { if (Check.isBlank(value)) { return Optional.empty(); } try { final BigDecimal bigDecimalValue = new BigDecimal(value); return Optional.of(bigDecimalValue.abs()); } catch (final Exception e) { return Optional.empty(); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\remadvimport\ecosio\JsonRemittanceAdviceProducer.java
2
请完成以下Java代码
public PathMatcher getPathMatcher(String syntaxAndPattern) { throw new UnsupportedOperationException("Nested paths do not support path matchers"); } @Override public UserPrincipalLookupService getUserPrincipalLookupService() { throw new UnsupportedOperationException("Nested paths do not have a user principal lookup service"); } @Override public WatchService newWatchService() throws IOException { throw new UnsupportedOperationException("Nested paths do not support the WatchService"); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } NestedFileSystem other = (NestedFileSystem) obj; return this.jarPath.equals(other.jarPath);
} @Override public int hashCode() { return this.jarPath.hashCode(); } @Override public String toString() { return this.jarPath.toAbsolutePath().toString(); } private void assertNotClosed() { if (this.closed) { throw new ClosedFileSystemException(); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystem.java
1
请完成以下Java代码
public boolean isSaveInHistoric () { Object oo = get_Value(COLUMNNAME_IsSaveInHistoric); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Deleted. @param LastDeleted Last Deleted */ public void setLastDeleted (int LastDeleted) { set_Value (COLUMNNAME_LastDeleted, Integer.valueOf(LastDeleted)); } /** Get Last Deleted. @return Last Deleted */ public int getLastDeleted () { Integer ii = (Integer)get_Value(COLUMNNAME_LastDeleted); if (ii == null) return 0; return ii.intValue(); } /** Set Last Run. @param LastRun Last Run */ public void setLastRun (Timestamp LastRun) { set_Value (COLUMNNAME_LastRun, LastRun); } /** Get Last Run. @return Last Run */ public Timestamp getLastRun () { return (Timestamp)get_Value(COLUMNNAME_LastRun); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_HouseKeeping.java
1
请完成以下Java代码
public List<DmnElementReference> getOutputDecisions() { return outputDecisions; } public void setOutputDecisions(List<DmnElementReference> outputDecisions) { this.outputDecisions = outputDecisions; } public void addOutputDecision(DmnElementReference outputDecision) { this.outputDecisions.add(outputDecision); } public List<DmnElementReference> getEncapsulatedDecisions() { return encapsulatedDecisions; } public void setEncapsulatedDecisions(List<DmnElementReference> encapsulatedDecisions) { this.encapsulatedDecisions = encapsulatedDecisions; } public void addEncapsulatedDecision(DmnElementReference encapsulatedDecision) { this.encapsulatedDecisions.add(encapsulatedDecision); } public List<DmnElementReference> getInputDecisions() { return inputDecisions; } public void setInputDecisions(List<DmnElementReference> inputDecisions) { this.inputDecisions = inputDecisions; }
public void addInputDecision(DmnElementReference inputDecision) { this.inputDecisions.add(inputDecision); } public List<DmnElementReference> getInputData() { return inputData; } public void setInputData(List<DmnElementReference> inputData) { this.inputData = inputData; } public void addInputData(DmnElementReference inputData) { this.inputData.add(inputData); } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionService.java
1
请完成以下Java代码
public List call() throws Exception { List<Type> result = (List<Type>) executeCallSingleValueReturn(function, List.class); return convertToNative(result); } }); } public RemoteCall<TransactionReceipt> enter(BigInteger weiValue) { final Function function = new Function( FUNC_ENTER, Arrays.<Type>asList(), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function, weiValue); } public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, credentials, contractGasProvider, BINARY, ""); } public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, transactionManager, contractGasProvider, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); } @Deprecated
public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, credentials, gasPrice, gasLimit); } @Deprecated public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, credentials, contractGasProvider); } public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, transactionManager, contractGasProvider); } }
repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\model\Lottery.java
1
请完成以下Java代码
public abstract class C_Flatrate_Term_Change_Base extends JavaProcess { private final IContractChangeBL contractChangeBL = Services.get(IContractChangeBL.class); public static final String PARAM_CHANGE_DATE = "EventDate"; public static final String PARAM_ACTION = I_C_Contract_Change.COLUMNNAME_Action; public static final String PARAM_TERMINATION_MEMO = I_C_Flatrate_Term.COLUMNNAME_TerminationMemo; public static final String PARAM_TERMINATION_REASON = I_C_Flatrate_Term.COLUMNNAME_TerminationReason; public static final String PARAM_IsCreditOpenInvoices = "IsCreditOpenInvoices"; public static final String PARAM_IsCloseInvoiceCandidate = "IsCloseInvoiceCandidate"; @Param(parameterName = PARAM_ACTION, mandatory = true) private String action; @Param(parameterName = PARAM_CHANGE_DATE, mandatory = true) private Timestamp changeDate; @Param(parameterName = PARAM_TERMINATION_MEMO) private String terminationMemo; @Param(parameterName = PARAM_TERMINATION_REASON) private String terminationReason; @Param(parameterName = PARAM_IsCreditOpenInvoices) private boolean isCreditOpenInvoices; @Param(parameterName = PARAM_IsCloseInvoiceCandidate) private boolean isCloseInvoiceCandidate;
@Override protected String doIt() { if (IContractChangeBL.ChangeTerm_ACTION_SwitchContract.equals(action)) { throw new AdempiereException("Not implemented"); } final IContractChangeBL.ContractChangeParameters contractChangeParameters = IContractChangeBL.ContractChangeParameters.builder() .changeDate(changeDate) .isCloseInvoiceCandidate(isCloseInvoiceCandidate) .terminationMemo(terminationMemo) .terminationReason(terminationReason) .isCreditOpenInvoices(isCreditOpenInvoices) .action(action) .build(); final Iterable<I_C_Flatrate_Term> flatrateTerms = getFlatrateTermsToChange(); flatrateTerms.forEach(currentTerm -> contractChangeBL.cancelContract(currentTerm, contractChangeParameters)); return MSG_OK; } protected abstract Iterable<I_C_Flatrate_Term> getFlatrateTermsToChange(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change_Base.java
1
请完成以下Java代码
public boolean isInfiniteQtyTUsPerLU() { return true; } @Override public BigDecimal getQtyTUsPerLU() { return null; } @Override public boolean isInfiniteQtyCUsPerTU() { return true;
} @Override public BigDecimal getQtyCUsPerTU() { return null; } @Override public I_C_UOM getQtyCUsPerTU_UOM() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\LUPIPackingInfo.java
1
请完成以下Java代码
public class BPartnerCreditLimit { public static final String METASFRESH_ID = "metasfreshId"; public static final String BPARTNER_ID = "bpartnerId"; public static final String AMOUNT = "amount"; public static final String DATE_FROM = "dateFrom"; public static final String CREDITLIMITTYPE = "creditLimitType"; @Nullable private BPartnerCreditLimitId id; @Setter(AccessLevel.NONE) @JsonIgnore @Nullable private BPartnerId bpartnerId; @JsonInclude(Include.NON_NULL) @NonNull private BigDecimal amount; @JsonInclude(Include.NON_NULL) @Nullable private LocalDate dateFrom; @JsonInclude(Include.NON_NULL) @NonNull private CreditLimitType creditLimitType; @Builder(toBuilder = true)
private BPartnerCreditLimit( @Nullable final BPartnerCreditLimitId id, @Nullable final LocalDate dateFrom, @NonNull final BigDecimal amount, @NonNull final CreditLimitType creditLimitType) { setId(id); this.dateFrom = dateFrom; this.amount = amount; this.creditLimitType = creditLimitType; } public BPartnerCreditLimit deepCopy() { final BPartnerCreditLimit.BPartnerCreditLimitBuilder builder = toBuilder(); return builder.build(); } public final void setId(@Nullable final BPartnerCreditLimitId id) { this.id = id; this.bpartnerId = id != null ? id.getBpartnerId() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerCreditLimit.java
1
请在Spring Boot框架中完成以下Java代码
public ApiResponse<CustomerMapping> getCustomerMappingWithHttpInfo(String albertaApiKey, String customerId) throws ApiException { com.squareup.okhttp.Call call = getCustomerMappingValidateBeforeCall(albertaApiKey, customerId, null, null); Type localVarReturnType = new TypeToken<CustomerMapping>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Zuordnung Kunde (WaWi) zu Patient (Alberta) abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, welche Alberta-Id dem jeweiligen Kunden zugeordnet ist * @param albertaApiKey (required) * @param customerId die Id des Kunden aus dem WaWi (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getCustomerMappingAsync(String albertaApiKey, String customerId, final ApiCallback<CustomerMapping> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getCustomerMappingValidateBeforeCall(albertaApiKey, customerId, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<CustomerMapping>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\CustomerMappingApi.java
2
请完成以下Java代码
public class QtyDemand_QtySupply_V_to_PP_Order_Candidate extends JavaProcess implements IProcessPrecondition { private final QtyDemandSupplyRepository demandSupplyRepository = SpringContextHolder.instance.getBean(QtyDemandSupplyRepository.class); private final PPOrderCandidateDAO ppOrderCandidateDAO = SpringContextHolder.instance.getBean(PPOrderCandidateDAO.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID())); final PPOrderCandidatesQuery ppOrderCandidatesQuery = PPOrderCandidatesQuery.builder()
.warehouseId(currentRow.getWarehouseId()) .orgId(currentRow.getOrgId()) .productId(currentRow.getProductId()) .attributesKey(currentRow.getAttributesKey()) .onlyNonZeroQty(true) .build(); final List<TableRecordReference> recordReferences = ppOrderCandidateDAO.listIdsByQuery(ppOrderCandidatesQuery) .stream() .map(id -> TableRecordReference.of(I_PP_Order_Candidate.Table_Name, id)) .collect(Collectors.toList()); getResult().setRecordsToOpen(recordReferences); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_PP_Order_Candidate.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this).addValue(tuHU).toString(); } private IHUProductStorage getHUProductStorage() { return huProductStorageSupplier.get(); } @Override public I_M_HU_PI getM_LU_HU_PI() { return null; } @Override public I_M_HU_PI getM_TU_HU_PI() { return Services.get(IHandlingUnitsBL.class).getPI(tuHU); } @Override public boolean isInfiniteQtyTUsPerLU() { return true; } @Override
public BigDecimal getQtyTUsPerLU() { return null; } @Override public boolean isInfiniteQtyCUsPerTU() { return false; } @Override public BigDecimal getQtyCUsPerTU() { final IHUProductStorage huProductStorage = getHUProductStorage(); return huProductStorage == null ? null : huProductStorage.getQty().toBigDecimal(); } @Override public I_C_UOM getQtyCUsPerTU_UOM() { final IHUProductStorage huProductStorage = getHUProductStorage(); return huProductStorage == null ? null : huProductStorage.getC_UOM(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\TUPackingInfo.java
1
请完成以下Java代码
public class EventHandlerImpl implements EventHandler { private final EventType eventType; public EventHandlerImpl(EventType eventType) { this.eventType = eventType; } public void handleIntermediateEvent(EventSubscriptionEntity eventSubscription, Object payload, Object localPayload, Object payloadToTriggeredScope, CommandContext commandContext) { PvmExecutionImpl execution = eventSubscription.getExecution(); ActivityImpl activity = eventSubscription.getActivity(); ensureNotNull("Error while sending signal for event subscription '" + eventSubscription.getId() + "': " + "no activity associated with event subscription", "activity", activity); if (payload instanceof Map) { execution.setVariables((Map<String, Object>)payload); } if (localPayload instanceof Map) { execution.setVariablesLocal((Map<String, Object>) localPayload); } if (payloadToTriggeredScope instanceof Map) { if (ActivityTypes.INTERMEDIATE_EVENT_MESSAGE.equals(activity.getProperty(BpmnProperties.TYPE.getName()))) { execution.setVariablesLocal((Map<String, Object>) payloadToTriggeredScope); } else { execution.getProcessInstance().setPayloadForTriggeredScope((Map<String, Object>) payloadToTriggeredScope); } } if(activity.equals(execution.getActivity())) { execution.signal("signal", null); }
else { // hack around the fact that the start event is referenced by event subscriptions for event subprocesses // and not the subprocess itself if (activity.getActivityBehavior() instanceof EventSubProcessStartEventActivityBehavior) { activity = (ActivityImpl) activity.getFlowScope(); } execution.executeEventHandlerActivity(activity); } } @Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, Object localPayload, Object payloadToTriggeredScope, String businessKey, CommandContext commandContext) { handleIntermediateEvent(eventSubscription, payload, localPayload, payloadToTriggeredScope, commandContext); } @Override public String getEventHandlerType() { return eventType.name(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\event\EventHandlerImpl.java
1
请完成以下Java代码
protected void leave(ActivityExecution execution) { if (hasCompensationHandler(execution)) { createCompensateEventSubscription(execution); } if (!hasLoopCharacteristics()) { super.leave(execution); } else if (hasMultiInstanceCharacteristics()) { multiInstanceActivityBehavior.leave(execution); } } protected boolean hasCompensationHandler(ActivityExecution execution) { return execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID) != null; } protected void createCompensateEventSubscription(ActivityExecution execution) { String compensationHandlerId = (String) execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID); ExecutionEntity executionEntity = (ExecutionEntity) execution; ActivityImpl compensationHandler = executionEntity.getProcessDefinition().findActivity(compensationHandlerId); PvmScope scopeActivity = compensationHandler.getParent(); ExecutionEntity scopeExecution = ScopeUtil.findScopeExecutionForScope(executionEntity, scopeActivity); CompensateEventSubscriptionEntity compensateEventSubscriptionEntity = CompensateEventSubscriptionEntity.createAndInsert(scopeExecution); compensateEventSubscriptionEntity.setActivity(compensationHandler); } protected boolean hasLoopCharacteristics() { return hasMultiInstanceCharacteristics(); } protected boolean hasMultiInstanceCharacteristics() { return multiInstanceActivityBehavior != null; } public MultiInstanceActivityBehavior getMultiInstanceActivityBehavior() { return multiInstanceActivityBehavior; } public void setMultiInstanceActivityBehavior(MultiInstanceActivityBehavior multiInstanceActivityBehavior) { this.multiInstanceActivityBehavior = multiInstanceActivityBehavior; } @Override public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception { if ("compensationDone".equals(signalName)) { signalCompensationDone(execution, signalData); } else {
super.signal(execution, signalName, signalData); } } protected void signalCompensationDone(ActivityExecution execution, Object signalData) { // default behavior is to join compensating executions and propagate the signal if all executions // have compensated // join compensating executions if (execution.getExecutions().isEmpty()) { if (execution.getParent() != null) { ActivityExecution parent = execution.getParent(); ((InterpretableExecution) execution).remove(); ((InterpretableExecution) parent).signal("compensationDone", signalData); } } else { ((ExecutionEntity) execution).forceUpdate(); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractBpmnActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private Long id; @NotNull(message = "First Name cannot be null") private String firstName; @Min(value = 15, message = "Age should not be less than 15") @Max(value = 65, message = "Age should not be greater than 65") private int age; @Email(regexp=".*@.*\\..*", message = "Email should be valid") private String email; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getEmail() { return email;
} public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-legacy\src\main\java\com\baeldung\swagger2boot\model\User.java
2
请完成以下Java代码
public void onNew(@NonNull final ICalloutRecord calloutRecord) { final I_M_CostRevaluation costRevaluation = calloutRecord.getModel(I_M_CostRevaluation.class); setDocTypeId(costRevaluation); } @CalloutMethod(columnNames = I_M_CostRevaluation.COLUMNNAME_C_DocType_ID) public void onDocTypeChanged(@NonNull final I_M_CostRevaluation costRevaluation) { setDocumentNo(costRevaluation); } private void setDocTypeId(final I_M_CostRevaluation costRevaluation) { final DocTypeId docTypeId = docTypeDAO.getDocTypeIdOrNull(DocTypeQuery.builder() .docBaseType(DocBaseType.CostRevaluation) .docSubType(DocTypeQuery.DOCSUBTYPE_Any) .adClientId(costRevaluation.getAD_Client_ID()) .adOrgId(costRevaluation.getAD_Org_ID()) .build()); if (docTypeId == null) { return; }
costRevaluation.setC_DocType_ID(docTypeId.getRepoId()); } private void setDocumentNo(final I_M_CostRevaluation costRevaluation) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(costRevaluation.getC_DocType_ID()); if (docTypeId == null) { return; } final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(docTypeDAO.getById(docTypeId)) .setOldDocumentNo(costRevaluation.getDocumentNo()) .setDocumentModel(costRevaluation) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { costRevaluation.setDocumentNo(documentNoInfo.getDocumentNo()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\callout\M_CostRevaluation.java
1
请完成以下Java代码
public class CorrelationSet { protected final String businessKey; protected final Map<String, Object> correlationKeys; protected final Map<String, Object> localCorrelationKeys; protected final String processInstanceId; protected final String processDefinitionId; protected final String tenantId; protected final boolean isTenantIdSet; protected final boolean isExecutionsOnly; public CorrelationSet(MessageCorrelationBuilderImpl builder) { this.businessKey = builder.getBusinessKey(); this.processInstanceId = builder.getProcessInstanceId(); this.correlationKeys = builder.getCorrelationProcessInstanceVariables(); this.localCorrelationKeys = builder.getCorrelationLocalVariables(); this.processDefinitionId = builder.getProcessDefinitionId(); this.tenantId = builder.getTenantId(); this.isTenantIdSet = builder.isTenantIdSet(); this.isExecutionsOnly = builder.isExecutionsOnly(); } public String getBusinessKey() { return businessKey; } public Map<String, Object> getCorrelationKeys() { return correlationKeys; } public Map<String, Object> getLocalCorrelationKeys() { return localCorrelationKeys; }
public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isExecutionsOnly() { return isExecutionsOnly; } @Override public String toString() { return "CorrelationSet [businessKey=" + businessKey + ", processInstanceId=" + processInstanceId + ", processDefinitionId=" + processDefinitionId + ", correlationKeys=" + correlationKeys + ", localCorrelationKeys=" + localCorrelationKeys + ", tenantId=" + tenantId + ", isTenantIdSet=" + isTenantIdSet + ", isExecutionsOnly=" + isExecutionsOnly + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\runtime\CorrelationSet.java
1
请完成以下Java代码
public boolean isAllowedToCreateInvoiceCandidateFor(final Object model) { final String tableName = InterfaceWrapperHelper.getModelTableName(model); final Collection<ModelWithoutInvoiceCandidateVetoer> listeners = tableName2Listeners.get(tableName); if (listeners == null) { return true; } for (final ModelWithoutInvoiceCandidateVetoer listener : listeners) { if (I_VETO.equals(listener.foundModelWithoutInvoiceCandidate(model))) { return false; } } return true; }
@NonNull private BigDecimal getActualDeliveredQty(@NonNull final org.compiere.model.I_M_InOutLine inOutLine) { final org.compiere.model.I_M_InOut inOut = inoutBL.getById(InOutId.ofRepoId(inOutLine.getM_InOut_ID())); final DocStatus docStatus = DocStatus.ofCode(inOut.getDocStatus()); Loggables.withLogger(logger, Level.DEBUG) .addLog("DocStatus for M_InOutLine_ID={} is {}", inOutLine.getM_InOutLine_ID(), docStatus.getCode()); if (docStatus.equals(DocStatus.Completed) || docStatus.equals(DocStatus.Closed)) { return inOutLine.getMovementQty(); } return ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandBL.java
1
请在Spring Boot框架中完成以下Java代码
public class AttributesIncludedTabDescriptor { @NonNull AttributesIncludedTabId id; @NonNull AttributeSetId attributeSetId; @NonNull ClientId clientId; @NonNull AdTableId parentTableId; @NonNull ITranslatableString caption; int seqNo; @NonNull ImmutableList<AttributesIncludedTabFieldDescriptor> fieldsInOrder; @NonNull @Getter(AccessLevel.NONE) ImmutableMap<AttributeId, AttributesIncludedTabFieldDescriptor> fieldsByAttributeId; @Builder private AttributesIncludedTabDescriptor( @NonNull final AttributesIncludedTabId id, @NonNull final AttributeSetId attributeSetId, @NonNull final ClientId clientId, @NonNull final AdTableId parentTableId, @NonNull final ITranslatableString caption, final int seqNo, @NonNull final List<AttributesIncludedTabFieldDescriptor> fields) { this.id = id; this.attributeSetId = attributeSetId; this.clientId = clientId; this.parentTableId = parentTableId; this.caption = caption; this.seqNo = seqNo; this.fieldsInOrder = ImmutableList.copyOf(fields); this.fieldsByAttributeId = Maps.uniqueIndex(fields, AttributesIncludedTabFieldDescriptor::getAttributeId);
} public ImmutableSet<AttributeId> getAttributeIds() { return fieldsByAttributeId.keySet(); } public AttributesIncludedTabFieldDescriptor getFieldByAttributeId(@NonNull final AttributeId attributeId) { final AttributesIncludedTabFieldDescriptor field = fieldsByAttributeId.get(attributeId); if (field == null) { throw new AdempiereException("Attribute " + attributeId + " not found in " + this); } return field; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\descriptor\AttributesIncludedTabDescriptor.java
2
请完成以下Java代码
public static LocalToRemoteSyncResult error( @NonNull final DataRecord datarecord, @NonNull final String errorMessage) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.ERROR) .errorMessage(errorMessage) .build(); } public enum LocalToRemoteStatus { INSERTED_ON_REMOTE, UPDATED_ON_REMOTE, UPSERTED_ON_REMOTE, DELETED_ON_REMOTE, UNCHANGED, ERROR; }
LocalToRemoteStatus localToRemoteStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private LocalToRemoteSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final LocalToRemoteStatus localToRemoteStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.localToRemoteStatus = localToRemoteStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\LocalToRemoteSyncResult.java
1
请完成以下Java代码
protected void addSignalStartEventSubscription(EventSubscriptionDeclaration signalEventDefinition, ProcessDefinitionEntity processDefinition) { EventSubscriptionEntity newSubscription = signalEventDefinition.createSubscriptionForStartEvent(processDefinition); newSubscription.insert(); } protected void addConditionalStartEventSubscription(EventSubscriptionDeclaration conditionalEventDefinition, ProcessDefinitionEntity processDefinition) { EventSubscriptionEntity newSubscription = conditionalEventDefinition.createSubscriptionForStartEvent(processDefinition); newSubscription.insert(); } enum ExprType { USER, GROUP; } protected void addAuthorizationsFromIterator(Set<Expression> exprSet, ProcessDefinitionEntity processDefinition, ExprType exprType) { if (exprSet != null) { for (Expression expr : exprSet) { IdentityLinkEntity identityLink = new IdentityLinkEntity(); identityLink.setProcessDef(processDefinition); if (exprType.equals(ExprType.USER)) { identityLink.setUserId(expr.toString()); } else if (exprType.equals(ExprType.GROUP)) { identityLink.setGroupId(expr.toString()); } identityLink.setType(IdentityLinkType.CANDIDATE); identityLink.setTenantId(processDefinition.getTenantId()); identityLink.insert(); } } } protected void addAuthorizations(ProcessDefinitionEntity processDefinition) { addAuthorizationsFromIterator(processDefinition.getCandidateStarterUserIdExpressions(), processDefinition, ExprType.USER); addAuthorizationsFromIterator(processDefinition.getCandidateStarterGroupIdExpressions(), processDefinition, ExprType.GROUP); } // context /////////////////////////////////////////////////////////////////////////////////////////// protected DbEntityManager getDbEntityManager() { return getCommandContext().getDbEntityManager(); } protected JobManager getJobManager() { return getCommandContext().getJobManager(); } protected JobDefinitionManager getJobDefinitionManager() { return getCommandContext().getJobDefinitionManager();
} protected EventSubscriptionManager getEventSubscriptionManager() { return getCommandContext().getEventSubscriptionManager(); } protected ProcessDefinitionManager getProcessDefinitionManager() { return getCommandContext().getProcessDefinitionManager(); } // getters/setters /////////////////////////////////////////////////////////////////////////////////// public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParser getBpmnParser() { return bpmnParser; } public void setBpmnParser(BpmnParser bpmnParser) { this.bpmnParser = bpmnParser; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\deployer\BpmnDeployer.java
1
请完成以下Java代码
public static IWord compile(IWord word) { String label = word.getLabel(); if ("nr".equals(label)) return new Word(word.getValue(), TAG_PEOPLE); else if ("m".equals(label) || "mq".equals(label)) return new Word(word.getValue(), TAG_NUMBER); else if ("t".equals(label)) return new Word(word.getValue(), TAG_TIME); else if ("ns".equals(label)) return new Word(word.getValue(), TAG_PLACE); // switch (word.getLabel()) // { // case "nr": // return new Word(word.getValue(), TAG_PEOPLE); // case "m": // case "mq": // return new Word(word.getValue(), TAG_NUMBER); // case "t": // return new Word(word.getValue(), TAG_TIME); // case "ns": // return new Word(word.getValue(), TAG_TIME); // } return word; } /** * 将word列表转为兼容的IWord列表 * * @param simpleSentenceList * @return */ public static List<List<IWord>> convert2CompatibleList(List<List<Word>> simpleSentenceList) {
List<List<IWord>> compatibleList = new LinkedList<List<IWord>>(); for (List<Word> wordList : simpleSentenceList) { compatibleList.add(new LinkedList<IWord>(wordList)); } return compatibleList; } public static List<IWord> spilt(List<IWord> wordList) { ListIterator<IWord> listIterator = wordList.listIterator(); while (listIterator.hasNext()) { IWord word = listIterator.next(); if (word instanceof CompoundWord) { listIterator.remove(); for (Word inner : ((CompoundWord) word).innerList) { listIterator.add(inner); } } } return wordList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\util\CorpusUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringBootApp { @Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) { SpringApplication.run(SpringBootApp.class, args); } @PostConstruct private void initDb() { System.out.println(String.format("****** Creating table: %s, and Inserting test data ******", "Employees")); String sqlStatements[] = { "drop table employees if exists", "create table employees(id serial,first_name varchar(255),last_name varchar(255))", "insert into employees(first_name, last_name) values('Eugen','Paraschiv')", "insert into employees(first_name, last_name) values('Scott','Tiger')" }; Arrays.asList(sqlStatements).stream().forEach(sql -> { System.out.println(sql); jdbcTemplate.execute(sql); }); System.out.println(String.format("****** Fetching from table: %s ******", "Employees")); jdbcTemplate.query("select id,first_name,last_name from employees", new RowMapper<Object>() {
@Override public Object mapRow(ResultSet rs, int i) throws SQLException { System.out.println(String.format("id:%s,first_name:%s,last_name:%s", rs.getString("id"), rs.getString("first_name"), rs.getString("last_name"))); return null; } }); } @Bean(initMethod = "start", destroyMethod = "stop") public Server inMemoryH2DatabaseServer() throws SQLException { return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9091"); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2db\demo\server\SpringBootApp.java
2
请完成以下Java代码
public void setIngredients(final String ingredients) { this.ingredients = ingredients; ingredientsSet = true; } public void setCurrentVendor(final Boolean currentVendor) { this.currentVendor = currentVendor; currentVendorSet = true; } public void setExcludedFromSales(final Boolean excludedFromSales) { this.excludedFromSales = excludedFromSales; excludedFromSalesSet = true; } public void setExclusionFromSalesReason(final String exclusionFromSalesReason) { this.exclusionFromSalesReason = exclusionFromSalesReason; exclusionFromSalesReasonSet = true; } public void setDropShip(final Boolean dropShip) { this.dropShip = dropShip; dropShipSet = true; } public void setUsedForVendor(final Boolean usedForVendor) { this.usedForVendor = usedForVendor;
usedForVendorSet = true; } public void setExcludedFromPurchase(final Boolean excludedFromPurchase) { this.excludedFromPurchase = excludedFromPurchase; excludedFromPurchaseSet = true; } public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason) { this.exclusionFromPurchaseReason = exclusionFromPurchaseReason; exclusionFromPurchaseReasonSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java
1
请在Spring Boot框架中完成以下Java代码
public void afterCommit() { publishToMetasfreshAsync(); } public void publishToMetasfreshAsync() { logger.debug("Synchronizing: {}", this); // // Sync daily product supplies { final List<ProductSupply> productSupplies = ImmutableList.copyOf(this.productSupplies); this.productSupplies.clear(); pushDailyReportsAsync(productSupplies); } // // Sync weekly product supplies { final List<WeekSupply> weeklySupplies = ImmutableList.copyOf(this.weeklySupplies); this.weeklySupplies.clear();
pushWeeklyReportsAsync(weeklySupplies); } // // Sync RfQ changes { final List<Rfq> rfqs = ImmutableList.copyOf(this.rfqs); this.rfqs.clear(); pushRfqsAsync(rfqs); } // // Sync User changes { final List<User> users = ImmutableList.copyOf(this.users); this.users.clear(); pushUsersAsync(users); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SenderToMetasfreshService.java
2
请完成以下Java代码
public Authentication convert(HttpServletRequest request) { X509Certificate[] clientCertificateChain = (X509Certificate[]) request .getAttribute("jakarta.servlet.request.X509Certificate"); if (clientCertificateChain == null || clientCertificateChain.length == 0) { return null; } MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request); // client_id (REQUIRED) String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID); if (!StringUtils.hasText(clientId)) { return null; }
if (parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } Map<String, Object> additionalParameters = OAuth2EndpointUtils .getParametersIfMatchesAuthorizationCodeGrantRequest(request, OAuth2ParameterNames.CLIENT_ID); ClientAuthenticationMethod clientAuthenticationMethod = (clientCertificateChain.length == 1) ? ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH : ClientAuthenticationMethod.TLS_CLIENT_AUTH; return new OAuth2ClientAuthenticationToken(clientId, clientAuthenticationMethod, clientCertificateChain, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\X509ClientCertificateAuthenticationConverter.java
1
请在Spring Boot框架中完成以下Java代码
public EntityManager getEntityManager() { if (entityManager == null) { entityManager = getEntityManagerFactory().createEntityManager(); if (handleTransactions) { // Add transaction listeners, if transactions should be handled TransactionListener jpaTransactionCommitListener = new TransactionListener() { @Override public void execute(CommandContext commandContext) { if (isTransactionActive()) { entityManager.getTransaction().commit(); } } }; TransactionListener jpaTransactionRollbackListener = new TransactionListener() { @Override public void execute(CommandContext commandContext) { if (isTransactionActive()) { entityManager.getTransaction().rollback(); }
} }; TransactionContext transactionContext = Context.getTransactionContext(); transactionContext.addTransactionListener(TransactionState.COMMITTED, jpaTransactionCommitListener); transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, jpaTransactionRollbackListener); // Also, start a transaction, if one isn't started already if (!isTransactionActive()) { entityManager.getTransaction().begin(); } } } return entityManager; } private EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EntityManagerSessionImpl.java
2
请完成以下Java代码
public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() {
return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Set<Project> getProjects() { return projects; } public void setProjects(Set<Project> projects) { this.projects = projects; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\manytomany\model\Employee.java
1
请完成以下Java代码
public void setCamundaCandidateStarterUsersList(List<String> camundaCandidateStarterUsersList) { String candidateStarterUsers = StringUtil.joinCommaSeparatedList(camundaCandidateStarterUsersList); camundaCandidateStarterUsersAttribute.setValue(this, candidateStarterUsers); } public String getCamundaJobPriority() { return camundaJobPriorityAttribute.getValue(this); } public void setCamundaJobPriority(String jobPriority) { camundaJobPriorityAttribute.setValue(this, jobPriority); } @Override public String getCamundaTaskPriority() { return camundaTaskPriorityAttribute.getValue(this); } @Override public void setCamundaTaskPriority(String taskPriority) { camundaTaskPriorityAttribute.setValue(this, taskPriority); } @Override public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } @Override public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive); setCamundaHistoryTimeToLiveString(value); } @Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLiveAttribute.getValue(this); }
@Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { if (historyTimeToLive == null) { camundaHistoryTimeToLiveAttribute.removeAttribute(this); } else { camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive); } } @Override public Boolean isCamundaStartableInTasklist() { return camundaIsStartableInTasklistAttribute.getValue(this); } @Override public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) { camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist); } @Override public String getCamundaVersionTag() { return camundaVersionTagAttribute.getValue(this); } @Override public void setCamundaVersionTag(String versionTag) { camundaVersionTagAttribute.setValue(this, versionTag); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java
1
请完成以下Java代码
private static boolean mergeLinkToGroup(@NonNull final CustomizedWindowInfo link, @NonNull final ArrayList<AdWindowId> group) { Check.assume(link.getPreviousCustomizationWindowIds().isEmpty(), "previous customization windowIds shall be empty: {}", link); if (group.isEmpty()) { group.add(link.getBaseWindowId()); group.add(link.getCustomizationWindowId()); return true; } else if (AdWindowId.equals(link.getCustomizationWindowId(), first(group))) { group.add(0, link.getBaseWindowId()); return true; } else if (AdWindowId.equals(link.getBaseWindowId(), last(group))) { group.add(link.getCustomizationWindowId()); return true; } else { return false; } } private static boolean mergeGroups(@NonNull final ArrayList<AdWindowId> targetGroup, @NonNull final ArrayList<AdWindowId> group) { if (AdWindowId.equals(last(targetGroup), first(group))) { targetGroup.addAll(group.subList(1, group.size())); group.clear(); return true;
} else if (AdWindowId.equals(last(group), first(targetGroup))) { targetGroup.addAll(0, group.subList(0, group.size() - 1)); group.clear(); return true; } else { return false; } } private static AdWindowId first(@NonNull final ArrayList<AdWindowId> group) { return group.get(0); } private static AdWindowId last(@NonNull final ArrayList<AdWindowId> group) { return group.get(group.size() - 1); } public Optional<CustomizedWindowInfo> getCustomizedWindowInfo(@NonNull final AdWindowId baseWindowId) { return Optional.ofNullable(effectiveCustomizedWindowInfos.get(baseWindowId)); } public boolean isTopLevelCustomizedWindow(@NonNull final AdWindowId adWindowId) { final CustomizedWindowInfo customizedWindowInfo = effectiveCustomizedWindowInfos.get(adWindowId); return customizedWindowInfo == null || AdWindowId.equals(customizedWindowInfo.getCustomizationWindowId(), adWindowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\CustomizedWindowInfoMap.java
1
请完成以下Java代码
public void deleteExistingADElementLinkForTabId(final AdTabId adTabId) { // IMPORTANT: we have to call delete directly because we don't want to have the AD_Element_Link_ID is the migration scripts DB.executeUpdateAndThrowExceptionOnFail( "DELETE FROM " + I_AD_Element_Link.Table_Name + " WHERE AD_Tab_ID=" + adTabId.getRepoId(), ITrx.TRXNAME_ThreadInherited); } @Override public void recreateADElementLinkForWindowId(final AdWindowId adWindowId) { deleteExistingADElementLinkForWindowId(adWindowId); createADElementLinkForWindowId(adWindowId); } @Override public void createADElementLinkForWindowId(final AdWindowId adWindowId)
{ // NOTE: no params because we want to log migration scripts DB.executeFunctionCallEx(ITrx.TRXNAME_ThreadInherited, MigrationScriptFileLoggerHolder.DDL_PREFIX + "select AD_Element_Link_Create_Missing_Window(" + adWindowId.getRepoId() + ")", new Object[] {}); } @Override public void deleteExistingADElementLinkForWindowId(final AdWindowId adWindowId) { // IMPORTANT: we have to call delete directly because we don't want to have the AD_Element_Link_ID is the migration scripts DB.executeUpdateAndThrowExceptionOnFail( "DELETE FROM " + I_AD_Element_Link.Table_Name + " WHERE AD_Window_ID=" + adWindowId.getRepoId(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\element\api\impl\ElementLinkBL.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @PartitionKey private int id; @CqlName("username") private String userName; @ClusteringColumn private int userAge; @Computed("writetime(userName)") private long writetime; public User() { } public User(int id, String userName, int userAge) { this.id = id; this.userName = userName; this.userAge = userAge; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }
public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } public long getWritetime() { return writetime; } public void setWritetime(long writetime) { this.writetime = writetime; } }
repos\tutorials-master\persistence-modules\spring-data-cassandra-2\src\main\java\org\baeldung\objectmapper\entity\User.java
2
请在Spring Boot框架中完成以下Java代码
public class FatalExceptionStrategyAmqpConfiguration { @Bean public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory( ConnectionFactory connectionFactory, SimpleRabbitListenerContainerFactoryConfigurer configurer) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); factory.setErrorHandler(errorHandler()); return factory; } @Bean public ErrorHandler errorHandler() { return new ConditionalRejectingErrorHandler(customExceptionStrategy()); } @Bean FatalExceptionStrategy customExceptionStrategy() { return new CustomFatalExceptionStrategy(); }
@Bean Queue messagesQueue() { return QueueBuilder.durable(QUEUE_MESSAGES) .build(); } @Bean DirectExchange messagesExchange() { return new DirectExchange(EXCHANGE_MESSAGES); } @Bean Binding bindingMessages() { return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\configuration\FatalExceptionStrategyAmqpConfiguration.java
2
请完成以下Java代码
public class AirlineGates { @Id String id; @Version Long version; @QueryIndexed String name; String iata; Long gates; public AirlineGates(String id, String name, String iata, Long gates) { this.id = id; this.name = name; this.iata = iata; this.gates = gates; } public String getId() { return id; }
public Long getGates() { return gates; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"id\":" + id); sb.append(", \"name\":" + name); sb.append(", \"iata\":" + iata); sb.append(", \"gates\":" + gates); sb.append("}"); return sb.toString(); } }
repos\spring-data-examples-main\couchbase\transactions\src\main\java\com\example\demo\AirlineGates.java
1
请完成以下Java代码
private void dbUpdateM_PricingSystems(final ImportRecordsSelection selection) { { final StringBuilder sql = new StringBuilder("UPDATE I_BPartner i " + "SET M_PricingSystem_ID=(SELECT M_PricingSystem_ID FROM M_PricingSystem ps" + " WHERE i.PricingSystem_Value=ps.value AND ps.AD_Client_ID IN (0, i.AD_Client_ID) and ps.IsActive='Y' ) " + "WHERE M_PricingSystem_ID IS NULL AND PricingSystem_Value IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); executeUpdate("Set M_PricingSystem_ID={}", sql); } // { final StringBuilder sql = new StringBuilder("UPDATE I_BPartner i " + "SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid M_PricingSystem_ID, ' " + "WHERE M_PricingSystem_ID IS NULL AND PricingSystem_Value IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); executeUpdate("Flag records with invalid M_PricingSystem", sql); } } private void dbUpdatePO_PricingSystems(final ImportRecordsSelection selection) { { final StringBuilder sql = new StringBuilder("UPDATE I_BPartner i " + "SET PO_PricingSystem_ID=(SELECT M_PricingSystem_ID FROM M_PricingSystem ps"
+ " WHERE i.PO_PricingSystem_Value=ps.value AND ps.AD_Client_ID IN (0, i.AD_Client_ID) and IsActive='Y') " + "WHERE PO_PricingSystem_ID IS NULL AND PO_PricingSystem_Value IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); executeUpdate("Set PO_PricingSystem_ID", sql); } // { final StringBuilder sql = new StringBuilder("UPDATE I_BPartner i " + "SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid M_PricingSystem_ID, ' " + "WHERE PO_PricingSystem_ID IS NULL AND PO_PricingSystem_Value IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); executeUpdate("Flag records with invalid PO_PricingSystem_ID", sql); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportTableSqlUpdater.java
1
请完成以下Java代码
public int getC_Payment_Reservation_ID() { return get_ValueAsInt(COLUMNNAME_C_Payment_Reservation_ID); } @Override public void setExternalId (final @Nullable java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setPayPal_AuthorizationId (final @Nullable java.lang.String PayPal_AuthorizationId) { set_Value (COLUMNNAME_PayPal_AuthorizationId, PayPal_AuthorizationId); } @Override public java.lang.String getPayPal_AuthorizationId() { return get_ValueAsString(COLUMNNAME_PayPal_AuthorizationId); } @Override public void setPayPal_Order_ID (final int PayPal_Order_ID) { if (PayPal_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PayPal_Order_ID, PayPal_Order_ID); } @Override public int getPayPal_Order_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_Order_ID); } @Override
public void setPayPal_OrderJSON (final @Nullable java.lang.String PayPal_OrderJSON) { set_Value (COLUMNNAME_PayPal_OrderJSON, PayPal_OrderJSON); } @Override public java.lang.String getPayPal_OrderJSON() { return get_ValueAsString(COLUMNNAME_PayPal_OrderJSON); } @Override public void setPayPal_PayerApproveUrl (final @Nullable java.lang.String PayPal_PayerApproveUrl) { set_Value (COLUMNNAME_PayPal_PayerApproveUrl, PayPal_PayerApproveUrl); } @Override public java.lang.String getPayPal_PayerApproveUrl() { return get_ValueAsString(COLUMNNAME_PayPal_PayerApproveUrl); } @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Order.java
1
请完成以下Java代码
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) { return jobDataManager.findJobCountByQueryCriteria(jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { jobDataManager.updateJobTenantIdForDeployment(deploymentId, newTenantId); } @Override public void delete(JobEntity jobEntity) { super.delete(jobEntity); deleteExceptionByteArrayRef(jobEntity); removeExecutionLink(jobEntity); // Send event if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this) ); } } @Override public void delete(JobEntity entity, boolean fireDeleteEvent) { if (entity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( entity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setJobCount(executionEntity.getJobCount() - 1); } } super.delete(entity, fireDeleteEvent); } /**
* Removes the job's execution's reference to this job, if the job has an associated execution. * Subclasses may override to provide custom implementations. */ protected void removeExecutionLink(JobEntity jobEntity) { if (jobEntity.getExecutionId() != null) { ExecutionEntity execution = getExecutionEntityManager().findById(jobEntity.getExecutionId()); if (execution != null) { execution.getJobs().remove(jobEntity); } } } /** * Deletes a the byte array used to store the exception information. Subclasses may override * to provide custom implementations. */ protected void deleteExceptionByteArrayRef(JobEntity jobEntity) { ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef(); if (exceptionByteArrayRef != null) { exceptionByteArrayRef.delete(); } } public JobDataManager getJobDataManager() { return jobDataManager; } public void setJobDataManager(JobDataManager jobDataManager) { this.jobDataManager = jobDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\JobEntityManagerImpl.java
1
请完成以下Java代码
public void removeQueueProcessor(final int queueProcessorId) { mainLock.lock(); try { removeQueueProcessor0(queueProcessorId); } finally { mainLock.unlock(); } } private void removeQueueProcessor0(final int queueProcessorId) { final Optional<IQueueProcessor> queueProcessor = asyncProcessorPlanner.getQueueProcessor(QueueProcessorId.ofRepoId(queueProcessorId)); if (!queueProcessor.isPresent()) { return; } unregisterMBean(queueProcessor.get()); this.asyncProcessorPlanner.removeQueueProcessor(queueProcessor.get().getQueueProcessorId()); } @Override @Nullable public IQueueProcessor getQueueProcessor(@NonNull final QueueProcessorId queueProcessorId) { mainLock.lock(); try { return asyncProcessorPlanner .getQueueProcessor(queueProcessorId) .orElse(null); } finally { mainLock.unlock(); } } @Override public void shutdown() { mainLock.lock(); try { logger.info("Shutdown started"); asyncProcessorPlanner.getRegisteredQueueProcessors() .stream() .map(IQueueProcessor::getQueueProcessorId) .map(QueueProcessorId::getRepoId) .forEach(this::removeQueueProcessor0); this.asyncProcessorPlanner.shutdown(); logger.info("Shutdown finished"); } finally {
mainLock.unlock(); } } private void registerMBean(final IQueueProcessor queueProcessor) { unregisterMBean(queueProcessor); final JMXQueueProcessor processorMBean = new JMXQueueProcessor(queueProcessor, queueProcessor.getQueueProcessorId().getRepoId()); final String jmxName = createJMXName(queueProcessor); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { final ObjectName name = new ObjectName(jmxName); mbs.registerMBean(processorMBean, name); } catch (final MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | NullPointerException e) { e.printStackTrace(); } } private void unregisterMBean(@NonNull final IQueueProcessor queueProcessor) { final String jmxName = createJMXName(queueProcessor); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { final ObjectName name = new ObjectName(jmxName); mbs.unregisterMBean(name); } catch (final InstanceNotFoundException e) { // nothing // e.printStackTrace(); } catch (final MalformedObjectNameException | NullPointerException | MBeanRegistrationException e) { e.printStackTrace(); } } private IQueueProcessor createProcessor(@NonNull final I_C_Queue_Processor processorDef) { final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForPackageProcessing(processorDef); return queueProcessorFactory.createAsynchronousQueueProcessor(processorDef, queue); } private static String createJMXName(@NonNull final IQueueProcessor queueProcessor) { return QueueProcessorsExecutor.class.getName() + ":type=" + queueProcessor.getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorsExecutor.java
1
请完成以下Spring Boot application配置
spring: application: name: price-service server: port: '8081' management: tracing: sampling: probability: '1.0' otlp:
tracing: endpoint: http://collector:4318/v1/traces
repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry2\src\main\resources\application.yml
2
请完成以下Java代码
public Optional<HttpHeadersWrapper> getRequestHeaders(@NonNull final ObjectMapper objectMapper) { if (Check.isBlank(httpHeaders)) { return Optional.empty(); } try { return Optional.of(objectMapper.readValue(httpHeaders, HttpHeadersWrapper.class)); } catch (final JsonProcessingException e) { throw new AdempiereException("Failed to parse httpHeaders!") .appendParametersToMessage() .setParameter("ApiAuditRequest", this); } } @NonNull public Optional<Object> getRequestBody(@NonNull final ObjectMapper objectMapper) {
if (Check.isBlank(body)) { return Optional.empty(); } try { return Optional.of(objectMapper.readValue(body, Object.class)); } catch (final JsonProcessingException e) { throw new AdempiereException("Failed to parse body!") .appendParametersToMessage() .setParameter("ApiAuditRequest", this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\request\ApiRequestAudit.java
1
请完成以下Java代码
private boolean isFailOnError() { return _failOnError; } @Override public DocumentNoBuilder setUsePreliminaryDocumentNo(final boolean usePreliminaryDocumentNo) { this._usePreliminaryDocumentNo = usePreliminaryDocumentNo; return this; } private boolean isUsePreliminaryDocumentNo() { return _usePreliminaryDocumentNo; } @NonNull private DocumentNoBuilder.CalendarYearMonthAndDay getCalendarYearMonthAndDay(@NonNull final DocumentSequenceInfo docSeqInfo) { final CalendarYearMonthAndDay.CalendarYearMonthAndDayBuilder calendarYearMonthAndDayBuilder = CalendarYearMonthAndDay.builder() .calendarYear(getCalendarYear(docSeqInfo.getDateColumn())) .calendarMonth(DEFAULT_CALENDAR_MONTH_TO_USE) .calendarDay(DEFAULT_CALENDAR_DAY_TO_USE); if (docSeqInfo.isStartNewDay()) { calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn())); calendarYearMonthAndDayBuilder.calendarDay(getCalendarDay(docSeqInfo.getDateColumn())); } else if (docSeqInfo.isStartNewMonth()) {
calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn())); } return calendarYearMonthAndDayBuilder.build(); } @Builder @Value private static class CalendarYearMonthAndDay { String calendarYear; String calendarMonth; String calendarDay; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilder.java
1
请完成以下Java代码
public void setResponseText (java.lang.String ResponseText) { set_Value (COLUMNNAME_ResponseText, ResponseText); } /** Get Antwort-Text. @return Anfrage-Antworttext */ @Override public java.lang.String getResponseText () { return (java.lang.String)get_Value(COLUMNNAME_ResponseText); } /** Set TransaktionsID Client. @param TransactionIDClient TransaktionsID Client */ @Override public void setTransactionIDClient (java.lang.String TransactionIDClient) { set_ValueNoCheck (COLUMNNAME_TransactionIDClient, TransactionIDClient); } /** Get TransaktionsID Client. @return TransaktionsID Client */
@Override public java.lang.String getTransactionIDClient () { return (java.lang.String)get_Value(COLUMNNAME_TransactionIDClient); } /** Set TransaktionsID Server. @param TransactionIDServer TransaktionsID Server */ @Override public void setTransactionIDServer (java.lang.String TransactionIDServer) { set_ValueNoCheck (COLUMNNAME_TransactionIDServer, TransactionIDServer); } /** Get TransaktionsID Server. @return TransaktionsID Server */ @Override public java.lang.String getTransactionIDServer () { return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Log.java
1
请在Spring Boot框架中完成以下Java代码
public BatchResponse getBatch(@ApiParam(name = "batchId") @PathVariable String batchId) { Batch batch = getBatchById(batchId); return restResponseFactory.createBatchResponse(batch); } @ApiOperation(value = "Get the batch document", tags = { "Batches" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the requested batch was found and the batch document has been returned. The response contains the raw batch document and always has a Content-type of application/json."), @ApiResponse(code = 404, message = "Indicates the requested batch was not found or the job does not have a batch document. Status-description contains additional information about the error.") }) @GetMapping("/management/batches/{batchId}/batch-document") public String getBatchDocument(@ApiParam(name = "batchId") @PathVariable String batchId, HttpServletResponse response) { Batch batch = getBatchById(batchId); String batchDocument = managementService.getBatchDocument(batchId); if (batchDocument == null) { throw new FlowableObjectNotFoundException("Batch with id '" + batch.getId() + "' does not have a batch document.", String.class); } response.setContentType("application/json"); return batchDocument; } @ApiOperation(value = "Delete a batch", tags = { "Batches" }, nickname = "deleteBatch", code = 204) @ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the batch was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested batch was not found.") }) @DeleteMapping("/management/batches/{batchId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteJob(@ApiParam(name = "batchId") @PathVariable String batchId) { Batch batch = getBatchById(batchId); if (restApiInterceptor != null) { restApiInterceptor.deleteBatch(batch); } try { managementService.deleteBatch(batchId); } catch (FlowableObjectNotFoundException aonfe) { // Re-throw to have consistent error-messaging across REST-api throw new FlowableObjectNotFoundException("Could not find a batch with id '" + batchId + "'.", Batch.class); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResource.java
2
请在Spring Boot框架中完成以下Java代码
public String getAuthorizationUserId() { return authorizationUserId; } public boolean isAuthorizationGroupsSet() { return authorizationGroupsSet; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() {
return withoutTenantId; } public boolean isIncludeAuthorization() { return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty()); } public List<List<String>> getSafeAuthorizationGroups() { return safeAuthorizationGroups; } public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) { this.safeAuthorizationGroups = safeAuthorizationGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CaseDefinitionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class AcceptPaymentDisputeRequest { public static final String SERIALIZED_NAME_RETURN_ADDRESS = "returnAddress"; @SerializedName(SERIALIZED_NAME_RETURN_ADDRESS) private ReturnAddress returnAddress; public static final String SERIALIZED_NAME_REVISION = "revision"; @SerializedName(SERIALIZED_NAME_REVISION) private Integer revision; public AcceptPaymentDisputeRequest returnAddress(ReturnAddress returnAddress) { this.returnAddress = returnAddress; return this; } /** * Get returnAddress * * @return returnAddress **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public ReturnAddress getReturnAddress() { return returnAddress; } public void setReturnAddress(ReturnAddress returnAddress) { this.returnAddress = returnAddress; } public AcceptPaymentDisputeRequest revision(Integer revision) { this.revision = revision; return this; } /** * This integer value indicates the revision number of the payment dispute. This field is required. The current revision number for a payment dispute can be retrieved with the getPaymentDispute method. Each time an action is taken against a payment dispute, this integer value increases by 1. * * @return revision **/ @javax.annotation.Nullable @ApiModelProperty(value = "This integer value indicates the revision number of the payment dispute. This field is required. The current revision number for a payment dispute can be retrieved with the getPaymentDispute method. Each time an action is taken against a payment dispute, this integer value increases by 1.") public Integer getRevision() { return revision; } public void setRevision(Integer revision) {
this.revision = revision; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AcceptPaymentDisputeRequest acceptPaymentDisputeRequest = (AcceptPaymentDisputeRequest)o; return Objects.equals(this.returnAddress, acceptPaymentDisputeRequest.returnAddress) && Objects.equals(this.revision, acceptPaymentDisputeRequest.revision); } @Override public int hashCode() { return Objects.hash(returnAddress, revision); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AcceptPaymentDisputeRequest {\n"); sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n"); sb.append(" revision: ").append(toIndentedString(revision)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AcceptPaymentDisputeRequest.java
2
请完成以下Java代码
public String getCallbackId() { return callbackId; } public Set<String> getCallBackIds() { return callbackIds; } public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public List<ExecutionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups;
} public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return null; } public String getParentScopeId() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public int getMaxIterations() { return maxIterations; } public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getExceptionStacktrace() { if (exceptionByteArrayRef == null) { return null; } byte[] bytes = exceptionByteArrayRef.getBytes(); if (bytes == null) { return null; } try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new ActivitiException("UTF-8 is not a supported encoding"); } } public void setExceptionStacktrace(String exception) { if (exceptionByteArrayRef == null) {
exceptionByteArrayRef = new ByteArrayRef(); } exceptionByteArrayRef.setValue("stacktrace", getUtf8Bytes(exception)); } public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } public ByteArrayRef getExceptionByteArrayRef() { return exceptionByteArrayRef; } protected byte[] getUtf8Bytes(String str) { if (str == null) { return null; } try { return str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new ActivitiException("UTF-8 is not a supported encoding"); } } @Override public String toString() { return getClass().getName() + " [id=" + id + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntityImpl.java
1
请完成以下Java代码
public DocumentPath getDocumentPath() { return documentPath; } public TableRecordReference getTableRecordReference() { return createTableRecordReferenceFromShipmentScheduleId(getShipmentScheduleId()); } @Override public ImmutableSet<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public List<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); } @Override public boolean hasAttributes() { return false; } @Override public IViewRowAttributes getAttributes() throws EntityNotFoundException { throw new EntityNotFoundException("Row does not support attributes"); } @Override public ViewId getIncludedViewId() {
return includedViewId; } public ShipmentScheduleId getShipmentScheduleId() { return shipmentScheduleId; } public Optional<OrderLineId> getSalesOrderLineId() { return salesOrderLineId; } public ProductId getProductId() { return product != null ? ProductId.ofRepoIdOrNull(product.getIdAsInt()) : null; } public Quantity getQtyOrderedWithoutPicked() { return qtyOrdered.subtract(qtyPicked).toZeroIfNegative(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRow.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<Student> findOne(String id) { return repo.findById(id); } public List<Student> findAll() { List<Student> people = new ArrayList<>(); Iterator<Student> it = repo.findAll().iterator(); while (it.hasNext()) { people.add(it.next()); } return people; } public List<Student> findByFirstName(String firstName) { return repo.findByFirstName(firstName); } public List<Student> findByLastName(String lastName) {
return repo.findByLastName(lastName); } public void create(Student student) { student.setCreated(DateTime.now()); repo.save(student); } public void update(Student student) { student.setUpdated(DateTime.now()); repo.save(student); } public void delete(Student student) { repo.delete(student); } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\StudentRepositoryService.java
2
请完成以下Java代码
public IView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = request.getViewId(); viewId.assertWindowId(WINDOWID); final OrderId orderId = request.getParameterAs(PARAM_PURCHASE_ORDER_ID, OrderId.class); Check.assumeNotNull(orderId, PARAM_PURCHASE_ORDER_ID + " is mandatory!"); final OrderAttachmentRows rows = rowsRepo.getByPurchaseOrderId(orderId); return OrderAttachmentView.builder() .attachmentEntryService(attachmentEntryService) .viewId(viewId) .rows(rows)
.build(); } @Override public ViewLayout getViewLayout(final WindowId windowId, final JSONViewDataType viewDataType, final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(WINDOWID) .setCaption(Services.get(IMsgBL.class).translatable(I_C_Order.COLUMNNAME_C_Order_ID)) .setAllowOpeningRowDetails(false) .allowViewCloseAction(ViewCloseAction.DONE) .addElementsFromViewRowClass(OrderAttachmentRow.class, viewDataType) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public I_C_BP_Group getById(@NonNull final BPGroupId bpGroupId) { return loadOutOfTrx(bpGroupId, I_C_BP_Group.class); } @Override public I_C_BP_Group getByIdInInheritedTrx(@NonNull final BPGroupId bpGroupId) { return load(bpGroupId, I_C_BP_Group.class); } @Override public I_C_BP_Group getByBPartnerId(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bpartnerRecord = Services.get(IBPartnerDAO.class).getById(bpartnerId); final BPGroupId bpGroupId = BPGroupId.ofRepoId(bpartnerRecord.getC_BP_Group_ID()); return getById(bpGroupId); } @Override public BPGroupId getBPGroupByBPartnerId(@NonNull final BPartnerId bpartnerId) { return BPGroupId.ofRepoId(getByBPartnerId(bpartnerId).getC_BP_Group_ID()); } @Override @Nullable public I_C_BP_Group getDefaultByClientOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { final BPGroupId bpGroupId = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_BP_Group.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Group.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addInArrayFilter(I_C_BP_Group.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId(), OrgId.ANY) .addEqualsFilter(I_C_BP_Group.COLUMNNAME_IsDefault, true) .orderByDescending(I_C_BP_Group.COLUMNNAME_AD_Org_ID) .create() .firstId(BPGroupId::ofRepoIdOrNull); if (bpGroupId == null) {
logger.warn("No default BP group found for {}", clientAndOrgId); return null; } return getById(bpGroupId); } @Override public BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull final BPGroupId bpGroupId) { final I_C_BP_Group bpGroup = getById(bpGroupId); return StringUtils.trimBlankToOptional(bpGroup.getBPNameAndGreetingStrategy()) .map(BPartnerNameAndGreetingStrategyId::ofString) .orElse(DoNothingBPartnerNameAndGreetingStrategy.ID); } @Override public void save(@NonNull final I_C_BP_Group bpGroup) { InterfaceWrapperHelper.saveRecord(bpGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPGroupDAO.java
2
请完成以下Java代码
public int getAD_Client_ID() { return invoiceLine.getAD_Client_ID(); } @Override public int getAD_Org_ID() { return invoiceLine.getAD_Org_ID(); } @Override public boolean isSOTrx() { final I_C_Invoice invoice = getInvoice(); return invoice.isSOTrx(); } @Override public I_C_BPartner getC_BPartner() { final I_C_Invoice invoice = getInvoice();
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner partner = InterfaceWrapperHelper.create(bpartnerDAO.getById(invoice.getC_BPartner_ID()), I_C_BPartner.class); if (partner == null) { return null; } return partner; } private I_C_Invoice getInvoice() { final I_C_Invoice invoice = invoiceLine.getC_Invoice(); if (invoice == null) { throw new AdempiereException("Invoice not set for" + invoiceLine); } return invoice; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InvoiceLineBPartnerAware.java
1
请完成以下Java代码
public NERTagSet getNERTagSet() { return tagSet; } private NERInstance createInstance(String[] wordArray, String[] posArray) { final FeatureTemplate[] featureTemplateArray = model.getFeatureTemplateArray(); return new NERInstance(wordArray, posArray, model.featureMap) { @Override protected int[] extractFeature(String[] wordArray, String[] posArray, FeatureMap featureMap, int position) { StringBuilder sbFeature = new StringBuilder(); List<Integer> featureVec = new LinkedList<Integer>(); for (int i = 0; i < featureTemplateArray.length; i++) { Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator(); Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator(); delimiterIterator.next(); // ignore U0 之类的id while (offsetIterator.hasNext()) { int[] offset = offsetIterator.next(); int t = offset[0] + position; boolean first = offset[1] == 0; if (t < 0) sbFeature.append(FeatureIndex.BOS[-(t + 1)]); else if (t >= wordArray.length) sbFeature.append(FeatureIndex.EOS[t - wordArray.length]); else sbFeature.append(first ? wordArray[t] : posArray[t]); if (delimiterIterator.hasNext()) sbFeature.append(delimiterIterator.next()); else sbFeature.append(i); } addFeatureThenClear(sbFeature, featureVec, featureMap); } return toFeatureArray(featureVec); } };
} @Override protected String getDefaultFeatureTemplate() { return "# Unigram\n" + // form "U0:%x[-2,0]\n" + "U1:%x[-1,0]\n" + "U2:%x[0,0]\n" + "U3:%x[1,0]\n" + "U4:%x[2,0]\n" + // pos "U5:%x[-2,1]\n" + "U6:%x[-1,1]\n" + "U7:%x[0,1]\n" + "U8:%x[1,1]\n" + "U9:%x[2,1]\n" + // pos 2-gram "UA:%x[-2,1]%x[-1,1]\n" + "UB:%x[-1,1]%x[0,1]\n" + "UC:%x[0,1]%x[1,1]\n" + "UD:%x[1,1]%x[2,1]\n" + "UE:%x[2,1]%x[3,1]\n" + "\n" + "# Bigram\n" + "B"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFNERecognizer.java
1
请在Spring Boot框架中完成以下Java代码
public void setImportMetadata(AnnotationMetadata importMetadata) { if (isAnnotationPresent(importMetadata)) { AnnotationAttributes enableDurableClientAttributes = getAnnotationAttributes(importMetadata); this.durableClientId = enableDurableClientAttributes.containsKey("id") ? enableDurableClientAttributes.getString("id") : null; this.durableClientTimeout = enableDurableClientAttributes.containsKey("timeout") ? enableDurableClientAttributes.getNumber("timeout") : DEFAULT_DURABLE_CLIENT_TIMEOUT; this.keepAlive = enableDurableClientAttributes.containsKey("keepAlive") ? enableDurableClientAttributes.getBoolean("keepAlive") : DEFAULT_KEEP_ALIVE; this.readyForEvents = enableDurableClientAttributes.containsKey("readyForEvents") ? enableDurableClientAttributes.getBoolean("readyForEvents") : DEFAULT_READY_FOR_EVENTS; } } protected Optional<String> getDurableClientId() { return Optional.ofNullable(this.durableClientId) .filter(StringUtils::hasText); } protected Integer getDurableClientTimeout() { return this.durableClientTimeout != null ? this.durableClientTimeout : DEFAULT_DURABLE_CLIENT_TIMEOUT; } protected Boolean getKeepAlive() { return this.keepAlive != null ? this.keepAlive : DEFAULT_KEEP_ALIVE; }
protected Boolean getReadyForEvents() { return this.readyForEvents != null ? this.readyForEvents : DEFAULT_READY_FOR_EVENTS; } protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive()); clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); } @Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(Long productId) { int count = memberCollectionService.delete(productId); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("显示当前用户商品收藏列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<MemberProductCollection>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { Page<MemberProductCollection> page = memberCollectionService.list(pageNum,pageSize); return CommonResult.success(CommonPage.restPage(page)); } @ApiOperation("显示商品收藏详情")
@RequestMapping(value = "/detail", method = RequestMethod.GET) @ResponseBody public CommonResult<MemberProductCollection> detail(@RequestParam Long productId) { MemberProductCollection memberProductCollection = memberCollectionService.detail(productId); return CommonResult.success(memberProductCollection); } @ApiOperation("清空当前用户商品收藏列表") @RequestMapping(value = "/clear", method = RequestMethod.POST) @ResponseBody public CommonResult clear() { memberCollectionService.clear(); return CommonResult.success(null); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberProductCollectionController.java
2
请完成以下Java代码
public User save(User entity) throws Exception { return userRepo.save(entity); } @Override public void delete(Long id) throws Exception { userRepo.delete(id); } @Override public void delete(User entity) throws Exception { userRepo.delete(entity); } @Override public User findById(Long id) { return userRepo.findOne(id); } @Override public User findBySample(User sample) { return userRepo.findOne(whereSpec(sample)); } @Override public List<User> findAll() { return userRepo.findAll(); } @Override public List<User> findAll(User sample) { return userRepo.findAll(whereSpec(sample)); } @Override public Page<User> findAll(PageRequest pageRequest) { return userRepo.findAll(pageRequest); }
@Override public Page<User> findAll(User sample, PageRequest pageRequest) { return userRepo.findAll(whereSpec(sample), pageRequest); } private Specification<User> whereSpec(final User sample){ return (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(); if (sample.getId()!=null){ predicates.add(cb.equal(root.<Long>get("id"), sample.getId())); } if (StringUtils.hasLength(sample.getUsername())){ predicates.add(cb.equal(root.<String>get("username"),sample.getUsername())); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User sample = new User(); sample.setUsername(username); User user = findBySample(sample); if( user == null ){ throw new UsernameNotFoundException(String.format("User with username=%s was not found", username)); } return user; } }
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\UserService.java
1
请完成以下Java代码
public class CreateWordDocument { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Add a section Section section = doc.addSection(); //Set the page margins section.getPageSetup().getMargins().setAll(40f); //Add a paragraph as title Paragraph titleParagraph = section.addParagraph(); titleParagraph.appendText("Introduction of Spire.Doc for Java"); //Add two paragraphs as body Paragraph bodyParagraph_1 = section.addParagraph(); bodyParagraph_1.appendText("Spire.Doc for Java is a professional Word API that empowers Java applications to " + "create, convert, manipulate and print Word documents without dependency on Microsoft Word."); Paragraph bodyParagraph_2 = section.addParagraph(); bodyParagraph_2.appendText("By using this multifunctional library, developers are able to process copious tasks " + "effortlessly, such as inserting image, hyperlink, digital signature, bookmark and watermark, setting " + "header and footer, creating table, setting background image, and adding footnote and endnote."); //Create and apply a style for title paragraph ParagraphStyle style1 = new ParagraphStyle(doc); style1.setName("titleStyle"); style1.getCharacterFormat().setBold(true);; style1.getCharacterFormat().setTextColor(Color.BLUE); style1.getCharacterFormat().setFontName("Times New Roman"); style1.getCharacterFormat().setFontSize(12f); doc.getStyles().add(style1); titleParagraph.applyStyle("titleStyle"); //Create and apply a style for body paragraphs ParagraphStyle style2 = new ParagraphStyle(doc); style2.setName("paraStyle"); style2.getCharacterFormat().setFontName("Times New Roman"); style2.getCharacterFormat().setFontSize(12); doc.getStyles().add(style2);
bodyParagraph_1.applyStyle("paraStyle"); bodyParagraph_2.applyStyle("paraStyle"); //Set the horizontal alignment of paragraphs titleParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); bodyParagraph_1.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify); bodyParagraph_2.getFormat().setHorizontalAlignment(HorizontalAlignment.Justify); //Set the first line indent bodyParagraph_1.getFormat().setFirstLineIndent(30) ; bodyParagraph_2.getFormat().setFirstLineIndent(30); //Set the after spacing titleParagraph.getFormat().setAfterSpacing(10); bodyParagraph_1.getFormat().setAfterSpacing(10); //Save to file doc.saveToFile("/Users/liuhaihua/tmp/WordDocument.docx", FileFormat.Docx_2013); doc.close(); } }
repos\springboot-demo-master\spire-doc\src\main\java\com\et\spire\doc\CreateWordDocument.java
1
请完成以下Java代码
public boolean isEmpty() {return list.isEmpty();} @Override @NonNull public Iterator<Candidate> iterator() {return list.iterator();} @Override public void forEach(@NonNull final Consumer<? super Candidate> action) {list.forEach(action);} public ClientAndOrgId getClientAndOrgId() { assertNotEmpty(); return list.get(0).getClientAndOrgId(); } public MaterialDispoGroupId getEffectiveGroupId() { assertNotEmpty(); return list.get(0).getEffectiveGroupId(); }
public CandidateBusinessCase getBusinessCase() { assertNotEmpty(); return CollectionUtils.extractSingleElement(list, Candidate::getBusinessCase); } public Candidate getSingleCandidate() { return CollectionUtils.singleElement(list); } public Candidate getSingleSupplyCandidate() { return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.SUPPLY)); } public Candidate getSingleDemandCandidate() { return CollectionUtils.singleElement(list, candidate -> CandidateType.equals(candidate.getType(), CandidateType.DEMAND)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidatesGroup.java
1
请在Spring Boot框架中完成以下Java代码
public void setExceptionStacktrace(String exception) { if (exceptionByteArrayRef == null) { exceptionByteArrayRef = new ByteArrayRef(); } exceptionByteArrayRef.setValue("stacktrace", exception, getEngineType()); } @Override public String getExceptionMessage() { return exceptionMessage; } @Override public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, JobInfo.MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String claimedBy) { this.lockOwner = claimedBy; } @Override public Date getLockExpirationTime() { return lockExpirationTime; } @Override public void setLockExpirationTime(Date claimedUntil) { this.lockExpirationTime = claimedUntil; } @Override public String getScopeType() { return scopeType;
} @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) { if (jobByteArrayRef == null) { return null; } return jobByteArrayRef.asString(getEngineType()); } protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoryJobEntity[").append("id=").append(id) .append(", jobHandlerType=").append(jobHandlerType); if (scopeType != null) { sb.append(", scopeType=").append(scopeType); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java
2
请完成以下Java代码
public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FAOpenItemTrxInfoComputeRequest request) { final AccountConceptualName accountConceptualName = request.getAccountConceptualName(); if (accountConceptualName == null) { return Optional.empty(); } if (I_C_BankStatement.Table_Name.equals(request.getTableName())) { if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { final BankStatementId bankStatementId = BankStatementId.ofRepoId(request.getRecordId()); final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(request.getLineId()); final BankStatementLineRefId bankStatementLineRefId = BankStatementLineRefId.ofRepoIdOrNull(request.getSubLineId()); return Optional.of(FAOpenItemTrxInfo.opening(FAOpenItemKey.bankStatementLine(bankStatementId, bankStatementLineId, bankStatementLineRefId, accountConceptualName))); } else { return Optional.empty(); } } else { return Optional.empty(); } } @Override public void onGLJournalLineCompleted(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementLineId -> bankStatementBL.markAsReconciledWithGLJournalLine(bankStatementLineId, line.getIdNotNull())); } }
@Override public void onGLJournalLineReactivated(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementBL::unreconcile); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\open_items_handler\BankStatementOIHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Void> delete(User user) { return db .sql("DELETE FROM jhi_user_authority WHERE user_id = :userId") .bind("userId", user.getId()) .then() .then(r2dbcEntityTemplate.delete(User.class).matching(query(where("id").is(user.getId()))).all().then()); } private Mono<User> findOneWithAuthoritiesBy(String fieldName, Object fieldValue) { return db .sql("SELECT * FROM jhi_user u LEFT JOIN jhi_user_authority ua ON u.id=ua.user_id WHERE u." + fieldName + " = :" + fieldName) .bind(fieldName, fieldValue) .map( (row, metadata) -> Tuples.of(r2dbcConverter.read(User.class, row, metadata), Optional.ofNullable(row.get("authority_name", String.class))) ) .all() .collectList() .filter(l -> !l.isEmpty()) .map(l -> updateUserWithAuthorities(l.get(0).getT1(), l)); }
private User updateUserWithAuthorities(User user, List<Tuple2<User, Optional<String>>> tuples) { user.setAuthorities( tuples .stream() .filter(t -> t.getT2().isPresent()) .map(t -> { Authority authority = new Authority(); authority.setName(t.getT2().orElseThrow()); return authority; }) .collect(Collectors.toSet()) ); return user; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\UserRepository.java
2
请完成以下Java代码
public String getTernary() { return ternary; } public void setTernary(String ternary) { this.ternary = ternary; } public String getTernary2() { return ternary2; } public void setTernary2(String ternary2) { this.ternary2 = ternary2; }
public String getElvis() { return elvis; } public void setElvis(String elvis) { this.elvis = elvis; } @Override public String toString() { return "SpelConditional{" + "ternary='" + ternary + '\'' + ", ternary2='" + ternary2 + '\'' + ", elvis='" + elvis + '\'' + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelConditional.java
1
请完成以下Java代码
public class Course { private int id; private String name; private String instructor; private Date enrolmentDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getInstructor() { return instructor; } public void setInstructor(String instructor) { this.instructor = instructor; } public Date getEnrolmentDate() { return enrolmentDate; } public void setEnrolmentDate(Date enrolmentDate) { this.enrolmentDate = enrolmentDate; } }
repos\tutorials-master\apache-cxf-modules\cxf-aegis\src\main\java\com\baeldung\cxf\aegis\Course.java
1
请完成以下Java代码
public void setC_Country_ID (int C_Country_ID) { if (C_Country_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Country_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID)); } /** Get Land. @return Country */ @Override public int getC_Country_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Region. @param C_Region_ID Identifies a geographical Region */ @Override public void setC_Region_ID (int C_Region_ID) { if (C_Region_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Region_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Region_ID, Integer.valueOf(C_Region_ID)); } /** Get Region. @return Identifies a geographical Region */ @Override public int getC_Region_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Region_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () {
return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Standard. @param IsDefault Default value */ @Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Standard. @return Default value */ @Override public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Region.java
1
请完成以下Java代码
public ProcessInstance getProcessInstance() { Execution execution = getExecution(); if(execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))){ return processEngine .getRuntimeService() .createProcessInstanceQuery() .processInstanceId(execution.getProcessInstanceId()) .singleResult(); } return (ProcessInstance) execution; } // internal implementation ////////////////////////////////////////////////////////// protected void assertExecutionAssociated() { if (associationManager.getExecution() == null) { throw new ProcessEngineCdiException("No execution associated. Call busniessProcess.associateExecutionById() or businessProcess.startTask() first.");
} } protected void assertTaskAssociated() { if (associationManager.getTask() == null) { throw new ProcessEngineCdiException("No task associated. Call businessProcess.startTask() first."); } } protected void assertCommandContextNotActive() { if(Context.getCommandContext() != null) { throw new ProcessEngineCdiException("Cannot use this method of the BusinessProcess bean from an active command context."); } } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\BusinessProcess.java
1
请在Spring Boot框架中完成以下Java代码
ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurer() { return configurer(); } @Bean(name = "kafkaListenerContainerFactoryConfigurer") @ConditionalOnMissingBean @ConditionalOnThreading(Threading.VIRTUAL) ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurerVirtualThreads() { ConcurrentKafkaListenerContainerFactoryConfigurer configurer = configurer(); SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("kafka-"); executor.setVirtualThreads(true); configurer.setListenerTaskExecutor(executor); return configurer; } private ConcurrentKafkaListenerContainerFactoryConfigurer configurer() { ConcurrentKafkaListenerContainerFactoryConfigurer configurer = new ConcurrentKafkaListenerContainerFactoryConfigurer(); configurer.setKafkaProperties(this.properties); configurer.setBatchMessageConverter(this.batchMessageConverter); configurer.setRecordMessageConverter(this.recordMessageConverter); configurer.setRecordFilterStrategy(this.recordFilterStrategy); configurer.setReplyTemplate(this.kafkaTemplate); configurer.setTransactionManager(this.transactionManager); configurer.setRebalanceListener(this.rebalanceListener); configurer.setCommonErrorHandler(this.commonErrorHandler); configurer.setAfterRollbackProcessor(this.afterRollbackProcessor); configurer.setRecordInterceptor(this.recordInterceptor); configurer.setBatchInterceptor(this.batchInterceptor); configurer.setThreadNameSupplier(this.threadNameSupplier); return configurer; } @Bean @ConditionalOnMissingBean(name = "kafkaListenerContainerFactory") ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
ConcurrentKafkaListenerContainerFactoryConfigurer configurer, ObjectProvider<ConsumerFactory<Object, Object>> kafkaConsumerFactory, ObjectProvider<ContainerCustomizer<Object, Object, ConcurrentMessageListenerContainer<Object, Object>>> kafkaContainerCustomizer) { ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); configurer.configure(factory, kafkaConsumerFactory .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); kafkaContainerCustomizer.ifAvailable(factory::setContainerCustomizer); return factory; } @Configuration(proxyBeanMethods = false) @EnableKafka @ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) static class EnableKafkaConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAnnotationDrivenConfiguration.java
2
请完成以下Java代码
public de.metas.aggregation.model.I_C_Aggregation getIncluded_Aggregation() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Included_Aggregation_ID, de.metas.aggregation.model.I_C_Aggregation.class); } @Override public void setIncluded_Aggregation(de.metas.aggregation.model.I_C_Aggregation Included_Aggregation) { set_ValueFromPO(COLUMNNAME_Included_Aggregation_ID, de.metas.aggregation.model.I_C_Aggregation.class, Included_Aggregation); } /** Set Included Aggregation. @param Included_Aggregation_ID Included Aggregation */ @Override public void setIncluded_Aggregation_ID (int Included_Aggregation_ID) { if (Included_Aggregation_ID < 1) set_Value (COLUMNNAME_Included_Aggregation_ID, null); else set_Value (COLUMNNAME_Included_Aggregation_ID, Integer.valueOf(Included_Aggregation_ID)); } /** Get Included Aggregation. @return Included Aggregation */ @Override public int getIncluded_Aggregation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Included_Aggregation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Include Logic. @param IncludeLogic If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public void setIncludeLogic (java.lang.String IncludeLogic) { set_Value (COLUMNNAME_IncludeLogic, IncludeLogic);
} /** Get Include Logic. @return If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded. */ @Override public java.lang.String getIncludeLogic () { return (java.lang.String)get_Value(COLUMNNAME_IncludeLogic); } /** * Type AD_Reference_ID=540532 * Reference name: C_AggregationItem_Type */ public static final int TYPE_AD_Reference_ID=540532; /** Column = COL */ public static final String TYPE_Column = "COL"; /** IncludedAggregation = INC */ public static final String TYPE_IncludedAggregation = "INC"; /** Attribute = ATR */ public static final String TYPE_Attribute = "ATR"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_AggregationItem.java
1
请完成以下Java代码
private boolean isToggleButton() { return toggleButton; } /** * Advice the builder to create a small size button. */ public Builder setSmallSize() { return setSmallSize(true); } /** * Advice the builder if a small size button is needed or not. * * @param smallSize true if small size button shall be created */ public Builder setSmallSize(final boolean smallSize) { this.smallSize = smallSize; return this; } private boolean isSmallSize() { return smallSize; } /** * Advice the builder to set given {@link Insets} to action's button. *
* @param buttonInsets * @see AbstractButton#setMargin(Insets) */ public Builder setButtonInsets(final Insets buttonInsets) { this.buttonInsets = buttonInsets; return this; } private final Insets getButtonInsets() { return buttonInsets; } /** * Sets the <code>defaultCapable</code> property, which determines whether the button can be made the default button for its root pane. * * @param defaultCapable * @return * @see JButton#setDefaultCapable(boolean) */ public Builder setButtonDefaultCapable(final boolean defaultCapable) { buttonDefaultCapable = defaultCapable; return this; } private Boolean getButtonDefaultCapable() { return buttonDefaultCapable; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AppsAction.java
1
请在Spring Boot框架中完成以下Java代码
public class UserAccount { @NotNull(message = "Password must be between 4 to 15 characters") @Size(min = 4, max = 15) private String password; @NotBlank(message = "Name must not be blank") private String name; @Min(value = 18, message = "Age should not be less than 18") private int age; @NotBlank(message = "Phone must not be blank") private String phone; @Valid @NotNull(message = "UserAddress must not be blank") private UserAddress useraddress; public UserAddress getUseraddress() { return useraddress; } public void setUseraddress(UserAddress useraddress) { this.useraddress = useraddress; } public UserAccount() { } public UserAccount(String email, String password, String name, int age) { this.password = password; this.name = name; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\spring\servicevalidation\domain\UserAccount.java
2
请在Spring Boot框架中完成以下Java代码
public String getLdif() { return this.ldif; } public void setLdif(String ldif) { this.ldif = ldif; } public Validation getValidation() { return this.validation; } public Ssl getSsl() { return this.ssl; } public static class Credential { /** * Embedded LDAP username. */ private @Nullable String username; /** * Embedded LDAP password. */ private @Nullable String password; public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } boolean isAvailable() { return StringUtils.hasText(this.username) && StringUtils.hasText(this.password); } } public static class Ssl { /** * Whether to enable SSL support. Enabled automatically if "bundle" is provided * unless specified otherwise. */ private @Nullable Boolean enabled; /** * SSL bundle name. */ private @Nullable String bundle; public boolean isEnabled() { return (this.enabled != null) ? this.enabled : this.bundle != null; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable String getBundle() { return this.bundle; }
public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-main\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
public void onNew(final ICalloutRecord calloutRecord) { final IBPartnerDAO bPartnerPA = Services.get(IBPartnerDAO.class); final I_C_BPartner_Location address = calloutRecord.getModel(I_C_BPartner_Location.class); if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsShipToDefault)) { address.setIsShipTo(true); address.setIsShipToDefault(true); } else { address.setIsShipTo(false); address.setIsShipToDefault(false); } if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsBillToDefault)) { address.setIsBillTo(true); address.setIsBillToDefault(true); } else { address.setIsBillTo(false); address.setIsBillToDefault(false); } if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsHandOverLocation))
{ address.setIsHandOverLocation(true); } else { address.setIsHandOverLocation(false); } // TODO: needs to be moved into de.metas.contracts project // if (!bPartnerPA.existsDefaultAddressInTable(address, null, I_C_BPartner_Location.COLUMNNAME_IsSubscriptionToDefault)) // { // address.setIsSubscriptionTo(true); // address.setIsSubscriptionToDefault(true); // } // else // { // address.setIsSubscriptionTo(false); // address.setIsSubscriptionToDefault(false); // } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\callout\C_BPartner_Location_Tab_Callout.java
1
请在Spring Boot框架中完成以下Java代码
public String getRate() { return rate; } public void setRate(final String rate) { this.rate = rate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (discount == null ? 0 : discount.hashCode()); result = prime * result + (discountDate == null ? 0 : discountDate.hashCode()); result = prime * result + (discountDays == null ? 0 : discountDays.hashCode()); result = prime * result + (rate == null ? 0 : rate.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop140V other = (Cctop140V)obj; if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (discount == null) { if (other.discount != null) { return false; } } else if (!discount.equals(other.discount)) { return false; }
if (discountDate == null) { if (other.discountDate != null) { return false; } } else if (!discountDate.equals(other.discountDate)) { return false; } if (discountDays == null) { if (other.discountDays != null) { return false; } } else if (!discountDays.equals(other.discountDays)) { return false; } if (rate == null) { if (other.rate != null) { return false; } } else if (!rate.equals(other.rate)) { return false; } return true; } @Override public String toString() { return "Cctop140V [cInvoiceID=" + cInvoiceID + ", discount=" + discount + ", discountDate=" + discountDate + ", discountDays=" + discountDays + ", rate=" + rate + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop140V.java
2
请完成以下Java代码
static boolean makeCoreDictionary(String inPath, String outPath) { final DictionaryMaker dictionaryMaker = new DictionaryMaker(); final TreeSet<String> labelSet = new TreeSet<String>(); CorpusLoader.walk(inPath, new CorpusLoader.Handler() { @Override public void handle(Document document) { for (List<Word> sentence : document.getSimpleSentenceList(true)) { for (Word word : sentence) { if (shouldInclude(word)) dictionaryMaker.add(word); } } // for (List<Word> sentence : document.getSimpleSentenceList(false)) // { // for (Word word : sentence) // { // if (shouldInclude(word)) // dictionaryMaker.add(word); // } // } } /** * 是否应当计算这个词语 * @param word * @return */ boolean shouldInclude(Word word)
{ if ("m".equals(word.label) || "mq".equals(word.label) || "w".equals(word.label) || "t".equals(word.label)) { if (!TextUtility.isAllChinese(word.value)) return false; } else if ("nr".equals(word.label)) { return false; } return true; } }); if (outPath != null) return dictionaryMaker.saveTxtTo(outPath); return false; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\NatureDictionaryMaker.java
1
请在Spring Boot框架中完成以下Java代码
public Result<SysDictItem> delete(@RequestParam(name="id",required=true) String id) { Result<SysDictItem> result = new Result<SysDictItem>(); SysDictItem joinSystem = sysDictItemService.getById(id); if(joinSystem==null) { result.error500("未找到对应实体"); }else { boolean ok = sysDictItemService.removeById(id); if(ok) { result.success("删除成功!"); } } return result; } /** * @功能:批量删除字典数据 * @param ids * @return */ @RequiresPermissions("system:dict:item:deleteBatch") @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE) @CacheEvict(value={CacheConstant.SYS_DICT_CACHE, CacheConstant.SYS_ENABLE_DICT_CACHE}, allEntries=true) public Result<SysDictItem> deleteBatch(@RequestParam(name="ids",required=true) String ids) { Result<SysDictItem> result = new Result<SysDictItem>(); if(ids==null || "".equals(ids.trim())) { result.error500("参数不识别!"); }else { this.sysDictItemService.removeByIds(Arrays.asList(ids.split(","))); result.success("删除成功!"); } return result; } /** * 字典值重复校验 * @param sysDictItem
* @param request * @return */ @RequestMapping(value = "/dictItemCheck", method = RequestMethod.GET) @Operation(summary="字典重复校验接口") public Result<Object> doDictItemCheck(SysDictItem sysDictItem, HttpServletRequest request) { Long num = Long.valueOf(0); LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<SysDictItem>(); queryWrapper.eq(SysDictItem::getItemValue,sysDictItem.getItemValue()); queryWrapper.eq(SysDictItem::getDictId,sysDictItem.getDictId()); if (StringUtils.isNotBlank(sysDictItem.getId())) { // 编辑页面校验 queryWrapper.ne(SysDictItem::getId,sysDictItem.getId()); } num = sysDictItemService.count(queryWrapper); if (num == 0) { // 该值可用 return Result.ok("该值可用!"); } else { // 该值不可用 log.info("该值不可用,系统中已存在!"); return Result.error("该值不可用,系统中已存在!"); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDictItemController.java
2
请完成以下Java代码
protected boolean isAutoStoreScriptVariablesEnabled() { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); if(processEngineConfiguration != null) { return processEngineConfiguration.isAutoStoreScriptVariables(); } return false; } public boolean containsKey(Object key) { for (Resolver scriptResolver: scriptResolvers) { if (scriptResolver.containsKey(key)) { return true; } } return wrappedBindings.containsKey(key); } public Object get(Object key) { Object result = null; if(wrappedBindings.containsKey(key)) { result = wrappedBindings.get(key); } else { for (Resolver scriptResolver: scriptResolvers) { if (scriptResolver.containsKey(key)) { result = scriptResolver.get(key); } } } return result; } public Object put(String name, Object value) { if(autoStoreScriptVariables) { if (!UNSTORED_KEYS.contains(name)) { Object oldValue = variableScope.getVariable(name); variableScope.setVariable(name, value); return oldValue; } } return wrappedBindings.put(name, value); } public Set<java.util.Map.Entry<String, Object>> entrySet() { return calculateBindingMap().entrySet(); } public Set<String> keySet() { return calculateBindingMap().keySet(); } public int size() { return calculateBindingMap().size();
} public Collection<Object> values() { return calculateBindingMap().values(); } public void putAll(Map< ? extends String, ? extends Object> toMerge) { for (java.util.Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) { put(entry.getKey(), entry.getValue()); } } public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return wrappedBindings.remove(key); } public void clear() { wrappedBindings.clear(); } public boolean containsValue(Object value) { return calculateBindingMap().containsValue(value); } public boolean isEmpty() { return calculateBindingMap().isEmpty(); } protected Map<String, Object> calculateBindingMap() { Map<String, Object> bindingMap = new HashMap<String, Object>(); for (Resolver resolver : scriptResolvers) { for (String key : resolver.keySet()) { bindingMap.put(key, resolver.get(key)); } } Set<java.util.Map.Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet(); for (Entry<String, Object> entry : wrappedBindingsEntries) { bindingMap.put(entry.getKey(), entry.getValue()); } return bindingMap; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\ScriptBindings.java
1
请完成以下Java代码
public int getSetupTime () { Integer ii = (Integer)get_Value(COLUMNNAME_SetupTime); if (ii == null) return 0; return ii.intValue(); } /** Set Units by Cycles. @param UnitsCycles The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit. */ @Override public void setUnitsCycles (java.math.BigDecimal UnitsCycles) { set_Value (COLUMNNAME_UnitsCycles, UnitsCycles); } /** Get Units by Cycles. @return The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit. */ @Override public java.math.BigDecimal getUnitsCycles () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitsCycles); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Waiting Time. @param WaitingTime Workflow Simulation Waiting time */ @Override public void setWaitingTime (int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, Integer.valueOf(WaitingTime)); } /** Get Waiting Time. @return Workflow Simulation Waiting time */ @Override public int getWaitingTime () { Integer ii = (Integer)get_Value(COLUMNNAME_WaitingTime); if (ii == null)
return 0; return ii.intValue(); } /** Set Working Time. @param WorkingTime Workflow Simulation Execution Time */ @Override public void setWorkingTime (int WorkingTime) { set_Value (COLUMNNAME_WorkingTime, Integer.valueOf(WorkingTime)); } /** Get Working Time. @return Workflow Simulation Execution Time */ @Override public int getWorkingTime () { Integer ii = (Integer)get_Value(COLUMNNAME_WorkingTime); if (ii == null) return 0; return ii.intValue(); } /** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield () { Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Workflow.java
1
请完成以下Java代码
public class PosKeyGenerate extends JavaProcess { private int posKeyLayoutId = 0; private int productCategoryId = 0; @Override protected void prepare() { for ( ProcessInfoParameter para : getParametersAsArray()) { if ( para.getParameterName().equals("C_POSKeyLayout_ID") ) posKeyLayoutId = para.getParameterAsInt(); if ( para.getParameterName().equals("M_Product_Category_ID") ) productCategoryId = para.getParameterAsInt(); else log.info("Parameter not found " + para.getParameterName()); } if ( posKeyLayoutId == 0 ) { posKeyLayoutId = getRecord_ID(); } } /** * Generate keys for each product */ @Override protected String doIt() throws Exception { if ( posKeyLayoutId == 0 ) throw new FillMandatoryException("C_POSKeyLayout_ID"); int count = 0; String where = ""; Object [] params = new Object[] {}; if ( productCategoryId > 0 ) { where = "M_Product_Category_ID = ? ";
params = new Object[] {productCategoryId}; } Query query = new Query(getCtx(), MProduct.Table_Name, where, get_TrxName()) .setParameters(params) .setOnlyActiveRecords(true) .setOrderBy("Value"); List<MProduct> products = query.list(MProduct.class); for (MProduct product : products ) { final I_C_POSKey key = InterfaceWrapperHelper.newInstance(I_C_POSKey.class, this); key.setName(product.getName()); key.setM_Product_ID(product.getM_Product_ID()); key.setC_POSKeyLayout_ID(posKeyLayoutId); key.setSeqNo(count*10); key.setQty(Env.ONE); InterfaceWrapperHelper.save(key); count++; } return "@Created@ " + count; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\PosKeyGenerate.java
1
请完成以下Java代码
public BigDecimal getQtyForecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyForecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyStock (final @Nullable BigDecimal QtyStock) { set_ValueNoCheck (COLUMNNAME_QtyStock, QtyStock); } @Override public BigDecimal getQtyStock() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyStock); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToMove (final @Nullable BigDecimal QtyToMove) { set_ValueNoCheck (COLUMNNAME_QtyToMove, QtyToMove);
} @Override public BigDecimal getQtyToMove() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToMove); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToProduce (final @Nullable BigDecimal QtyToProduce) { set_ValueNoCheck (COLUMNNAME_QtyToProduce, QtyToProduce); } @Override public BigDecimal getQtyToProduce() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProduce); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyUnconfirmedBySupplier (final @Nullable BigDecimal QtyUnconfirmedBySupplier) { set_ValueNoCheck (COLUMNNAME_QtyUnconfirmedBySupplier, QtyUnconfirmedBySupplier); } @Override public BigDecimal getQtyUnconfirmedBySupplier() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUnconfirmedBySupplier); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_QtyDemand_QtySupply_V.java
1
请完成以下Java代码
public static boolean isPlanItemAlreadyCompleted(CommandContext commandContext, PlanItemInstanceEntity planItemInstance) { List<PlanItemInstanceEntity> planItemInstances = CommandContextUtil.getPlanItemInstanceEntityManager(commandContext) .findByCaseInstanceIdAndPlanItemId(planItemInstance.getCaseInstanceId(), planItemInstance.getPlanItem().getId()); if (planItemInstances != null && planItemInstances.size() > 0) { for (PlanItemInstanceEntity item : planItemInstances) { if (Objects.equals(planItemInstance.getStageInstanceId(), item.getStageInstanceId()) && COMPLETED.equals(item.getState())) { return true; } } } return false; } /** * Checks the plan items parent completion mode to be equal to a given type and returns true if so. * * @param planItemInstance the plan item to check for a parent completion mode * @param parentCompletionRuleType the parent completion type to check against * @return true, if there is a parent completion mode set on the plan item equal to the given one
*/ public static boolean isParentCompletionRuleForPlanItemEqualToType(PlanItemInstanceEntity planItemInstance, String parentCompletionRuleType) { if (planItemInstance.getPlanItem() == null) { throw new FlowableException("Plan item could not be found for " + planItemInstance); } if (planItemInstance.getPlanItem().getItemControl() != null && planItemInstance.getPlanItem().getItemControl().getParentCompletionRule() != null) { ParentCompletionRule parentCompletionRule = planItemInstance.getPlanItem().getItemControl().getParentCompletionRule(); if (parentCompletionRuleType.equals(parentCompletionRule.getType())) { return true; } } return false; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\PlanItemInstanceContainerUtil.java
1