instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ConsumerApplication { public static void main(String[] args) { // 启动 Spring Boot 应用 ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args); } @Component public class UserRpcServiceTest implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) throws Exception { UserDTO user = userRpcService.get(1); logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user); } } @Component public class UserRpcServiceTest02 implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) throws Exception { // 获得用户 try { // 发起调用 UserDTO user = userRpcService.get(null); // 故意传入空的编号,为了校验编号不通过 logger.info("[run][发起一次 Dubbo RPC 请求,获得用户为({})]", user); } catch (Exception e) { logger.error("[run][获得用户发生异常,信息为:[{}]", e.getMessage()); } // 添加用户 try { // 创建 UserAddDTO UserAddDTO addDTO = new UserAddDTO(); addDTO.setName("yudaoyuanmayudaoyuanma"); // 故意把名字打的特别长,为了校验名字不通过 addDTO.setGender(null); // 不传递性别,为了校验性别不通过
// 发起调用 userRpcService.add(addDTO); logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO); } catch (Exception e) { logger.error("[run][添加用户发生异常,信息为:[{}]", e.getMessage()); } } } @Component public class UserRpcServiceTest03 implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Resource private UserRpcService userRpcService; @Override public void run(String... args) { // 添加用户 try { // 创建 UserAddDTO UserAddDTO addDTO = new UserAddDTO(); addDTO.setName("yudaoyuanma"); // 设置为 yudaoyuanma ,触发 ServiceException 异常 addDTO.setGender(1); // 发起调用 userRpcService.add(addDTO); logger.info("[run][发起一次 Dubbo RPC 请求,添加用户为({})]", addDTO); } catch (Exception e) { logger.error("[run][添加用户发生异常({}),信息为:[{}]", e.getClass().getSimpleName(), e.getMessage()); } } } }
repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-xml-demo\user-rpc-service-consumer\src\main\java\cn\iocoder\springboot\lab30\rpc\ConsumerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public class RateLimitInterceptor implements HandlerInterceptor { private static final String HEADER_API_KEY = "X-api-key"; private static final String HEADER_LIMIT_REMAINING = "X-Rate-Limit-Remaining"; private static final String HEADER_RETRY_AFTER = "X-Rate-Limit-Retry-After-Seconds"; @Autowired private PricingPlanService pricingPlanService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String apiKey = request.getHeader(HEADER_API_KEY); if (apiKey == null || apiKey.isEmpty()) { response.sendError(HttpStatus.BAD_REQUEST.value(), "Missing Header: " + HEADER_API_KEY); return false; } Bucket tokenBucket = pricingPlanService.resolveBucket(apiKey);
ConsumptionProbe probe = tokenBucket.tryConsumeAndReturnRemaining(1); if (probe.isConsumed()) { response.addHeader(HEADER_LIMIT_REMAINING, String.valueOf(probe.getRemainingTokens())); return true; } else { long waitForRefill = probe.getNanosToWaitForRefill() / 1_000_000_000; response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.addHeader(HEADER_RETRY_AFTER, String.valueOf(waitForRefill)); response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(), "You have exhausted your API Request Quota"); // 429 return false; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\ratelimiting\bucket4japp\interceptor\RateLimitInterceptor.java
2
请完成以下Java代码
public BpmnEdge newInstance(ModelTypeInstanceContext instanceContext) { return new BpmnEdgeImpl(instanceContext); } }); bpmnElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_BPMN_ELEMENT) .qNameAttributeReference(BaseElement.class) .build(); sourceElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_SOURCE_ELEMENT) .qNameAttributeReference(DiagramElement.class) .build(); targetElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_TARGET_ELEMENT) .qNameAttributeReference(DiagramElement.class) .build(); messageVisibleKindAttribute = typeBuilder.enumAttribute(BPMNDI_ATTRIBUTE_MESSAGE_VISIBLE_KIND, MessageVisibleKind.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); bpmnLabelChild = sequenceBuilder.element(BpmnLabel.class) .build(); typeBuilder.build(); } public BpmnEdgeImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public BaseElement getBpmnElement() { return bpmnElementAttribute.getReferenceTargetElement(this); } public void setBpmnElement(BaseElement bpmnElement) { bpmnElementAttribute.setReferenceTargetElement(this, bpmnElement); } public DiagramElement getSourceElement() {
return sourceElementAttribute.getReferenceTargetElement(this); } public void setSourceElement(DiagramElement sourceElement) { sourceElementAttribute.setReferenceTargetElement(this, sourceElement); } public DiagramElement getTargetElement() { return targetElementAttribute.getReferenceTargetElement(this); } public void setTargetElement(DiagramElement targetElement) { targetElementAttribute.setReferenceTargetElement(this, targetElement); } public MessageVisibleKind getMessageVisibleKind() { return messageVisibleKindAttribute.getValue(this); } public void setMessageVisibleKind(MessageVisibleKind messageVisibleKind) { messageVisibleKindAttribute.setValue(this, messageVisibleKind); } public BpmnLabel getBpmnLabel() { return bpmnLabelChild.getChild(this); } public void setBpmnLabel(BpmnLabel bpmnLabel) { bpmnLabelChild.setChild(this, bpmnLabel); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnEdgeImpl.java
1
请完成以下Java代码
class ActiveMQClassicDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<ActiveMQConnectionDetails> { private static final int ACTIVEMQ_PORT = 61616; protected ActiveMQClassicDockerComposeConnectionDetailsFactory() { super("apache/activemq-classic"); } @Override protected ActiveMQConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new ActiveMQDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link ActiveMQConnectionDetails} backed by an {@code activemq} * {@link RunningService}. */ static class ActiveMQDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements ActiveMQConnectionDetails { private final ActiveMQClassicEnvironment environment; private final String brokerUrl; protected ActiveMQDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new ActiveMQClassicEnvironment(service.env()); this.brokerUrl = "tcp://" + service.host() + ":" + service.ports().get(ACTIVEMQ_PORT);
} @Override public String getBrokerUrl() { return this.brokerUrl; } @Override public @Nullable String getUser() { return this.environment.getUser(); } @Override public @Nullable String getPassword() { return this.environment.getPassword(); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\docker\compose\ActiveMQClassicDockerComposeConnectionDetailsFactory.java
1
请在Spring Boot框架中完成以下Java代码
public UserDetailsService userDetailsServiceApp2() { UserDetails user = User.withUsername("user") .password(encoder().encode("user")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public SecurityFilterChain filterChainApp2(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); http.securityMatcher("/user*") .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(mvcMatcherBuilder.pattern("/user*")).hasRole("USER")) // log in .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/loginUser")
.loginProcessingUrl("/user_login") .failureUrl("/loginUser?error=loginError") .defaultSuccessUrl("/userPage")) // logout .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/user_logout") .logoutSuccessUrl("/protectedLinks") .deleteCookies("JSESSIONID")) .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedPage("/403")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\multiplelogin\MultipleLoginSecurityConfig.java
2
请完成以下Java代码
private static AttributesIncludedTabFieldDescriptor toAttributesIncludedTabField( @NonNull final AttributeId attributeId, @NonNull final ImmutableMap<AttributeId, I_M_Attribute> attributesById) { final I_M_Attribute attribute = attributesById.get(attributeId); if (attribute == null) { throw new AdempiereException("No Attribute with ID " + attributeId + " found"); } final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(attribute); return AttributesIncludedTabFieldDescriptor.builder() .caption(trls.getColumnTrl(I_M_Attribute.COLUMNNAME_Name, attribute.getName())) .description(trls.getColumnTrl(I_M_Attribute.COLUMNNAME_Description, attribute.getDescription())) .attributeId(attributeId) .attributeCode(AttributeCode.ofString(attribute.getValue())) .attributeValueType(AttributeValueType.ofCode(attribute.getAttributeValueType())) .readOnlyValues(attribute.isReadOnlyValues()) .mandatory(attribute.isMandatory()) .uomId(UomId.ofRepoIdOrNull(attribute.getC_UOM_ID())) .build(); } @Nullable public IAttributeValuesProvider createAttributeValuesProvider(final AttributeId attributeId) { return attributesBL.createAttributeValuesProvider(attributeId); } // // // //
// private static class AttributesIncludedTabMap { private static final AttributesIncludedTabMap EMPTY = new AttributesIncludedTabMap(ImmutableList.of()); private final ImmutableListMultimap<AdTableId, AttributesIncludedTabDescriptor> byTableId; private AttributesIncludedTabMap(final List<AttributesIncludedTabDescriptor> list) { this.byTableId = list.stream() .sorted(Comparator.comparing(AttributesIncludedTabDescriptor::getParentTableId) .thenComparing(AttributesIncludedTabDescriptor::getSeqNo)) .collect(ImmutableListMultimap.toImmutableListMultimap(AttributesIncludedTabDescriptor::getParentTableId, tab -> tab)); } public static AttributesIncludedTabMap of(final List<AttributesIncludedTabDescriptor> list) { return list.isEmpty() ? EMPTY : new AttributesIncludedTabMap(list); } public List<AttributesIncludedTabDescriptor> listBy(final @NonNull AdTableId adTableId) { return byTableId.get(adTableId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\descriptor\AttributesIncludedTabDescriptorService.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedArticleLineDuration orderedArticleLineDuration = (OrderedArticleLineDuration) o; return Objects.equals(this.amount, orderedArticleLineDuration.amount) && Objects.equals(this.timePeriod, orderedArticleLineDuration.timePeriod); } @Override public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderedArticleLineDuration {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).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\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLineDuration.java
2
请在Spring Boot框架中完成以下Java代码
public class XmlBalance { /** expecting default = CHF */ @NonNull String currency; @NonNull BigDecimal amount; /** expecting default = 0 */ @NonNull BigDecimal amountReminder; /** expecting default = 0 */ @Nullable BigDecimal amountPrepaid; @NonNull BigDecimal amountDue; /** expecting default = 0 */ @NonNull BigDecimal amountObligations; @NonNull XmlVat vat; public XmlBalance withMod(@Nullable final BalanceMod balanceMod) { if (balanceMod == null) { return this; } final XmlBalanceBuilder builder = toBuilder(); if (balanceMod.getCurrency() != null) { builder.currency(balanceMod.getCurrency()); }
if (balanceMod.getAmount() != null) { builder.amount(balanceMod.getAmount()); } if (balanceMod.getAmountDue() != null) { builder.amountDue(balanceMod.getAmountDue()); } return builder .vat(vat.withMod(balanceMod.getVatMod())) .build(); } @Value @Builder public static class BalanceMod { @Nullable String currency; @Nullable BigDecimal amount; @Nullable BigDecimal amountDue; @Nullable VatMod vatMod; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\XmlBalance.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getDepartName() { return departName; } public void setDepartName(String departName) { this.departName = departName; } public String getDepartNameEn() { return departNameEn; } public void setDepartNameEn(String departNameEn) { this.departNameEn = departNameEn; } public String getDepartNameAbbr() { return departNameAbbr; } public void setDepartNameAbbr(String departNameAbbr) { this.departNameAbbr = departNameAbbr; } public Integer getDepartOrder() { return departOrder; } public void setDepartOrder(Integer departOrder) { this.departOrder = departOrder; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOrgCategory() {
return orgCategory; } public void setOrgCategory(String orgCategory) { this.orgCategory = orgCategory; } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType; } public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java
1
请完成以下Java代码
public String getState() { return null; } @Override public Date getInProgressStartTime() { return null; } @Override public String getInProgressStartedBy() { return null; } @Override public Date getClaimTime() { return null; } @Override public String getClaimedBy() { return null; } @Override public Date getSuspendedTime() {
return null; } @Override public String getSuspendedBy() { return null; } @Override public Date getInProgressStartDueDate() { return null; } @Override public void setInProgressStartDueDate(Date inProgressStartDueDate) { // nothing } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntity.java
1
请完成以下Java代码
public void setQtyUsageVariance (final BigDecimal QtyUsageVariance) { set_Value (COLUMNNAME_QtyUsageVariance, QtyUsageVariance); } @Override public BigDecimal getQtyUsageVariance() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUsageVariance); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScrap (final @Nullable BigDecimal Scrap) { set_ValueNoCheck (COLUMNNAME_Scrap, Scrap); } @Override public BigDecimal getScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setShowSubBOMIngredients (final boolean ShowSubBOMIngredients) { set_Value (COLUMNNAME_ShowSubBOMIngredients, ShowSubBOMIngredients); } @Override public boolean isShowSubBOMIngredients() { return get_ValueAsBoolean(COLUMNNAME_ShowSubBOMIngredients); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() {
return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } /** * VariantGroup AD_Reference_ID=540490 * Reference name: VariantGroup */ public static final int VARIANTGROUP_AD_Reference_ID=540490; /** 01 = 01 */ public static final String VARIANTGROUP_01 = "01"; /** 02 = 02 */ public static final String VARIANTGROUP_02 = "02"; /** 03 = 03 */ public static final String VARIANTGROUP_03 = "03"; /** 04 = 04 */ public static final String VARIANTGROUP_04 = "04"; /** 05 = 05 */ public static final String VARIANTGROUP_05 = "05"; /** 06 = 06 */ public static final String VARIANTGROUP_06 = "06"; /** 07 = 07 */ public static final String VARIANTGROUP_07 = "07"; /** 08 = 08 */ public static final String VARIANTGROUP_08 = "08"; /** 09 = 09 */ public static final String VARIANTGROUP_09 = "09"; @Override public void setVariantGroup (final @Nullable java.lang.String VariantGroup) { set_Value (COLUMNNAME_VariantGroup, VariantGroup); } @Override public java.lang.String getVariantGroup() { return get_ValueAsString(COLUMNNAME_VariantGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOMLine.java
1
请完成以下Java代码
protected String getShortClassName(final Class<?> cls) { if (cls != null && cls.isArray() && getDepth() > 0) { return ""; } return super.getShortClassName(cls); } static class MutableInteger { private int value; MutableInteger(final int value) { this.value = value; }
public final int get() { return value; } public final void increment() { ++value; } public final void decrement() { --value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\RecursiveIndentedMultilineToStringStyle.java
1
请完成以下Java代码
public FetchAndLockBuilderImpl asc() throws NotValidException { configureLastOrderingPropertyDirection(ASCENDING); return this; } public FetchAndLockBuilderImpl desc() throws NotValidException { configureLastOrderingPropertyDirection(DESCENDING); return this; } @Override public ExternalTaskQueryTopicBuilder subscribe() { checkQueryOk(); return new ExternalTaskQueryTopicBuilderImpl(commandExecutor, workerId, maxTasks, usePriority, orderingProperties); } protected void configureLastOrderingPropertyDirection(Direction direction) { QueryOrderingProperty lastProperty = !orderingProperties.isEmpty() ? getLastElement(orderingProperties) : null;
ensureNotNull(NotValidException.class, "You should call any of the orderBy methods first before specifying a direction", "currentOrderingProperty", lastProperty); if (lastProperty.getDirection() != null) { ensureNull(NotValidException.class, "Invalid query: can specify only one direction desc() or asc() for an ordering constraint", "direction", direction); } lastProperty.setDirection(direction); } protected void checkQueryOk() { for (QueryOrderingProperty orderingProperty : orderingProperties) { ensureNotNull(NotValidException.class, "Invalid query: call asc() or desc() after using orderByXX()", "direction", orderingProperty.getDirection()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\FetchAndLockBuilderImpl.java
1
请完成以下Java代码
protected List<DelegateListener<? extends BaseDelegateExecution>> getListeners(CoreModelElement scope, T execution) { if(execution.isSkipCustomListeners()) { return getBuiltinListeners(scope); } else { return scope.getListeners(getEventName()); } } protected List<DelegateListener<? extends BaseDelegateExecution>> getBuiltinListeners(CoreModelElement scope) { return scope.getBuiltInListeners(getEventName()); } protected boolean isSkipNotifyListeners(T execution) { return false; } protected T eventNotificationsStarted(T execution) { // do nothing
return execution; } protected abstract CoreModelElement getScope(T execution); protected abstract String getEventName(); protected abstract void eventNotificationsCompleted(T execution); protected void eventNotificationsFailed(T execution, Exception exception) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new PvmException("couldn't execute event listener : " + exception.getMessage(), exception); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\operation\AbstractEventAtomicOperation.java
1
请完成以下Java代码
public class DevToolsSettings { /** * The location to look for settings properties. Can be present in multiple JAR files. */ public static final String SETTINGS_RESOURCE_LOCATION = "META-INF/spring-devtools.properties"; private static final Log logger = DevToolsLogFactory.getLog(DevToolsSettings.class); private static @Nullable DevToolsSettings settings; private final List<Pattern> restartIncludePatterns = new ArrayList<>(); private final List<Pattern> restartExcludePatterns = new ArrayList<>(); private final Map<String, Object> propertyDefaults = new HashMap<>(); DevToolsSettings() { } private void add(Map<?, ?> properties) { Map<String, Pattern> includes = getPatterns(properties, "restart.include."); this.restartIncludePatterns.addAll(includes.values()); Map<String, Pattern> excludes = getPatterns(properties, "restart.exclude."); this.restartExcludePatterns.addAll(excludes.values()); properties.forEach((key, value) -> { String name = String.valueOf(key); if (name.startsWith("defaults.")) { name = name.substring("defaults.".length()); this.propertyDefaults.put(name, value); } }); } private Map<String, Pattern> getPatterns(Map<?, ?> properties, String prefix) { Map<String, Pattern> patterns = new LinkedHashMap<>(); properties.forEach((key, value) -> { String name = String.valueOf(key); if (name.startsWith(prefix)) { Pattern pattern = Pattern.compile((String) value); patterns.put(name, pattern); } }); return patterns; } public boolean isRestartInclude(URL url) { return isMatch(url.toString(), this.restartIncludePatterns); } public boolean isRestartExclude(URL url) { return isMatch(url.toString(), this.restartExcludePatterns); }
public Map<String, Object> getPropertyDefaults() { return Collections.unmodifiableMap(this.propertyDefaults); } private boolean isMatch(String url, List<Pattern> patterns) { for (Pattern pattern : patterns) { if (pattern.matcher(url).find()) { return true; } } return false; } public static DevToolsSettings get() { if (settings == null) { settings = load(); } return settings; } static DevToolsSettings load() { return load(SETTINGS_RESOURCE_LOCATION); } static DevToolsSettings load(String location) { try { DevToolsSettings settings = new DevToolsSettings(); Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(location); while (urls.hasMoreElements()) { settings.add(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement()))); } if (logger.isDebugEnabled()) { logger.debug("Included patterns for restart : " + settings.restartIncludePatterns); logger.debug("Excluded patterns for restart : " + settings.restartExcludePatterns); } return settings; } catch (Exception ex) { throw new IllegalStateException("Unable to load devtools settings from location [" + location + "]", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\settings\DevToolsSettings.java
1
请完成以下Java代码
public void actionPerformed(final ActionEvent e) { letterHtml = ""; letterPdfFile = null; updateComponentsStatus(); } }; public VLetterAttachment(final Dialog parentDialog) { super(); this.parentDialog = parentDialog; init(); } private void init() { fPreview.setText(""); fPreview.setPreferredSize(new Dimension (500,80)); // else the component will be displayed too small if empty (when using FlowLayout) bEdit.setIcon(Images.getImageIcon2("Open16")); bEdit.setText(""); bEdit.addActionListener(editAction); bCancel.setIcon(Images.getImageIcon2("Cancel16")); bCancel.setText(""); bCancel.addActionListener(cancelAction); // setLayout(new FlowLayout(FlowLayout.LEFT)); this.add(fPreview);
this.add(bEdit); this.add(bCancel); } private void updateComponentsStatus() { fPreview.setText(letterHtml == null ? "" : letterHtml); bCancel.setEnabled(!Check.isEmpty(letterHtml, false)); } public void setVariables(final BoilerPlateContext variables) { this.variables = variables; } public String getLetterHtml() { return letterHtml; } public File getPDF() { return letterPdfFile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VLetterAttachment.java
1
请完成以下Java代码
public void updatePaymentImportTable(@NonNull final ImportRecordsSelection selection) { dbUpdateBPartners(selection); dbUpdateInvoices(selection); dbUpdateIsReceipt(selection); dbUpdateErrorMessages(selection); } private void dbUpdateBPartners(@NonNull final ImportRecordsSelection selection) { StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ") .append("SET C_BPartner_ID=(SELECT MAX(C_BPartner_ID) FROM C_BPartner bp ") .append(" WHERE (i.BPartnerValue=bp.Debtorid OR i.BPartnerValue=bp.CreditorId) AND i.AD_Client_ID=bp.AD_Client_ID AND i.AD_Org_ID=bp.AD_Org_ID ) ") .append("WHERE C_BPartner_ID IS NULL AND BPartnerValue IS NOT NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause("i")); DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); } private void dbUpdateInvoices(@NonNull final ImportRecordsSelection selection) { StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ") .append("SET C_Invoice_ID = (SELECT C_Invoice_ID FROM C_Invoice inv ") .append("WHERE i.InvoiceDocumentNo = inv.DocumentNo ") .append("AND round((i.PayAmt+i.DiscountAmt),2) = round(inv.GrandTotal,2) AND i.DateTrx = inv.DateInvoiced ") .append("AND i.AD_Client_ID=inv.AD_Client_ID AND i.AD_Org_ID=inv.AD_Org_ID ) ") .append("WHERE C_Invoice_ID IS NULL AND InvoiceDocumentNo IS NOT NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause("i")); DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); } private void dbUpdateIsReceipt(@NonNull final ImportRecordsSelection selection) { StringBuilder sql = new StringBuilder("UPDATE I_Datev_Payment i ") .append("SET IsReceipt = (CASE WHEN TransactionCode='H' THEN 'N' ELSE 'Y' END) ") .append("WHERE I_IsImported<>'Y' ") .append(selection.toSqlWhereClause("i")); DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); } private void dbUpdateErrorMessages(@NonNull final ImportRecordsSelection selection)
{ StringBuilder sql; int no; sql = new StringBuilder("UPDATE I_Datev_Payment ") .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No BPartner, ' ") .append("WHERE C_BPartner_ID IS NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No BPartner = {}", no); } sql = new StringBuilder("UPDATE I_Datev_Payment ") .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Invoice, ' ") .append("WHERE C_Invoice_ID IS NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause("i")); no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No Invoice = {}", no); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impexp\CPaymentImportTableSqlUpdater.java
1
请完成以下Java代码
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() {
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age); } @Override public int hashCode() { return Objects.hash(firstName, lastName, age); } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\geode\Customer.java
1
请完成以下Java代码
public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public String updateProcessBusinessKey(String bzKey) { if (isProcessInstanceType() && bzKey != null) { setBusinessKey(bzKey); Context.getCommandContext().getHistoryManager().updateProcessBusinessKeyInHistory(this); if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } return bzKey; } return null; } public void deleteIdentityLink(String userId, String groupId, String type) { List<IdentityLinkEntity> identityLinks = Context.getCommandContext().getIdentityLinkEntityManager() .findIdentityLinkByProcessInstanceUserGroupAndType(id, userId, groupId, type); for (IdentityLinkEntity identityLink : identityLinks) { Context.getCommandContext().getIdentityLinkEntityManager().deleteIdentityLink(identityLink, true); }
getIdentityLinks().removeAll(identityLinks); } // NOT IN V5 @Override public boolean isMultiInstanceRoot() { return false; } @Override public void setMultiInstanceRoot(boolean isMultiInstanceRoot) { } @Override public String getPropagatedStageInstanceId() { return null; } protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity, ProcessEngineConfigurationImpl processEngineConfiguration) { JobProcessorContextImpl jobProcessorContext = new JobProcessorContextImpl(processorType, abstractJobEntity); for (JobProcessor jobProcessor : processEngineConfiguration.getJobProcessors()) { jobProcessor.process(jobProcessorContext); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntity.java
1
请完成以下Java代码
public void setQtyDelivered_LU (java.math.BigDecimal QtyDelivered_LU) { set_Value (COLUMNNAME_QtyDelivered_LU, QtyDelivered_LU); } /** Get Gelieferte Menge (LU). @return Gelieferte Menge (LU) */ @Override public java.math.BigDecimal getQtyDelivered_LU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered_LU); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Gelieferte Menge (TU). @param QtyDelivered_TU Gelieferte Menge (TU) */ @Override public void setQtyDelivered_TU (java.math.BigDecimal QtyDelivered_TU) { set_Value (COLUMNNAME_QtyDelivered_TU, QtyDelivered_TU); } /** Get Gelieferte Menge (TU). @return Gelieferte Menge (TU) */ @Override public java.math.BigDecimal getQtyDelivered_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered_TU); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Bestellte Menge (LU). @param QtyOrdered_LU Bestellte Menge (LU) */ @Override public void setQtyOrdered_LU (java.math.BigDecimal QtyOrdered_LU) { set_Value (COLUMNNAME_QtyOrdered_LU, QtyOrdered_LU); } /** Get Bestellte Menge (LU). @return Bestellte Menge (LU) */ @Override public java.math.BigDecimal getQtyOrdered_LU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_LU); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Bestellte Menge (TU). @param QtyOrdered_TU Bestellte Menge (TU) */ @Override public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU) { set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU); } /** Get Bestellte Menge (TU). @return Bestellte Menge (TU) */ @Override public java.math.BigDecimal getQtyOrdered_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU); if (bd == null) return BigDecimal.ZERO;
return bd; } /** Set Ausliefermenge (LU). @param QtyToDeliver_LU Ausliefermenge (LU) */ @Override public void setQtyToDeliver_LU (java.math.BigDecimal QtyToDeliver_LU) { set_Value (COLUMNNAME_QtyToDeliver_LU, QtyToDeliver_LU); } /** Get Ausliefermenge (LU). @return Ausliefermenge (LU) */ @Override public java.math.BigDecimal getQtyToDeliver_LU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_LU); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ausliefermenge (TU). @param QtyToDeliver_TU Ausliefermenge (TU) */ @Override public void setQtyToDeliver_TU (java.math.BigDecimal QtyToDeliver_TU) { set_Value (COLUMNNAME_QtyToDeliver_TU, QtyToDeliver_TU); } /** Get Ausliefermenge (TU). @return Ausliefermenge (TU) */ @Override public java.math.BigDecimal getQtyToDeliver_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_TU); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_Tour_Instance.java
1
请在Spring Boot框架中完成以下Java代码
public static String validateString(final String field, final String errorMsg) { if (isEmpty(field)) { throw new RuntimeCamelException(errorMsg); } return field; } /** * Validate {@link Number}, and throw {@link RuntimeCamelException} if the field is null or 0. * * @param field * @param errorMsg */ public static Number validateNumber(final Number field, final String errorMsg)
{ if (field == null || field.intValue() == 0) { throw new RuntimeCamelException(errorMsg); } return field; } public static List<?> validateList(final List<?> field, final String errorMsg) { if (field == null || field.isEmpty()) { throw new RuntimeCamelException(errorMsg); } return field; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\ValidationHelper.java
2
请在Spring Boot框架中完成以下Java代码
static DelegatingMethodSecurityMetadataSource methodMetadataSource( MethodSecurityExpressionHandler methodSecurityExpressionHandler) { ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory( methodSecurityExpressionHandler); PrePostAnnotationSecurityMetadataSource prePostSource = new PrePostAnnotationSecurityMetadataSource( attributeFactory); return new DelegatingMethodSecurityMetadataSource(Arrays.asList(prePostSource)); } @Bean static PrePostAdviceReactiveMethodInterceptor securityMethodInterceptor(AbstractMethodSecurityMetadataSource source, MethodSecurityExpressionHandler handler) { ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice(handler); ExpressionBasedPreInvocationAdvice preAdvice = new ExpressionBasedPreInvocationAdvice(); preAdvice.setExpressionHandler(handler); return new PrePostAdviceReactiveMethodInterceptor(source, preAdvice, postAdvice); } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Fallback static DefaultMethodSecurityExpressionHandler methodSecurityExpressionHandler( ReactiveMethodSecurityConfiguration configuration) { DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); if (configuration.grantedAuthorityDefaults != null) {
handler.setDefaultRolePrefix(configuration.grantedAuthorityDefaults.getRolePrefix()); } return handler; } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.advisorOrder = (int) importMetadata.getAnnotationAttributes(EnableReactiveMethodSecurity.class.getName()) .get("order"); } @Autowired(required = false) void setGrantedAuthorityDefaults(GrantedAuthorityDefaults grantedAuthorityDefaults) { this.grantedAuthorityDefaults = grantedAuthorityDefaults; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecurityConfiguration.java
2
请完成以下Java代码
private @NonNull SumUpTransactionExternalId findTransactionToRefundByPOSRef(final @NonNull SumUpPOSRef posRef) { if (posRef.getPosPaymentId() <= 0) { throw new AdempiereException("posPaymentId not provided"); } final List<SumUpTransaction> trxs = trxRepository.stream(SumUpTransactionQuery.builder() .status(SumUpTransactionStatus.SUCCESSFUL) .posRef(posRef) .build()) .filter(trx -> !trx.isRefunded()) .collect(Collectors.toList()); if (trxs.isEmpty()) { throw new AdempiereException("No successful transactions found"); } else if (trxs.size() != 1) { throw new AdempiereException("More than successful transaction found");
} else { return trxs.get(0).getExternalId(); } } public SumUpTransaction refundTransaction(@NonNull final SumUpTransactionExternalId id) { return trxRepository.updateById(id, trx -> { final SumUpConfig config = configRepository.getById(trx.getConfigId()); final SumUpClient client = clientFactory.newClient(config); client.setPosRef(trx.getPosRef()); client.refundTransaction(trx.getExternalId()); final JsonGetTransactionResponse remoteTrx = client.getTransactionById(trx.getExternalId()); return updateTransactionFromRemote(trx, remoteTrx); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpService.java
1
请完成以下Java代码
public VariableInstanceQuery excludeVariableInitialization() { wrappedVariableInstanceQuery.excludeVariableInitialization(); return this; } @Override public VariableInstanceQuery variableValueEquals(String variableName, Object variableValue) { wrappedVariableInstanceQuery.variableValueEquals(variableName, variableValue); return this; } @Override public VariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) { wrappedVariableInstanceQuery.variableValueNotEquals(variableName, variableValue); return this; } @Override public VariableInstanceQuery variableValueLike(String variableName, String variableValue) { wrappedVariableInstanceQuery.variableValueLike(variableName, variableValue); return this; } @Override public VariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) { wrappedVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue); return this; } @Override public VariableInstanceQuery orderByVariableName() { wrappedVariableInstanceQuery.orderByVariableName(); return this; } @Override public VariableInstanceQuery asc() { wrappedVariableInstanceQuery.asc(); return this; } @Override public VariableInstanceQuery desc() { wrappedVariableInstanceQuery.desc(); return this; } @Override public VariableInstanceQuery orderBy(QueryProperty property) { wrappedVariableInstanceQuery.orderBy(property); return this; } @Override public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this; } @Override public long count() { return wrappedVariableInstanceQuery.count(); } @Override public VariableInstance singleResult() { return wrappedVariableInstanceQuery.singleResult(); } @Override public List<VariableInstance> list() { return wrappedVariableInstanceQuery.list(); } @Override public List<VariableInstance> listPage(int firstResult, int maxResults) { return wrappedVariableInstanceQuery.listPage(firstResult, maxResults); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java
1
请完成以下Java代码
public void onChatEvent(SocketIOClient client, AckRequest request, SingleMessageRequest data) { Optional<UUID> toUser = dbTemplate.findByUserId(data.getToUid()); if (toUser.isPresent()) { log.info("用户 {} 刚刚私信了用户 {}:{}", data.getFromUid(), data.getToUid(), data.getMessage()); sendToSingle(toUser.get(), data); request.sendAckData(Dict.create().set("flag", true).set("message", "发送成功")); } else { request.sendAckData(Dict.create().set("flag", false).set("message", "发送失败,对方不想理你(" + data.getToUid() + "不在线)")); } } @OnEvent(value = Event.GROUP) public void onGroupEvent(SocketIOClient client, AckRequest request, GroupMessageRequest data) { Collection<SocketIOClient> clients = server.getRoomOperations(data.getGroupId()).getClients(); boolean inGroup = false; for (SocketIOClient socketIOClient : clients) { if (ObjectUtil.equal(socketIOClient.getSessionId(), client.getSessionId())) { inGroup = true; break; } } if (inGroup) { log.info("群号 {} 收到来自 {} 的群聊消息:{}", data.getGroupId(), data.getFromUid(), data.getMessage()); sendToGroup(data); } else { request.sendAckData("请先加群!"); } } /** * 单聊 */
public void sendToSingle(UUID sessionId, SingleMessageRequest message) { server.getClient(sessionId).sendEvent(Event.CHAT, message); } /** * 广播 */ public void sendToBroadcast(BroadcastMessageRequest message) { log.info("系统紧急广播一条通知:{}", message.getMessage()); for (UUID clientId : dbTemplate.findAll()) { if (server.getClient(clientId) == null) { continue; } server.getClient(clientId).sendEvent(Event.BROADCAST, message); } } /** * 群聊 */ public void sendToGroup(GroupMessageRequest message) { server.getRoomOperations(message.getGroupId()).sendEvent(Event.GROUP, message); } }
repos\spring-boot-demo-master\demo-websocket-socketio\src\main\java\com\xkcoding\websocket\socketio\handler\MessageEventHandler.java
1
请完成以下Java代码
protected void runPreExportHook(final TableRecordReference recordReferenceToExport) { } private void exportIfAlreadyExportedOnce(@NonNull final I_M_HU_Trace huTrace) { final ExportHUCandidate exportHUCandidate = ExportHUCandidate.builder() .huId(HuId.ofRepoId(huTrace.getM_HU_ID())) .linkedSourceVHuId(HuId.ofRepoIdOrNull(huTrace.getVHU_Source_ID())) .build(); enqueueHUExport(exportHUCandidate); } private void directlyExportToAllMatchingConfigs(@NonNull final I_M_HU_Trace huTrace) { final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum); for (final ExternalSystemParentConfig config : configs) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig()); if (!shouldExportToExternalSystem(grsConfig, HUTraceType.ofCode(huTrace.getHUTraceType()))) { continue; } final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParent(HuId.ofRepoId(huTrace.getM_HU_ID())); final TableRecordReference topLevelHURecordRef = TableRecordReference.of(topLevelHU); exportToExternalSystem(grsConfig.getId(), topLevelHURecordRef, null); } }
private boolean shouldExportDirectly(@NonNull final I_M_HU_Trace huTrace) { final HUTraceType huTraceType = HUTraceType.ofCode(huTrace.getHUTraceType()); final boolean purchasedOrProduced = huTraceType.equals(MATERIAL_RECEIPT) || huTraceType.equals(PRODUCTION_RECEIPT); final boolean docCompleted = DocStatus.ofCodeOptional(huTrace.getDocStatus()) .map(DocStatus::isCompleted) .orElse(false); return purchasedOrProduced && docCompleted; } private boolean shouldExportIfAlreadyExportedOnce(@NonNull final HUTraceType huTraceType) { return huTraceType.equals(TRANSFORM_LOAD) || huTraceType.equals(TRANSFORM_PARENT); } private boolean shouldExportToExternalSystem(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig, @NonNull final HUTraceType huTraceType) { switch (huTraceType) { case MATERIAL_RECEIPT: return grsSignumConfig.isSyncHUsOnMaterialReceipt(); case PRODUCTION_RECEIPT: return grsSignumConfig.isSyncHUsOnProductionReceipt(); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportHUToGRSService.java
1
请在Spring Boot框架中完成以下Java代码
public String getRequest() { return request; } /** 请求信息 **/ public void setRequest(String request) { this.request = request == null ? null : request.trim(); } /** 返回信息 **/ public String getResponse() { return response; } /** 返回信息 **/ public void setResponse(String response) { this.response = response == null ? null : response.trim(); } /** 商户编号 **/ public String getMerchantNo() { return merchantNo; } /** 商户编号 **/ public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo == null ? null : merchantNo.trim(); } /** 商户订单号 **/
public String getMerchantOrderNo() { return merchantOrderNo; } /** 商户订单号 **/ public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim(); } /** HTTP状态 **/ public Integer getHttpStatus() { return httpStatus; } /** HTTP状态 **/ public void setHttpStatus(Integer httpStatus) { this.httpStatus = httpStatus; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpNotifyRecordLog.java
2
请完成以下Java代码
public PO getPO(final int Record_ID, final String trxName) { final Properties ctx = getCtx(); final String tableName = getTableName(); return TableModelLoader.instance.getPO(ctx, tableName, Record_ID, trxName); } /** * * @return tableName's model class * @deprecated Please use {@link TableModelClassLoader#getClass(String)}. */ @Deprecated public static Class<?> getClass(String tableName) { return TableModelClassLoader.instance.getClass(tableName); } /** * Before Save * * @param newRecord new * @return true */ @Override protected boolean beforeSave(boolean newRecord) { if (isView() && isDeleteable()) { setIsDeleteable(false); } // return true; } // beforeSave /** * After Save * * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave(boolean newRecord, boolean success) { // // Create/Update table sequences // NOTE: we shall do this only if it's a new table, else we will change the sequence's next value
// which could be OK on our local development database, // but when the migration script will be executed on target customer database, their sequences will be wrongly changed (08607) if (success && newRecord) { final ISequenceDAO sequenceDAO = Services.get(ISequenceDAO.class); sequenceDAO.createTableSequenceChecker(getCtx()) .setFailOnFirstError(true) .setSequenceRangeCheck(false) .setTable(this) .setTrxName(get_TrxName()) .run(); } if (!newRecord && is_ValueChanged(COLUMNNAME_TableName)) { final IADTableDAO adTableDAO = Services.get(IADTableDAO.class); adTableDAO.onTableNameRename(this); } return success; } // afterSave public Query createQuery(String whereClause, String trxName) { return new Query(this.getCtx(), this, whereClause, trxName); } @Override public String toString() { return "MTable[" + get_ID() + "-" + getTableName() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTable.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonWorkflowLauncher { @NonNull String applicationId; @NonNull String caption; @Nullable String startedWFProcessId; @NonNull Map<String, Object> wfParameters; @Nullable WorkflowLauncherIndicator indicator; boolean showWarningSign; @Nullable JsonTestId testId; public static JsonWorkflowLauncher of( @NonNull final WorkflowLauncher workflowLauncher, @NonNull final JsonOpts jsonOpts) { final String adLanguage = jsonOpts.getAdLanguage(); final String caption = workflowLauncher.getCaption().translate(adLanguage); final WFProcessId startedWFProcessId = workflowLauncher.getStartedWFProcessId();
final String applicationId = workflowLauncher.getApplicationId().getAsString(); Params wfParameters = workflowLauncher.getWfParameters(); if (startedWFProcessId == null) { wfParameters = wfParameters.withParameter(JsonWFProcessStartRequest.PARAM_ApplicationId, applicationId); } return builder() .applicationId(applicationId) .caption(caption) .startedWFProcessId(WFProcessId.getAsStringOrNull(startedWFProcessId)) .wfParameters(wfParameters.toJson(jsonOpts::convertValueToJson)) .indicator(workflowLauncher.getIndicator()) .showWarningSign(workflowLauncher.isPartiallyHandledBefore()) .testId(workflowLauncher.getTestId()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\json\JsonWorkflowLauncher.java
2
请在Spring Boot框架中完成以下Java代码
public class MainApplication { @Autowired private BookstoreService bookstoreService; public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\nCall AuthorRepository#findAll():"); bookstoreService.displayAuthorsWithBooksAndPublishers(); System.out.println("\nCall AuthorRepository#findByAgeLessThanOrderByNameDesc(int age):"); bookstoreService.displayAuthorsByAgeWithBooksAndPublishers(25); System.out.println("\nCall AuthorRepository#fetchAllAgeBetween20And40():"); bookstoreService.displayAuthorsByAgeBetween20And40WithBooksAndPublishers();
System.out.println("\nCall AuthorRepository#findAll(Specification):"); bookstoreService.displayAuthorsWithBooksAndPublishersWithSpec(); System.out.println("\nCall PublisherRepository#findAll():"); bookstoreService.displayPublishersWithBooksAndAuthors(); System.out.println("\nCall PublisherRepository#findByIdLessThanOrderByCompanyDesc():"); bookstoreService.displayPublishersByIdWithBooksAndAuthors(); System.out.println("\nCall PublisherRepository#findAll(Specification):"); bookstoreService.displayPublishersWithBooksAndAuthorsWithSpec(); System.out.println("\nCall PublisherRepository#fetchAllIdBetween1And3:"); bookstoreService.displayPublishersByIdBetween1And3WithBooksAndAuthors(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedSubgraph\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsCountGroupedByProcessDefinitionVersion(this); } @Override public List<ProcessDefinitionStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsGroupedByProcessDefinitionVersion(this, page); } public ProcessDefinitionStatisticsQuery includeFailedJobs() { includeFailedJobs = true; return this; } public ProcessDefinitionStatisticsQuery includeIncidents() { includeIncidents = true; return this; } public ProcessDefinitionStatisticsQuery includeIncidentsForType(String incidentType) { this.includeIncidentsForType = incidentType; return this; }
public boolean isFailedJobsToInclude() { return includeFailedJobs; } public boolean isIncidentsToInclude() { return includeIncidents || includeRootIncidents || includeIncidentsForType != null; } protected void checkQueryOk() { super.checkQueryOk(); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } if (includeRootIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeRootIncident() and includeIncidentForType() to execute one query."); } if (includeIncidents && includeRootIncidents) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeRootIncidents() to execute one query."); } } @Override public ProcessDefinitionStatisticsQuery includeRootIncidents() { this.includeRootIncidents = true; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionStatisticsQueryImpl.java
1
请完成以下Java代码
class ReflectionEnvironmentPostProcessorsFactory implements EnvironmentPostProcessorsFactory { private final @Nullable List<Class<?>> classes; private @Nullable ClassLoader classLoader; private @Nullable final List<String> classNames; ReflectionEnvironmentPostProcessorsFactory(Class<?>... classes) { this.classes = new ArrayList<>(Arrays.asList(classes)); this.classNames = null; } ReflectionEnvironmentPostProcessorsFactory(@Nullable ClassLoader classLoader, String... classNames) { this(classLoader, Arrays.asList(classNames)); } ReflectionEnvironmentPostProcessorsFactory(@Nullable ClassLoader classLoader, List<String> classNames) { this.classes = null; this.classLoader = classLoader; this.classNames = classNames; } @Override public List<EnvironmentPostProcessor> getEnvironmentPostProcessors(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext) { Instantiator<EnvironmentPostProcessor> instantiator = new Instantiator<>(EnvironmentPostProcessor.class,
(parameters) -> { parameters.add(DeferredLogFactory.class, logFactory); parameters.add(Log.class, logFactory::getLog); parameters.add(ConfigurableBootstrapContext.class, bootstrapContext); parameters.add(BootstrapContext.class, bootstrapContext); parameters.add(BootstrapRegistry.class, bootstrapContext); }); if (this.classes != null) { return instantiator.instantiateTypes(this.classes); } Assert.state(this.classNames != null, "'classNames' must not be null"); return instantiator.instantiate(this.classLoader, this.classNames); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\support\ReflectionEnvironmentPostProcessorsFactory.java
1
请完成以下Java代码
public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); } /** Get Ausschluß. @return Exclude access to the data - if not selected Include access to the data */ @Override public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Schreibgeschützt. @param IsReadOnly Field is read only */ @Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt.
@return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column_Access.java
1
请完成以下Java代码
default int size() { return getDocumentId2TopLevelRows().size(); } /* private */default Map<DocumentId, T> getDocumentId2AllRows() { return RowsDataTool.extractAllRows(getDocumentId2TopLevelRows().values()); } /** @return all rows (top level and included ones) */ default Collection<T> getAllRows() { return getDocumentId2AllRows().values(); } default Collection<T> getTopLevelRows() { return getDocumentId2TopLevelRows().values(); } /** @return top level or include row */ default T getById(final DocumentId rowId) throws EntityNotFoundException { final T row = getByIdOrNull(rowId);
if (row == null) { throw new EntityNotFoundException("Row not found") .appendParametersToMessage() .setParameter("rowId", rowId); } return row; } @Nullable default T getByIdOrNull(final DocumentId rowId) { return getDocumentId2AllRows().get(rowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\IRowsData.java
1
请完成以下Java代码
public Object clone() { return getDelegate().clone(); } @Override public String toString() { return getDelegate().toString(); } @Override public Set<Object> keySet() { return getDelegate().keySet(); } @Override public Set<java.util.Map.Entry<Object, Object>> entrySet() { return getDelegate().entrySet(); } @Override public Collection<Object> values() { return getDelegate().values(); } @Override public boolean equals(Object o) { return getDelegate().equals(o); } @SuppressWarnings("deprecation") @Override public void save(OutputStream out, String comments) { getDelegate().save(out, comments); } @Override public int hashCode() { return getDelegate().hashCode(); } @Override public void store(Writer writer, String comments) throws IOException { getDelegate().store(writer, comments); } @Override public void store(OutputStream out, String comments) throws IOException { getDelegate().store(out, comments); } @Override public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { getDelegate().loadFromXML(in); } @Override public void storeToXML(OutputStream os, String comment) throws IOException { getDelegate().storeToXML(os, comment); } @Override public void storeToXML(OutputStream os, String comment, String encoding) throws IOException { getDelegate().storeToXML(os, comment, encoding); } @Override
public String getProperty(String key) { return getDelegate().getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return getDelegate().getProperty(key, defaultValue); } @Override public Enumeration<?> propertyNames() { return getDelegate().propertyNames(); } @Override public Set<String> stringPropertyNames() { return getDelegate().stringPropertyNames(); } @Override public void list(PrintStream out) { getDelegate().list(out); } @Override public void list(PrintWriter out) { getDelegate().list(out); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\AbstractPropertiesProxy.java
1
请完成以下Java代码
public void close(final ViewCloseAction action) { if (action.isDone()) { closePickingCandidatesFromRackSystemPickingSlots(); } } private void closePickingCandidatesFromRackSystemPickingSlots() { final Set<ShipmentScheduleId> shipmentScheduleIds = getRows() .stream() .map(PackageableRow::getShipmentScheduleId) .collect(ImmutableSet.toImmutableSet()); // Close all picking candidates which are on a rack system picking slot (gh2740) pickingCandidateService.closeForShipmentSchedules(CloseForShipmentSchedulesRequest.builder() .shipmentScheduleIds(shipmentScheduleIds) .pickingSlotIsRackSystem(true) .failOnError(false) // close as much candidates as it's possible .build()); } public void setPickingSlotView(@NonNull final DocumentId rowId, @NonNull final PickingSlotView pickingSlotView) { pickingSlotsViewByRowId.put(rowId, pickingSlotView);
} public void removePickingSlotView(@NonNull final DocumentId rowId, @NonNull final ViewCloseAction viewCloseAction) { final PickingSlotView view = pickingSlotsViewByRowId.remove(rowId); if (view != null) { view.close(viewCloseAction); } } public PickingSlotView getPickingSlotViewOrNull(@NonNull final DocumentId rowId) { return pickingSlotsViewByRowId.get(rowId); } public PickingSlotView computePickingSlotViewIfAbsent(@NonNull final DocumentId rowId, @NonNull final Supplier<PickingSlotView> pickingSlotViewFactory) { return pickingSlotsViewByRowId.computeIfAbsent(rowId, id -> pickingSlotViewFactory.get()); } public void invalidatePickingSlotViews() { pickingSlotsViewByRowId.values().forEach(PickingSlotView::invalidateAll); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableView.java
1
请完成以下Java代码
public java.lang.String getGTIN_PackingMaterial() { return get_ValueAsString(COLUMNNAME_GTIN_PackingMaterial); } @Override public void setIPA_SSCC18 (final java.lang.String IPA_SSCC18) { set_Value (COLUMNNAME_IPA_SSCC18, IPA_SSCC18); } @Override public java.lang.String getIPA_SSCC18() { return get_ValueAsString(COLUMNNAME_IPA_SSCC18); } @Override public void setIsManual_IPA_SSCC18 (final boolean IsManual_IPA_SSCC18) { set_Value (COLUMNNAME_IsManual_IPA_SSCC18, IsManual_IPA_SSCC18); } @Override public boolean isManual_IPA_SSCC18() { return get_ValueAsBoolean(COLUMNNAME_IsManual_IPA_SSCC18); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID) { if (M_HU_PackagingCode_ID < 1) set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null); else set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID); } @Override public int getM_HU_PackagingCode_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID); } @Override
public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text) { throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); } @Override public java.lang.String getM_HU_PackagingCode_Text() { return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { throw new IllegalArgumentException ("M_InOut_ID is virtual column"); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java
1
请完成以下Java代码
public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyPicked (final BigDecimal QtyPicked) { set_Value (COLUMNNAME_QtyPicked, QtyPicked); } @Override public BigDecimal getQtyPicked() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason);
} @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } /** * Status AD_Reference_ID=541435 * Reference name: DD_OrderLine_Schedule_Status */ public static final int STATUS_AD_Reference_ID=541435; /** NotStarted = NS */ public static final String STATUS_NotStarted = "NS"; /** InProgress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
1
请完成以下Java代码
protected JobHandlerConfiguration getJobHandlerConfiguration() { if (processDefinitionId != null) { return ProcessDefinitionSuspensionStateConfiguration.byProcessDefinitionId(processDefinitionId, isIncludeSubResources()); } else if (isTenantIdSet) { return ProcessDefinitionSuspensionStateConfiguration.byProcessDefinitionKeyAndTenantId(processDefinitionKey, tenantId, isIncludeSubResources()); } else { return ProcessDefinitionSuspensionStateConfiguration.byProcessDefinitionKey(processDefinitionKey, isIncludeSubResources()); } } @Override protected void logUserOperation(CommandContext commandContext) { PropertyChange suspensionStateChanged = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName()); PropertyChange includeProcessInstances = new PropertyChange(INCLUDE_PROCESS_INSTANCES_PROPERTY, null, isIncludeSubResources()); commandContext.getOperationLogManager() .logProcessDefinitionOperation( getLogEntryOperation(), processDefinitionId, processDefinitionKey, Arrays.asList(suspensionStateChanged, includeProcessInstances) ); } // ABSTRACT METHODS //////////////////////////////////////////////////////////////////// /** * Subclasses should return the type of the {@link JobHandler} here. it will be used when * the user provides an execution date on which the actual state change will happen. */ @Override
protected abstract String getDelayedExecutionJobHandlerType(); /** * Subclasses should return the type of the {@link AbstractSetJobDefinitionStateCmd} here. * It will be used to suspend or activate the {@link JobDefinition}s. * @param jobDefinitionSuspensionStateBuilder */ protected abstract AbstractSetJobDefinitionStateCmd getSetJobDefinitionStateCmd(UpdateJobDefinitionSuspensionStateBuilderImpl jobDefinitionSuspensionStateBuilder); @Override protected AbstractSetProcessInstanceStateCmd getNextCommand() { UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder = createProcessInstanceCommandBuilder(); return getNextCommand(processInstanceCommandBuilder); } @Override protected String getDeploymentId(CommandContext commandContext) { if (processDefinitionId != null) { return getDeploymentIdByProcessDefinition(commandContext, processDefinitionId); } else if (processDefinitionKey != null) { return getDeploymentIdByProcessDefinitionKey(commandContext, processDefinitionKey, isTenantIdSet, tenantId); } return null; } protected abstract AbstractSetProcessInstanceStateCmd getNextCommand(UpdateProcessInstanceSuspensionStateBuilderImpl processInstanceCommandBuilder); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetProcessDefinitionStateCmd.java
1
请在Spring Boot框架中完成以下Java代码
private ImmutableMultimap<Path, JsonPrintingSegment> extractAndAssignPaths( @NonNull final JsonPrintingData printingData, @NonNull final String baseDirectory) { final ImmutableMultimap.Builder<Path, JsonPrintingSegment> path2Segments = new ImmutableMultimap.Builder<>(); for (final JsonPrintingSegment segment : printingData.getSegments()) { final JsonPrinterHW printer = segment.getPrinterHW(); if (!OUTPUTTYPE_Queue.equals(printer.getOutputType())) { continue; } Path path = null; final int trayId = segment.getTrayId(); if (trayId > 0) { final List<JsonPrinterTray> trays = printer.getTrays(); for (final JsonPrinterTray tray : trays) { if(tray.getTrayId() == trayId) { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName()), FileUtil.stripIllegalCharacters(tray.getName())) // don't use the number for the path, because we want to control it entirely with the tray name ;
break; } } if(path == null) { throw new PrintingException("Shouldn't happen. Segment has TrayId, that doesn't exist in Trays of PrinterHW"); } } else { path = Paths.get(baseDirectory, FileUtil.stripIllegalCharacters(printer.getName())); } path2Segments.put(path, segment); } return path2Segments.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-printingclient\src\main\java\de\metas\camel\externalsystems\PrintingClientPDFFileStorer.java
2
请完成以下Java代码
public <T extends CostCalculationMethodParams> T castParams(@Nullable final CostCalculationMethodParams params, @NonNull final Class<T> type) { if (params == null) { throw new AdempiereException("No calculation method parameters provided for " + type.getSimpleName()); } return type.cast(params); } public interface CaseMapper<T> { T fixedAmount(); T percentageOfAmount(); }
public <T> T map(@NonNull final CaseMapper<T> mapper) { if (this == CostCalculationMethod.FixedAmount) { return mapper.fixedAmount(); } else if (this == CostCalculationMethod.PercentageOfAmount) { return mapper.percentageOfAmount(); } else { throw new AdempiereException("Calculation method not handled: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\calculation_methods\CostCalculationMethod.java
1
请完成以下Java代码
public void setEntityType (String EntityType) { set_ValueNoCheck (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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 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(); } /** Set Version. @param Version Version of the table definition */ public void setVersion (String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ public String getVersion () { return (String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Modification.java
1
请完成以下Java代码
public class PropertyBasedCorsFilter extends AbstractHttpConfigurer<PropertyBasedCorsFilter, HttpSecurity> { protected final RestAppProperties restAppProperties; public PropertyBasedCorsFilter(RestAppProperties restAppProperties) { this.restAppProperties = restAppProperties; } @Override public void configure(HttpSecurity http) { CorsFilter corsFilter = corsFilter(restAppProperties.getCors()); http.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class); } protected CorsFilter corsFilter(RestAppProperties.Cors cors) { CorsConfiguration config = new CorsConfiguration(); if (cors.isAllowCredentials()) { config.setAllowCredentials(true); } for (String origin : cors.getAllowedOrigins()) { config.addAllowedOrigin(origin); }
for (String header : cors.getAllowedHeaders()) { config.addAllowedHeader(header); } for (String exposedHeader : cors.getExposedHeaders()) { config.addExposedHeader(exposedHeader); } for (String method : cors.getAllowedMethods()) { config.addAllowedMethod(method); } UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\conf\PropertyBasedCorsFilter.java
1
请完成以下Java代码
public DDOrderMoveSchedule createScheduleToMove(@NonNull final DDOrderMoveScheduleCreateRequest request) { final I_DD_Order_MoveSchedule record = InterfaceWrapperHelper.newInstance(I_DD_Order_MoveSchedule.class); //record.setAD_Org_ID(ddOrderline.getAD_Org_ID()); record.setDD_Order_ID(request.getDdOrderId().getRepoId()); record.setDD_OrderLine_ID(request.getDdOrderLineId().getRepoId()); record.setStatus(DDOrderMoveScheduleStatus.NOT_STARTED.getCode()); record.setM_Product_ID(request.getProductId().getRepoId()); // // Pick From record.setPickFrom_Warehouse_ID(request.getPickFromLocatorId().getWarehouseId().getRepoId()); record.setPickFrom_Locator_ID(request.getPickFromLocatorId().getRepoId()); record.setPickFrom_HU_ID(request.getPickFromHUId().getRepoId()); record.setC_UOM_ID(request.getQtyToPick().getUomId().getRepoId()); record.setQtyToPick(request.getQtyToPick().toBigDecimal()); record.setQtyPicked(BigDecimal.ZERO); record.setIsPickWholeHU(request.isPickWholeHU()); // // Drop To record.setDropTo_Warehouse_ID(request.getDropToLocatorId().getWarehouseId().getRepoId()); record.setDropTo_Locator_ID(request.getDropToLocatorId().getRepoId()); // InterfaceWrapperHelper.saveRecord(record); addToCache(record, ImmutableList.of()); return fromRecord(record); } public DDOrderMoveSchedule updateById(final DDOrderMoveScheduleId id, Consumer<DDOrderMoveSchedule> updater)
{ warmUpById(id); final I_DD_Order_MoveSchedule record = getRecordById(id); final DDOrderMoveSchedule schedule = fromRecord(record); updater.accept(schedule); save(schedule); return schedule; } public ImmutableList<DDOrderMoveSchedule> updateByIds(final Set<DDOrderMoveScheduleId> ids, Consumer<DDOrderMoveSchedule> updater) { warmUpByIds(ids); ImmutableList.Builder<DDOrderMoveSchedule> result = ImmutableList.builder(); ids.forEach(id -> { final I_DD_Order_MoveSchedule record = getRecordById(id); final DDOrderMoveSchedule schedule = fromRecord(record); updater.accept(schedule); save(schedule); result.add(schedule); }); return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleLoaderAndSaver.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof Square)) { return false; } Square other = (Square) obj; if (color == null) { if (other.color != null) { return false; }
} else if (!color.equals(other.color)) { return false; } return true; } protected Color getColor() { return color; } protected void setColor(Color color) { this.color = color; } }
repos\tutorials-master\core-java-modules\core-java-lang-8\src\main\java\com\baeldung\equalshashcode\entities\Square.java
1
请完成以下Java代码
public ListenableFuture<String> getCustomerName() { String[] names = new String[] { "Mark", "Jane", "June" }; return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return names[new Random().nextInt(names.length)]; }); } public ListenableFuture<List<String>> getCartItems() { String[] items = new String[] { "Apple", "Orange", "Mango", "Pineapple" }; return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); int noOfItems = new Random().nextInt(items.length); if (noOfItems == 0) ++noOfItems; return Arrays.stream(items, 0, noOfItems).collect(Collectors.toList()); }); } public ListenableFuture<String> generateUsername(String firstName) {
return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); return firstName.replaceAll("[^a-zA-Z]+","") .concat("@service.com"); }); } public ListenableFuture<String> generatePassword(String username) { return lExecService.submit(() -> { TimeUnit.MILLISECONDS.sleep(500); if (username.contains("@")) { String[] parts = username.split("@"); return parts[0] + "123@" + parts[1]; } else { return username + "123"; } }); } }
repos\tutorials-master\guava-modules\guava-concurrency\src\main\java\com\baeldung\guava\future\ListenableFutureService.java
1
请完成以下Java代码
public void propertyChange (PropertyChangeEvent e) { MTreeNode tn = (MTreeNode)e.getNewValue(); log.info(tn.toString()); if (tn == null) return; ListModel model = centerList.getModel(); int size = model.getSize(); int index = -1; for (index = 0; index < size; index++) { ListItem item = (ListItem)model.getElementAt(index); if (item.id == tn.getNode_ID()) break; } centerList.setSelectedIndex(index); } // propertyChange /** * Action: Add Node to Tree * @param item item */ private void action_treeAdd(ListItem item) { log.info("Item=" + item); if (item != null) { MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1, item.isSummary, item.imageIndicator, false, null); centerTree.nodeChanged(true, info); // May cause Error if in tree addNode(item); } } // action_treeAdd /** * Action: Delete Node from Tree * @param item item */ private void action_treeDelete(ListItem item) { log.info("Item=" + item); if (item != null)
{ MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1, item.isSummary, item.imageIndicator, false, null); centerTree.nodeChanged(false, info); deleteNode(item); } } // action_treeDelete /** * Action: Add All Nodes to Tree */ private void action_treeAddAll() { log.info(""); ListModel model = centerList.getModel(); int size = model.getSize(); int index = -1; for (index = 0; index < size; index++) { ListItem item = (ListItem)model.getElementAt(index); action_treeAdd(item); } } // action_treeAddAll /** * Action: Delete All Nodes from Tree */ private void action_treeDeleteAll() { log.info(""); ListModel model = centerList.getModel(); int size = model.getSize(); int index = -1; for (index = 0; index < size; index++) { ListItem item = (ListItem)model.getElementAt(index); action_treeDelete(item); } } // action_treeDeleteAll } // VTreeMaintenance
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTreeMaintenance.java
1
请在Spring Boot框架中完成以下Java代码
public class Foo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(nullable = false) private String name; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1;
result = prime * result + ((name == null) ? 0 : name.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 Foo other = (Foo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\jpa\domain\Foo.java
2
请完成以下Java代码
public BigDecimal getQtyToAllocate() { return qtyToAllocate; } @Override public BigDecimal getQtyAllocated() { return qtyToAllocateInitial.subtract(qtyToAllocate); } @Override public void addTransaction(final IHUTransactionCandidate trx) { transactions.add(trx); } @Override public void addTransactions(final List<IHUTransactionCandidate> trxs) { trxs.forEach(trx -> addTransaction(trx)); } @Override public List<IHUTransactionCandidate> getTransactions() { return transactionsRO; } @Override public void addAttributeTransaction(final IHUTransactionAttribute attributeTrx) { attributeTransactions.add(attributeTrx); }
@Override public void addAttributeTransactions(final List<IHUTransactionAttribute> attributeTrxs) { attributeTransactions.addAll(attributeTrxs); } @Override public List<IHUTransactionAttribute> getAttributeTransactions() { return attributeTransactionsRO; } @Override public void aggregateTransactions() { final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); final List<IHUTransactionCandidate> aggregateTransactions = huTrxBL.aggregateTransactions(transactions); transactions.clear(); transactions.addAll(aggregateTransactions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\MutableAllocationResult.java
1
请完成以下Java代码
public class MetricsResourceImpl implements MetricsResource { protected String metricsName; protected ProcessEngine processEngine; protected ObjectMapper objectMapper; public MetricsResourceImpl(String metricsName, ProcessEngine processEngine, ObjectMapper objectMapper) { this.metricsName = metricsName; this.processEngine = processEngine; this.objectMapper = objectMapper; } @Override public MetricsResultDto sum(UriInfo uriInfo) { MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters(); DateConverter dateConverter = new DateConverter(); dateConverter.setObjectMapper(objectMapper); Number result = null; if (Metrics.UNIQUE_TASK_WORKERS.equals(metricsName) || Metrics.TASK_USERS.equals(metricsName)) { result = processEngine.getManagementService().getUniqueTaskWorkerCount( extractStartDate(queryParameters, dateConverter), extractEndDate(queryParameters, dateConverter)); } else { MetricsQuery query = processEngine.getManagementService() .createMetricsQuery() .name(metricsName); applyQueryParams(queryParameters, dateConverter, query); result = query.sum(); } return new MetricsResultDto(result); } protected void applyQueryParams(MultivaluedMap<String, String> queryParameters, DateConverter dateConverter, MetricsQuery query) { Date startDate = extractStartDate(queryParameters, dateConverter); Date endDate = extractEndDate(queryParameters, dateConverter); if (startDate != null) { query.startDate(startDate); } if (endDate != null) {
query.endDate(endDate); } } protected Date extractEndDate(MultivaluedMap<String, String> queryParameters, DateConverter dateConverter) { if(queryParameters.getFirst("endDate") != null) { return dateConverter.convertQueryParameterToType(queryParameters.getFirst("endDate")); } return null; } protected Date extractStartDate(MultivaluedMap<String, String> queryParameters, DateConverter dateConverter) { if(queryParameters.getFirst("startDate") != null) { return dateConverter.convertQueryParameterToType(queryParameters.getFirst("startDate")); } return null; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\metrics\MetricsResourceImpl.java
1
请完成以下Java代码
public class ClearPickingSlot extends JavaProcess implements IProcessPrecondition { private final SpringContextHolder.Lazy<PickingSlotService> pickingSlotServiceLazy = SpringContextHolder.lazyBean(PickingSlotService.class); @Param(parameterName = "ForceRemoveForOngoingJobs") private boolean forceRemoveForOngoingJobs; @Param(parameterName = "RemoveUnprocessedHUsFromSlot") private boolean removeUnprocessedHUsFromSlot; @Param(parameterName = "RemoveQueuedHUsFromSlot") private boolean removeQueuedHUsFromSlot; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
} return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { pickingSlotServiceLazy.get().releasePickingSlot(ReleasePickingSlotRequest.builder() .pickingSlotId(PickingSlotId.ofRepoId(getRecord_ID())) .isForceRemoveForOngoingJobs(forceRemoveForOngoingJobs) .removeUnprocessedHUsFromSlot(removeUnprocessedHUsFromSlot) .removeQueuedHUsFromSlot(removeQueuedHUsFromSlot) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\process\ClearPickingSlot.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isSigningCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.SIGNING); } /** * Indicate whether this credential can be used for decryption * @return true if the credential has a {@link Saml2X509CredentialType#DECRYPTION} * type */ public boolean isDecryptionCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.DECRYPTION); } /** * Indicate whether this credential can be used for verification * @return true if the credential has a {@link Saml2X509CredentialType#VERIFICATION} * type */ public boolean isVerificationCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.VERIFICATION); } /** * Indicate whether this credential can be used for encryption * @return true if the credential has a {@link Saml2X509CredentialType#ENCRYPTION} * type */ public boolean isEncryptionCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.ENCRYPTION); } /** * List all this credential's intended usages * @return the set of this credential's intended usages */ public Set<Saml2X509CredentialType> getCredentialTypes() { return this.credentialTypes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Saml2X509Credential that = (Saml2X509Credential) o; return Objects.equals(this.privateKey, that.privateKey) && this.certificate.equals(that.certificate) && this.credentialTypes.equals(that.credentialTypes); } @Override public int hashCode() { return Objects.hash(this.privateKey, this.certificate, this.credentialTypes); } private void validateUsages(Saml2X509CredentialType[] usages, Saml2X509CredentialType... validUsages) {
for (Saml2X509CredentialType usage : usages) { boolean valid = false; for (Saml2X509CredentialType validUsage : validUsages) { if (usage == validUsage) { valid = true; break; } } Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } public enum Saml2X509CredentialType { VERIFICATION, ENCRYPTION, SIGNING, DECRYPTION, } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2X509Credential.java
2
请在Spring Boot框架中完成以下Java代码
private boolean isSameUnderlyingResource(Resource ours, Resource other) { return ours.equals(other) || isSameFile(getUnderlyingFile(ours), getUnderlyingFile(other)); } private boolean isSameFile(@Nullable File ours, @Nullable File other) { return (ours != null) && ours.equals(other); } @Override public int hashCode() { File underlyingFile = getUnderlyingFile(this.resource); return (underlyingFile != null) ? underlyingFile.hashCode() : this.resource.hashCode(); } @Override public String toString() { if (this.resource instanceof FileSystemResource || this.resource instanceof FileUrlResource) { try { return "file [" + this.resource.getFile() + "]"; } catch (IOException ex) { // Ignore } }
return this.resource.toString(); } private @Nullable File getUnderlyingFile(Resource resource) { try { if (resource instanceof ClassPathResource || resource instanceof FileSystemResource || resource instanceof FileUrlResource) { return resource.getFile().getAbsoluteFile(); } } catch (IOException ex) { // Ignore } return null; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataResource.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class OnEnabledComponent<T> extends SpringBootCondition implements ConfigurationCondition { private static final String PREFIX = "spring.cloud.gateway.server.webflux."; private static final String SUFFIX = ".enabled"; @Override public ConfigurationPhase getConfigurationPhase() { return ConfigurationPhase.REGISTER_BEAN; } @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { Class<? extends T> candidate = getComponentType(annotationClass(), context, metadata); return determineOutcome(candidate, context.getEnvironment()); } @SuppressWarnings("unchecked") protected Class<? extends T> getComponentType(Class<?> annotationClass, ConditionContext context, AnnotatedTypeMetadata metadata) { Map<String, Object> attributes = metadata.getAnnotationAttributes(annotationClass.getName()); if (attributes != null && attributes.containsKey("value")) { Class<?> target = (Class<?>) attributes.get("value"); if (target != defaultValueClass()) { return (Class<? extends T>) target; } } Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()), getClass().getSimpleName() + " must be used on @Bean methods when the value is not specified"); MethodMetadata methodMetadata = (MethodMetadata) metadata; try { return (Class<? extends T>) ClassUtils.forName(methodMetadata.getReturnTypeName(),
context.getClassLoader()); } catch (Throwable ex) { throw new IllegalStateException("Failed to extract component class for " + methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(), ex); } } private ConditionOutcome determineOutcome(Class<? extends T> componentClass, PropertyResolver resolver) { String key = PREFIX + normalizeComponentName(componentClass) + SUFFIX; ConditionMessage.Builder messageBuilder = forCondition(annotationClass().getName(), componentClass.getName()); if ("false".equalsIgnoreCase(resolver.getProperty(key))) { return ConditionOutcome.noMatch(messageBuilder.because("bean is not available")); } return ConditionOutcome.match(); } protected abstract String normalizeComponentName(Class<? extends T> componentClass); protected abstract Class<?> annotationClass(); protected abstract Class<? extends T> defaultValueClass(); }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\conditional\OnEnabledComponent.java
2
请完成以下Java代码
public class UserDetailParam { private String userId; private Integer minAge; private Integer maxAge; private String realName; private String introduction; private String city; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Integer getMinAge() { return minAge; } public void setMinAge(Integer minAge) { this.minAge = minAge; } public Integer getMaxAge() { return maxAge; } public void setMaxAge(Integer maxAge) { this.maxAge = maxAge; } public String getRealName() {
return realName; } public void setRealName(String realName) { this.realName = realName; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\param\UserDetailParam.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoServiceImpl implements DemoService { @Autowired private PersonRepository personRepository; @Override //@CachePut缓存新增的或更新的数据到缓存,其中缓存名字是 people 。数据的key是person的id @CachePut(value = "people", key = "#person.id") public Person save(Person person) { Person p = personRepository.save(person); System.out.println("为id、key为:"+p.getId()+"数据做了缓存"); return p; } @Override //@CacheEvict 从缓存people中删除key为id 的数据
@CacheEvict(value = "people") public void remove(Long id) { System.out.println("删除了id、key为"+id+"的数据缓存"); //这里不做实际删除操作 } @Override //@Cacheable缓存key为person 的id 数据到缓存people 中,如果没有指定key则方法参数作为key保存到缓存中。 @Cacheable(value = "people", key = "#person.id") public Person findOne(Person person) { Person p = personRepository.findOne(person.getId()); System.out.println("为id、key为:"+p.getId()+"数据做了缓存"); return p; } }
repos\springBoot-master\springboot-Cache\src\main\java\com\us\example\service\Impl\DemoServiceImpl.java
2
请完成以下Java代码
private Inventory assigningTo(@NonNull final UserId newResponsibleId, boolean allowReassignment) { // no responsible change if (UserId.equals(responsibleId, newResponsibleId)) { return this; } if (!newResponsibleId.isRegularUser()) { throw new AdempiereException("Only regular users can be assigned to an inventory"); } if (!allowReassignment && responsibleId != null) { throw new AdempiereException("Inventory is already assigned"); } return toBuilder().responsibleId(newResponsibleId).build(); } public Inventory unassign() { return responsibleId == null ? this : toBuilder().responsibleId(null).build(); } public void assertHasAccess(@NonNull final UserId calledId) { if (!UserId.equals(responsibleId, calledId)) { throw new AdempiereException("No access"); } } public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId) {
return onlyLineId != null ? Stream.of(getLineById(onlyLineId)) : lines.stream(); } public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId) { return streamLines(onlyLineId) .filter(InventoryLine::isEligibleForCounting) .map(InventoryLine::getLocatorId) .collect(ImmutableSet.toImmutableSet()); } public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater) { final ImmutableList<InventoryLine> newLines = CollectionUtils.map( this.lines, line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line ); return this.lines == newLines ? this : toBuilder().lines(newLines).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java
1
请在Spring Boot框架中完成以下Java代码
public class PP_Order_CopyTemplateCustomizer implements CopyTemplateCustomizer { @Override public String getTableName() {return I_PP_Order.Table_Name;} @Override public ValueToCopy extractValueToCopy(final POInfo poInfo, final String columnName) { if (de.metas.materialtracking.model.I_PP_Order.COLUMNNAME_QtyOrdered.equals(columnName)) { return ValueToCopy.computeFunction(PP_Order_CopyTemplateCustomizer::computeQtyOrdered); } else { return ValueToCopy.NOT_SPECIFIED; } }
private static BigDecimal computeQtyOrdered(final ValueToCopyResolveContext context) { final PO from = context.getFrom(); final BigDecimal qtyOrderedBeforeOrderClose = from.get_ValueAsBigDecimal(de.metas.materialtracking.model.I_PP_Order.COLUMNNAME_QtyBeforeClose); final BigDecimal qtyEntered = from.get_ValueAsBigDecimal(de.metas.materialtracking.model.I_PP_Order.COLUMNNAME_QtyEntered); return qtyOrderedBeforeOrderClose == null || qtyOrderedBeforeOrderClose.signum() == 0 ? qtyEntered : qtyOrderedBeforeOrderClose; } @Override public @NonNull InSetPredicate<String> getChildTableNames() {return InSetPredicate.none();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\PP_Order_CopyTemplateCustomizer.java
2
请完成以下Java代码
private void resetManualFlags(final I_C_OrderLine orderLineRecord) { orderLineRecord.setIsManualDiscount(false); orderLineRecord.setIsManualPrice(false); orderLineRecord.setIsManualPaymentTerm(false); orderLineBL.updatePrices(orderLineRecord); // see task 06727 } @CalloutMethod(columnNames = { I_C_OrderLine.COLUMNNAME_Discount }, skipIfCopying = true, skipIfIndirectlyCalled = true) public void SetIsManualDiscount(final I_C_OrderLine orderLine) { orderLine.setIsManualDiscount(true); } /** * Sets {@code C_OrderLine.IsManualPrice='Y'}, but only if the user "manually" edited the price. */ @CalloutMethod(columnNames = { I_C_OrderLine.COLUMNNAME_PriceEntered }, skipIfCopying = true, skipIfIndirectlyCalled = true) public void setIsManualPriceFlag(final I_C_OrderLine orderLine) { orderLine.setIsManualPrice(true); } @CalloutMethod(columnNames = {
I_C_OrderLine.COLUMNNAME_C_BPartner_ID, I_C_OrderLine.COLUMNNAME_C_BPartner_Location_ID }, skipIfCopying = true) public void updateBPartnerAddress(final I_C_OrderLine orderLine) { documentLocationBL.updateRenderedAddressAndCapturedLocation(OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine)); } @CalloutMethod(columnNames = I_C_OrderLine.COLUMNNAME_AD_User_ID, skipIfCopying = true) public void updateRenderedAddress(final I_C_OrderLine orderLine) { documentLocationBL.updateRenderedAddress(OrderLineDocumentLocationAdapterFactory.locationAdapter(orderLine)); } @CalloutMethod(columnNames = { I_C_OrderLine.COLUMNNAME_C_BPartner_ID }, skipIfCopying = true) public void updateBPartnerLocation(final I_C_OrderLine orderLine) { orderLineBL.setBPLocation(orderLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\callout\C_OrderLine.java
1
请完成以下Java代码
class FileProducer implements Runnable { private final BlockingQueue<String> queue; private final String inputFileName; public FileProducer(BlockingQueue<String> queue, String inputFileName) { this.queue = queue; this.inputFileName = inputFileName; } @Override public void run() { try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) { String line; while ((line = reader.readLine()) != null) { queue.offer(line); System.out.println("Producer added line: " + line); System.out.println("Queue size: " + queue.size()); } } catch (IOException e) { e.printStackTrace(); } } } class FileConsumer implements Runnable { private final BlockingQueue<String> queue; private final String outputFileName;
public FileConsumer(BlockingQueue queue, String outputFileName) { this.queue = queue; this.outputFileName = outputFileName; } @Override public void run() { try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) { String line; while ((line = queue.poll()) != null) { writer.write(line); writer.newLine(); System.out.println(Thread.currentThread() .getId() + " - Consumer processed line: " + line); System.out.println("Queue size: " + queue.size()); } } catch (IOException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\readwritethread\ReadWriteBlockingQueue.java
1
请在Spring Boot框架中完成以下Java代码
public R<List<DeptVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> dept, BladeUser bladeUser) { QueryWrapper<Dept> queryWrapper = Condition.getQueryWrapper(dept, Dept.class); List<Dept> list = deptService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Dept::getTenantId, bladeUser.getTenantId()) : queryWrapper); return R.data(DeptWrapper.build().listNodeVO(list)); } /** * 获取部门树形结构 * * @return */ @GetMapping("/tree") @ApiOperationSupport(order = 3) @Operation(summary = "树形结构", description = "树形结构") public R<List<DeptVO>> tree(String tenantId, BladeUser bladeUser) { List<DeptVO> tree = deptService.tree(Func.toStr(tenantId, bladeUser.getTenantId())); return R.data(tree); } /** * 新增或修改 */ @PostMapping("/submit") @ApiOperationSupport(order = 4) @Operation(summary = "新增或修改", description = "传入dept")
public R submit(@Valid @RequestBody Dept dept) { return R.status(deptService.submit(dept)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 5) @Operation(summary = "删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(deptService.removeByIds(Func.toLongList(ids))); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\DeptController.java
2
请完成以下Java代码
public boolean isInternalUseInventory() { return inventoryType.isInternalUse(); } public InventoryLine getLineById(@NonNull final InventoryLineId inventoryLineId) { return lines.stream() .filter(line -> inventoryLineId.equals(line.getId())) .findFirst() .orElseThrow(() -> new AdempiereException("No line found for " + inventoryLineId + " in " + this)); } public ImmutableList<InventoryLineHU> getLineHUs() { return streamLineHUs().collect(ImmutableList.toImmutableList()); } private Stream<InventoryLineHU> streamLineHUs() { return lines.stream().flatMap(line -> line.getInventoryLineHUs().stream()); } public ImmutableSet<HuId> getHuIds() { return InventoryLineHU.extractHuIds(streamLineHUs()); } public Inventory assigningTo(@NonNull final UserId newResponsibleId) { return assigningTo(newResponsibleId, false); } public Inventory reassigningTo(@NonNull final UserId newResponsibleId) { return assigningTo(newResponsibleId, true); } private Inventory assigningTo(@NonNull final UserId newResponsibleId, boolean allowReassignment) { // no responsible change if (UserId.equals(responsibleId, newResponsibleId)) { return this; } if (!newResponsibleId.isRegularUser()) { throw new AdempiereException("Only regular users can be assigned to an inventory"); } if (!allowReassignment && responsibleId != null) { throw new AdempiereException("Inventory is already assigned"); }
return toBuilder().responsibleId(newResponsibleId).build(); } public Inventory unassign() { return responsibleId == null ? this : toBuilder().responsibleId(null).build(); } public void assertHasAccess(@NonNull final UserId calledId) { if (!UserId.equals(responsibleId, calledId)) { throw new AdempiereException("No access"); } } public Stream<InventoryLine> streamLines(@Nullable final InventoryLineId onlyLineId) { return onlyLineId != null ? Stream.of(getLineById(onlyLineId)) : lines.stream(); } public Set<LocatorId> getLocatorIdsEligibleForCounting(@Nullable final InventoryLineId onlyLineId) { return streamLines(onlyLineId) .filter(InventoryLine::isEligibleForCounting) .map(InventoryLine::getLocatorId) .collect(ImmutableSet.toImmutableSet()); } public Inventory updatingLineById(@NonNull final InventoryLineId lineId, @NonNull UnaryOperator<InventoryLine> updater) { final ImmutableList<InventoryLine> newLines = CollectionUtils.map( this.lines, line -> InventoryLineId.equals(line.getId(), lineId) ? updater.apply(line) : line ); return this.lines == newLines ? this : toBuilder().lines(newLines).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\Inventory.java
1
请完成以下Java代码
protected JmxManagedProcessEngineController createProcessEngineControllerInstance(ProcessEngineConfigurationImpl configuration) { return new JmxManagedProcessEngineController(configuration); } /** * <p>Instantiates and applies all {@link ProcessEnginePlugin}s defined in the processEngineXml */ protected void configurePlugins(ProcessEngineConfigurationImpl configuration, ProcessEngineXml processEngineXml, ClassLoader classLoader) { for (ProcessEnginePluginXml pluginXml : processEngineXml.getPlugins()) { // create plugin instance Class<? extends ProcessEnginePlugin> pluginClass = loadClass(pluginXml.getPluginClass(), classLoader, ProcessEnginePlugin.class); ProcessEnginePlugin plugin = ReflectUtil.createInstance(pluginClass); // apply configured properties Map<String, String> properties = pluginXml.getProperties(); PropertyHelper.applyProperties(plugin, properties); // add to configuration configuration.getProcessEnginePlugins().add(plugin); } } protected JobExecutor getJobExecutorService(final PlatformServiceContainer serviceContainer) { // lookup container managed job executor String jobAcquisitionName = processEngineXml.getJobAcquisitionName(); JobExecutor jobExecutor = serviceContainer.getServiceValue(ServiceTypes.JOB_EXECUTOR, jobAcquisitionName); return jobExecutor; } @SuppressWarnings("unchecked") protected <T> Class<? extends T> loadClass(String className, ClassLoader customClassloader, Class<T> clazz) { try { return ReflectUtil.loadClass(className, customClassloader, clazz); } catch (ClassNotFoundException e) { throw LOG.cannotLoadConfigurationClass(className, e);
} catch (ClassCastException e) { throw LOG.configurationClassHasWrongType(className, clazz, e); } } /** * Add additional plugins that are not declared in the process engine xml. */ protected void addAdditionalPlugins(ProcessEngineConfigurationImpl configuration) { // do nothing } protected void additionalConfiguration(ProcessEngineConfigurationImpl configuration) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StartProcessEngineStep.java
1
请在Spring Boot框架中完成以下Java代码
public void notifyOrderCreated(Order order) { tpl.execute("NOTIFY " + ORDERS_CHANNEL + ", '" + order.getId() + "'"); } public Runnable createNotificationHandler(Consumer<PGNotification> consumer) { return () -> { tpl.execute((Connection c) -> { log.info("notificationHandler: sending LISTEN command..."); c.createStatement().execute("LISTEN " + ORDERS_CHANNEL); PGConnection pgconn = c.unwrap(PGConnection.class); while(!Thread.currentThread().isInterrupted()) { PGNotification[] nts = pgconn.getNotifications(10000);
if ( nts == null || nts.length == 0 ) { continue; } for( PGNotification nt : nts) { consumer.accept(nt); } } return 0; }); }; } }
repos\tutorials-master\messaging-modules\postgres-notify\src\main\java\com\baeldung\messaging\postgresql\service\NotifierService.java
2
请完成以下Java代码
public ViewRowIdsOrderedSelection getOrderedSelection(@Nullable final DocumentQueryOrderByList orderBys) { if(orderBys == null || orderBys.isEmpty()) { return getDefaultSelection(); } return computeCurrentSelections(selections -> computeOrderBySelectionIfAbsent(selections, orderBys)) .getSelection(orderBys); } private ViewRowIdsOrderedSelections computeOrderBySelectionIfAbsent( @NonNull final ViewRowIdsOrderedSelections selections, @Nullable final DocumentQueryOrderByList orderBys) { return selections.withOrderBysSelectionIfAbsent( orderBys, this::createSelectionFromSelection); } private ViewRowIdsOrderedSelection createSelectionFromSelection( @NonNull final ViewRowIdsOrderedSelection fromSelection, @Nullable final DocumentQueryOrderByList orderBys) { final ViewEvaluationCtx viewEvaluationCtx = getViewEvaluationCtx();
final SqlDocumentFilterConverterContext filterConverterContext = SqlDocumentFilterConverterContext.builder() .userRolePermissionsKey(viewEvaluationCtx.getPermissionsKey()) .build(); return viewDataRepository.createOrderedSelectionFromSelection( viewEvaluationCtx, fromSelection, DocumentFilterList.EMPTY, orderBys, filterConverterContext); } public Set<DocumentId> retainExistingRowIds(@NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } return viewDataRepository.retrieveRowIdsMatchingFilters( viewId, DocumentFilterList.EMPTY, rowIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelectionsHolder.java
1
请完成以下Java代码
public class PactDto { private boolean condition; private String name; public PactDto() { } public PactDto(boolean condition, String name) { super(); this.condition = condition; this.name = name; } public boolean isCondition() { return condition;
} public void setCondition(boolean condition) { this.condition = condition; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\dto\PactDto.java
1
请在Spring Boot框架中完成以下Java代码
public class MultiFileIteamReaderDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job multiFileItemReaderJob() { return jobBuilderFactory.get("multiFileItemReaderJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(multiFileItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> multiFileItemReader() { MultiResourceItemReader<TestData> reader = new MultiResourceItemReader<>(); reader.setDelegate(fileItemReader()); // 设置文件读取代理,方法可以使用前面文件读取中的例子 Resource[] resources = new Resource[]{ new ClassPathResource("file1"), new ClassPathResource("file2") }; reader.setResources(resources); // 设置多文件源 return reader; }
private FlatFileItemReader<TestData> fileItemReader() { FlatFileItemReader<TestData> reader = new FlatFileItemReader<>(); reader.setLinesToSkip(1); // 忽略第一行 // AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取, // 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符 DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); // 设置属姓名,类似于表头 tokenizer.setNames("id", "field1", "field2", "field3"); // 将每行数据转换为TestData对象 DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>(); mapper.setLineTokenizer(tokenizer); // 设置映射方式 mapper.setFieldSetMapper(fieldSet -> { TestData data = new TestData(); data.setId(fieldSet.readInt("id")); data.setField1(fieldSet.readString("field1")); data.setField2(fieldSet.readString("field2")); data.setField3(fieldSet.readString("field3")); return data; }); reader.setLineMapper(mapper); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\MultiFileIteamReaderDemo.java
2
请完成以下Java代码
protected void deleteEntity(DbEntityOperation operation) { final DbEntity dbEntity = operation.getEntity(); // get statement String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass()); ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement); LOG.executeDatabaseOperation("DELETE", dbEntity); try { int nrOfRowsDeleted = executeDelete(deleteStatement, dbEntity); entityDeletePerformed(operation, nrOfRowsDeleted, null); } catch (PersistenceException e) { entityDeletePerformed(operation, 0, e); } } @Override protected void deleteBulk(DbBulkOperation operation) { String statement = operation.getStatement(); Object parameter = operation.getParameter(); LOG.executeDatabaseBulkOperation("DELETE", statement, parameter); try { int rowsAffected = executeDelete(statement, parameter); bulkDeletePerformed(operation, rowsAffected, null); } catch (PersistenceException e) { bulkDeletePerformed(operation, 0, e); } } // update //////////////////////////////////////// @Override
protected void updateEntity(DbEntityOperation operation) { final DbEntity dbEntity = operation.getEntity(); String updateStatement = dbSqlSessionFactory.getUpdateStatement(dbEntity); ensureNotNull("no update statement for " + dbEntity.getClass() + " in the ibatis mapping files", "updateStatement", updateStatement); LOG.executeDatabaseOperation("UPDATE", dbEntity); try { int rowsAffected = executeUpdate(updateStatement, dbEntity); entityUpdatePerformed(operation, rowsAffected, null); } catch (PersistenceException e) { entityUpdatePerformed(operation, 0, e); } } @Override protected void updateBulk(DbBulkOperation operation) { String statement = operation.getStatement(); Object parameter = operation.getParameter(); LOG.executeDatabaseBulkOperation("UPDATE", statement, parameter); try { int rowsAffected = executeUpdate(statement, parameter); bulkUpdatePerformed(operation, rowsAffected, null); } catch (PersistenceException e) { bulkUpdatePerformed(operation, 0, e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\SimpleDbSqlSession.java
1
请完成以下Java代码
private static String extractChartOfAccountsNameNotNull(final @NonNull I_I_ElementValue importRecord) { final String chartOfAccountsName = StringUtils.trimBlankToNull(importRecord.getElementName()); if (chartOfAccountsName == null) { throw new FillMandatoryException(I_I_ElementValue.COLUMNNAME_ElementName); } return chartOfAccountsName; } public void setChartOfAccountsToDefaultSchemaElement(@NonNull final ChartOfAccountsId chartOfAccountsId) { final AcctSchemaId primaryAcctSchemaId = acctSchemasRepo.getPrimaryAcctSchemaId(ClientId.METASFRESH); final AcctSchema acctSchema = acctSchemasRepo.getById(primaryAcctSchemaId); final AcctSchemaElement accountElement = acctSchema.getSchemaElementByType(AcctSchemaElementType.Account); accountElement.setChartOfAccountsId(chartOfAccountsId); acctSchemasRepo.saveAcctSchemaElement(accountElement); } @NonNull
public OrgId extractOrgId(@NonNull final I_I_ElementValue importRecord) { final String orgValue = importRecord.getOrgValue(); if (Check.isNotBlank(orgValue)) { final I_AD_Org orgRecord = orgDAO.retrieveOrganizationByValue(Env.getCtx(), orgValue); if (orgRecord != null) { return OrgId.ofRepoId(orgRecord.getAD_Org_ID()); } } return OrgId.ANY; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\impexp\ChartOfAccountsImportHelper.java
1
请完成以下Java代码
public List<DocumentLayoutElementDescriptor> getElements() { return elements; } public static final class Builder { private static final Logger logger = LogManager.getLogger(DocumentLayoutElementLineDescriptor.Builder.class); private String internalName; private final List<DocumentLayoutElementDescriptor.Builder> elementsBuilders = new ArrayList<>(); private Builder() { } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("internalName", internalName) .add("elements-count", elementsBuilders.size()) .toString(); } public DocumentLayoutElementLineDescriptor build() { final DocumentLayoutElementLineDescriptor result = new DocumentLayoutElementLineDescriptor(this); logger.trace("Built {} for {}", result, this); return result; } private List<DocumentLayoutElementDescriptor> buildElements() { return elementsBuilders .stream() .filter(elementBuilder -> checkValid(elementBuilder)) .map(elementBuilder -> elementBuilder.build()) .filter(element -> checkValid(element)) .collect(GuavaCollectors.toImmutableList()); } private final boolean checkValid(final DocumentLayoutElementDescriptor.Builder elementBuilder) { if (elementBuilder.isConsumed()) { logger.trace("Skip adding {} to {} because it's already consumed", elementBuilder, this); return false; }
if (elementBuilder.isEmpty()) { logger.trace("Skip adding {} to {} because it's empty", elementBuilder, this); return false; } return true; } private final boolean checkValid(final DocumentLayoutElementDescriptor element) { if (element.isEmpty()) { logger.trace("Skip adding {} to {} because it does not have fields", element, this); return false; } return true; } public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) { elementsBuilders.add(elementBuilder); return this; } public boolean hasElements() { return !elementsBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementsBuilders.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementLineDescriptor.java
1
请完成以下Java代码
public class ExternalWorkerTaskCompleteJobHandler implements JobHandler { public static final String TYPE = "cmmn-external-worker-complete"; protected CmmnEngineConfiguration cmmnEngineConfiguration; public ExternalWorkerTaskCompleteJobHandler(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } @Override public String getType() { return TYPE; } @Override public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) { PlanItemInstanceEntity planItemInstanceEntity = (PlanItemInstanceEntity) variableScope; VariableService variableService = cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableService(); List<VariableInstanceEntity> jobVariables = variableService.findVariableInstanceBySubScopeIdAndScopeType(planItemInstanceEntity.getId(), ScopeTypes.CMMN_EXTERNAL_WORKER);
if (!jobVariables.isEmpty()) { for (VariableInstanceEntity jobVariable : jobVariables) { planItemInstanceEntity.setVariable(jobVariable.getName(), jobVariable.getValue()); variableService.deleteVariableInstance(jobVariable); } if (planItemInstanceEntity instanceof CountingPlanItemInstanceEntity) { ((CountingPlanItemInstanceEntity) planItemInstanceEntity) .setVariableCount(((CountingPlanItemInstanceEntity) planItemInstanceEntity).getVariableCount() - jobVariables.size()); } } if (configuration != null && configuration.startsWith("terminate:")) { //TODO maybe pass exitType and exitEventType CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(planItemInstanceEntity, null, null); } else { CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstanceEntity); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\ExternalWorkerTaskCompleteJobHandler.java
1
请完成以下Java代码
public AssociationDirection getAssociationDirection() { return associationDirectionAttribute.getValue(this); } public void setAssociationDirection(AssociationDirection associationDirection) { associationDirectionAttribute.setValue(this, associationDirection); } public DmnElement getSource() { return sourceRef.getReferenceTargetElement(this); } public void setSource(DmnElement source) { sourceRef.setReferenceTargetElement(this, source); } public DmnElement getTarget() { return targetRef.getReferenceTargetElement(this); } public void setTarget(DmnElement target) { targetRef.setReferenceTargetElement(this, target); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, DMN_ELEMENT_ASSOCIATION) .namespaceUri(LATEST_DMN_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); } }); associationDirectionAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .defaultValue(AssociationDirection.None) .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); sourceRef = sequenceBuilder.element(SourceRef.class) .required() .uriElementReference(DmnElement.class) .build(); targetRef = sequenceBuilder.element(TargetRef.class) .required() .uriElementReference(DmnElement.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\AssociationImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WEBUI_M_HU_PrintReceiptLabel extends HUEditorProcessTemplate implements IProcessPrecondition { private final HULabelService huLabelService = SpringContextHolder.instance.getBean(HULabelService.class); @Param(mandatory = true, parameterName = "Copies") private int p_copies = 1; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectWithInternalReason("No (single) row selected"); } final HUToReport hu = HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow());
if (hu == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No (single) HU selected"); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { final HUToReport hu = HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow()); huLabelService.print(HULabelPrintRequest.builder() .sourceDocType(HULabelSourceDocType.MaterialReceipt) .hu(hu) .printCopiesOverride(PrintCopies.ofInt(p_copies)) .failOnMissingLabelConfig(true) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_PrintReceiptLabel.java
2
请完成以下Java代码
/* package */static Optional<JSONDocumentFilterParam> of(final DocumentFilterParam filterParam, final JSONOptions jsonOpts) { // Don't convert internal filters if (filterParam.isSqlFilter()) { // throw new IllegalArgumentException("Sql filters are not allowed to be converted to JSON filters: " + filterParam); return Optional.empty(); } final String fieldName = filterParam.getFieldName(); final Object jsonValue = Values.valueToJsonObject(filterParam.getValue(), jsonOpts); final Object jsonValueTo = Values.valueToJsonObject(filterParam.getValueTo(), jsonOpts); final JSONDocumentFilterParam jsonFilterParam = new JSONDocumentFilterParam(fieldName, jsonValue, jsonValueTo); return Optional.of(jsonFilterParam); } @JsonProperty("parameterName") String parameterName; @JsonProperty("value") Object value;
@JsonProperty("valueTo") Object valueTo; @JsonCreator @Builder private JSONDocumentFilterParam( @JsonProperty("parameterName") final String parameterName, @JsonProperty("value") final Object value, @JsonProperty("valueTo") final Object valueTo) { this.parameterName = parameterName; this.value = value; this.valueTo = valueTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\json\JSONDocumentFilterParam.java
1
请完成以下Java代码
public void setAD_WF_Next_ID (final int AD_WF_Next_ID) { if (AD_WF_Next_ID < 1) set_Value (COLUMNNAME_AD_WF_Next_ID, null); else set_Value (COLUMNNAME_AD_WF_Next_ID, AD_WF_Next_ID); } @Override public int getAD_WF_Next_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Next_ID); } @Override public void setAD_WF_Node_ID (final int AD_WF_Node_ID) { if (AD_WF_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, AD_WF_Node_ID); } @Override public int getAD_WF_Node_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID); } @Override public void setAD_WF_NodeNext_ID (final int AD_WF_NodeNext_ID) { if (AD_WF_NodeNext_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_NodeNext_ID, AD_WF_NodeNext_ID); } @Override public int getAD_WF_NodeNext_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_NodeNext_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType);
} @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void setIsStdUserWorkflow (final boolean IsStdUserWorkflow) { set_Value (COLUMNNAME_IsStdUserWorkflow, IsStdUserWorkflow); } @Override public boolean isStdUserWorkflow() { return get_ValueAsBoolean(COLUMNNAME_IsStdUserWorkflow); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTransitionCode (final java.lang.String TransitionCode) { set_Value (COLUMNNAME_TransitionCode, TransitionCode); } @Override public java.lang.String getTransitionCode() { return get_ValueAsString(COLUMNNAME_TransitionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_NodeNext.java
1
请完成以下Java代码
public final class XorCsrfChannelInterceptor implements ChannelInterceptor { private final MessageMatcher<Object> matcher = new SimpMessageTypeMatcher(SimpMessageType.CONNECT); @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { if (!this.matcher.matches(message)) { return message; } Map<String, Object> sessionAttributes = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); CsrfToken expectedToken = (sessionAttributes != null) ? (CsrfToken) sessionAttributes.get(CsrfToken.class.getName()) : null; if (expectedToken == null) { throw new MissingCsrfTokenException(null); } String actualToken = SimpMessageHeaderAccessor.wrap(message) .getFirstNativeHeader(expectedToken.getHeaderName()); String actualTokenValue = XorCsrfTokenUtils.getTokenValue(actualToken, expectedToken.getToken()); boolean csrfCheckPassed = equalsConstantTime(expectedToken.getToken(), actualTokenValue); if (!csrfCheckPassed) { throw new InvalidCsrfTokenException(expectedToken, actualToken); } return message; } /** * Constant time comparison to prevent against timing attacks.
* @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, @Nullable String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\web\csrf\XorCsrfChannelInterceptor.java
1
请完成以下Java代码
private CommentEntryParentId getParentIdOrNull(final @NonNull TableRecordReference tableRecordReference) { return queryBL.createQueryBuilder(I_CM_Chat.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_CM_Chat.COLUMNNAME_AD_Table_ID, tableRecordReference.getAD_Table_ID()) .addEqualsFilter(I_CM_Chat.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID()) .orderBy(I_CM_Chat.COLUMNNAME_CM_Chat_ID) .create() .firstId(CommentEntryParentId::ofRepoIdOrNull); } @NonNull private ImmutableMap<TableRecordReference, CommentSummary> retrieveCommentSummaries( @NonNull final Collection<TableRecordReference> references) { if (references.isEmpty()) { return ImmutableMap.of(); } final ImmutableSetMultimap<Integer, Integer> recordIdsByTableId = references.stream() .collect(ImmutableSetMultimap.toImmutableSetMultimap( TableRecordReference::getAD_Table_ID, TableRecordReference::getRecord_ID)); @SuppressWarnings("OptionalGetWithoutIsPresent") final IQuery<I_CM_Chat> query = recordIdsByTableId.keySet() .stream() .map(tableId -> createCMChatQueryByTableAndRecordIds(tableId, recordIdsByTableId.get(tableId))) .reduce(IQuery.unionDistict()) .get(); final ImmutableSet<TableRecordReference> referencesWithComments = query.stream() .map(chat -> TableRecordReference.of(chat.getAD_Table_ID(), chat.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); return references.stream() .map(reference -> CommentSummary.builder() .reference(reference) .hasComments(referencesWithComments.contains(reference))
.build()) .collect(GuavaCollectors.toImmutableMapByKey(CommentSummary::getReference)); } private IQuery<I_CM_Chat> createCMChatQueryByTableAndRecordIds(final int tableId, final Set<Integer> recordIds) { return queryBL.createQueryBuilder(I_CM_Chat.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_CM_Chat.COLUMNNAME_AD_Table_ID, tableId) .addInArrayFilter(I_CM_Chat.COLUMNNAME_Record_ID, recordIds) .create(); } @Value @Builder private static class CommentSummary { @NonNull TableRecordReference reference; boolean hasComments; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\comments\CommentsRepository.java
1
请完成以下Java代码
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
请完成以下Java代码
private static SecurPharmProduct toProductDataResult(@NonNull final I_M_Securpharm_Productdata_Result record) { final boolean error = record.isError(); return SecurPharmProduct.builder() .error(error) .resultCode(record.getLastResultCode()) .resultMessage(record.getLastResultMessage()) .productDetails(!error ? toProductDetails(record) : null) .huId(HuId.ofRepoId(record.getM_HU_ID())) .id(SecurPharmProductId.ofRepoId(record.getM_Securpharm_Productdata_Result_ID())) .build(); } private static ProductDetails toProductDetails(final I_M_Securpharm_Productdata_Result record) { return ProductDetails.builder() .productCode(record.getProductCode()) .productCodeType(ProductCodeType.ofCode(record.getProductCodeType()))
// .lot(record.getLotNumber()) .serialNumber(record.getSerialNumber()) // .expirationDate(JsonExpirationDate.ofLocalDate(TimeUtil.asLocalDate(record.getExpirationDate()))) // .activeStatus(JsonProductPackageState.ofYesNoString(record.getActiveStatus())) .inactiveReason(record.getInactiveReason()) // .decommissioned(record.isDecommissioned()) .decommissionedServerTransactionId(record.getDecommissionedServerTransactionId()) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\SecurPharmProductRepository.java
1
请完成以下Java代码
private static KPIField extractUOMField(final List<KPIField> fields) { if (fields.size() < 2) { return null; } for (final KPIField field : fields) { final String fieldName = field.getFieldName(); if ("Currency".equalsIgnoreCase(fieldName) || "CurrencyCode".equalsIgnoreCase(fieldName) || "UOMSymbol".equalsIgnoreCase(fieldName) || "UOM".equalsIgnoreCase(fieldName)) { return field; } } return null; } private static KPIField extractValueField( final List<KPIField> fields, final KPIField... excludeFields) { final List<KPIField> excludeFieldsList = Arrays.asList(excludeFields); for (final KPIField field : fields) { if (!excludeFieldsList.contains(field)) {
return field; } } throw new AdempiereException("Cannot determine value field: " + fields); } @Override public void loadRowToResult(@NonNull final KPIDataResult.Builder data, final @NonNull ResultSet rs) throws SQLException { final KPIDataValue value = SQLRowLoaderUtils.retrieveValue(rs, valueField); final String unit = uomField != null ? rs.getString(uomField.getFieldName()) : null; data.dataSet(valueField.getFieldName()) .unit(unit) .dataSetValue(KPIDataSetValuesAggregationKey.NO_KEY) .put(valueField.getFieldName(), value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\ValueAndUomSQLRowLoader.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } 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 Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\java\com\neo\entity\User.java
1
请在Spring Boot框架中完成以下Java代码
public class GetSalutationsRoute extends RouteBuilder { public static final String GET_SALUTATION_ROUTE_ID = "Shopware6-getSalutations"; private final ProcessLogger processLogger; public GetSalutationsRoute(@NonNull final ProcessLogger processLogger) { this.processLogger = processLogger; } @Override public void configure() { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager cacheManager = cachingProvider.getCacheManager(); final MutableConfiguration<GetSalutationsRequest, Object> config = new MutableConfiguration<>(); config.setTypes(GetSalutationsRequest.class, Object.class); config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1))); final Cache<GetSalutationsRequest, Object> cache = cacheManager.createCache("salutation", config); final JCachePolicy jcachePolicy = new JCachePolicy(); jcachePolicy.setCache(cache); from(direct(GET_SALUTATION_ROUTE_ID)) .id(GET_SALUTATION_ROUTE_ID) .streamCache("true") .policy(jcachePolicy) .log("Route invoked. Salutations will be cached") .process(this::getAndAttachSalutations); } private void getAndAttachSalutations(final Exchange exchange) { final GetSalutationsRequest getSalutationsRequest = exchange.getIn().getBody(GetSalutationsRequest.class); if (getSalutationsRequest == null) { throw new RuntimeException("No getSalutationsRequest provided!");
} final PInstanceLogger pInstanceLogger = PInstanceLogger.of(processLogger); final ShopwareClient shopwareClient = ShopwareClient .of(getSalutationsRequest.getClientId(), getSalutationsRequest.getClientSecret(), getSalutationsRequest.getBaseUrl(), pInstanceLogger); final ImmutableMap<String, String> salutationId2DisplayName = shopwareClient.getSalutations() .map(JsonSalutation::getSalutationList) .map(salutationList -> salutationList .stream() .filter(salutationItem -> salutationItem!= null && !Objects.equals(salutationItem.getSalutationKey(), SALUTATION_KEY_NOT_SPECIFIED)) .collect(ImmutableMap.toImmutableMap(JsonSalutationItem::getId, JsonSalutationItem::getDisplayName))) .orElseGet(ImmutableMap::of); final SalutationInfoProvider salutationInfoProvider = SalutationInfoProvider.builder() .salutationId2DisplayName(salutationId2DisplayName) .build(); exchange.getIn().setBody(salutationInfoProvider); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\salutation\GetSalutationsRoute.java
2
请完成以下Java代码
private String getNextMatch(String start) { for (int i = currentIndex; i < items.size(); i++) { if(items.get(i).toLowerCase().startsWith(start.toLowerCase())) { currentIndex = i+1; return items.get(i); } } currentIndex=0; return start; } /** * Shows the next match. * * @param e the action event */ public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if ((target != null) && (e != null)) { if ((! target.isEditable()) || (! target.isEnabled())) { UIManager.getLookAndFeel().provideErrorFeedback(target); return; } String content = target.getText(); if (content != null && target.getSelectionStart()>0) { content = content.substring(0,target.getSelectionStart()); } if (content != null) { target.setText(getNextMatch(content)); adaptor.markText(content.length()); } } } }
/** * A TextAction that provides an error feedback for the text component that invoked * the action. The error feedback is most likely a "beep". */ static Object errorFeedbackAction = new TextAction("provide-error-feedback") { /** * */ private static final long serialVersionUID = 6251452041316544686L; public void actionPerformed(ActionEvent e) { UIManager.getLookAndFeel().provideErrorFeedback(getTextComponent(e)); } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\ADempiereAutoCompleteDecorator.java
1
请完成以下Java代码
public ServerResponse.BodyBuilder lastModified(Instant lastModified) { this.headers.setLastModified(lastModified); return this; } @Override public ServerResponse.BodyBuilder location(URI location) { this.headers.setLocation(location); return this; } @Override public ServerResponse.BodyBuilder cacheControl(CacheControl cacheControl) { this.headers.setCacheControl(cacheControl); return this; } @Override public ServerResponse.BodyBuilder varyBy(String... requestHeaders) { this.headers.setVary(Arrays.asList(requestHeaders)); return this; } @Override public ServerResponse build() { return build((request, response) -> null); } @Override public ServerResponse build(WriteFunction writeFunction) { return new WriteFunctionResponse(this.statusCode, this.headers, this.cookies, writeFunction); } @Override public ServerResponse body(Object body) { return GatewayEntityResponseBuilder.fromObject(body) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build(); } @Override public <T> ServerResponse body(T body, ParameterizedTypeReference<T> bodyType) { return GatewayEntityResponseBuilder.fromObject(body, bodyType) .status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .build();
} @Override public ServerResponse render(String name, Object... modelAttributes) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(modelAttributes) .build(); } @Override public ServerResponse render(String name, Map<String, ?> model) { return new GatewayRenderingResponseBuilder(name).status(this.statusCode) .headers(headers -> headers.putAll(this.headers)) .cookies(cookies -> cookies.addAll(this.cookies)) .modelAttributes(model) .build(); } @Override public ServerResponse stream(Consumer<ServerResponse.StreamBuilder> streamConsumer) { return GatewayStreamingServerResponse.create(this.statusCode, this.headers, this.cookies, streamConsumer, null); } private static class WriteFunctionResponse extends AbstractGatewayServerResponse { private final WriteFunction writeFunction; WriteFunctionResponse(HttpStatusCode statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies, WriteFunction writeFunction) { super(statusCode, headers, cookies); Objects.requireNonNull(writeFunction, "WriteFunction must not be null"); this.writeFunction = writeFunction; } @Override protected @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { return this.writeFunction.write(request, response); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponseBuilder.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } }
repos\tutorials-master\spring-boot-modules\spring-boot-annotations\src\main\java\com\baeldung\retryable\transactional\Article.java
1
请完成以下Java代码
public void registrationSummary(String string) { logInfo( "021", string); } public void exceptionWhileLoggingRegistrationSummary(Throwable e) { logError( "022", "Exception while logging registration summary", e); } public boolean isContextSwitchLoggable() { return isDebugEnabled(); } public void debugNoTargetProcessApplicationFound(ExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("023",
"No target process application found for Execution[{}], ProcessDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getProcessDefinitionId(), execution.getProcessDefinition().getDeploymentId(), processApplicationManager.getRegistrationSummary()); } public void debugNoTargetProcessApplicationFoundForCaseExecution(CaseExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("024", "No target process application found for CaseExecution[{}], CaseDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getCaseDefinitionId(), ((CaseDefinitionEntity)execution.getCaseDefinition()).getDeploymentId(), processApplicationManager.getRegistrationSummary()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class FreshCCOUNTRYLOOKUPCOUNTRYCODEType { @XmlElement(name = "CountryCode", required = true) protected String countryCode; /** * Gets the value of the countryCode property. * * @return * possible object is * {@link String } * */ public String getCountryCode() { return countryCode;
} /** * Sets the value of the countryCode property. * * @param value * allowed object is * {@link String } * */ public void setCountryCode(String value) { this.countryCode = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\FreshCCOUNTRYLOOKUPCOUNTRYCODEType.java
2
请完成以下Java代码
public class ProductDocumentBuilder { private static ProductDocument productDocument; // create start public static ProductDocumentBuilder create(){ productDocument = new ProductDocument(); return new ProductDocumentBuilder(); } public ProductDocumentBuilder addId(String id) { productDocument.setId(id); return this; } public ProductDocumentBuilder addProductName(String productName) { productDocument.setProductName(productName); return this; } public ProductDocumentBuilder addProductDesc(String productDesc) { productDocument.setProductDesc(productDesc); return this;
} public ProductDocumentBuilder addCreateTime(Date createTime) { productDocument.setCreateTime(createTime); return this; } public ProductDocumentBuilder addUpdateTime(Date updateTime) { productDocument.setUpdateTime(updateTime); return this; } public ProductDocument builder() { return productDocument; } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\document\ProductDocumentBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductScalePriceService { private final IProductPA productPA = Services.get(IProductPA.class); private final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); @Nullable public ProductPriceSettings getProductPriceSettings(@NonNull final I_M_ProductPrice productPrice, @Nullable final Quantity qty) { if (qty == null) { return ProductPriceSettings.of(productPrice); } final ScalePriceUsage scalePriceUsage = ScalePriceUsage.ofCode(productPrice.getUseScalePrice()); if (!scalePriceUsage.useScalePrice()) { return ProductPriceSettings.of(productPrice); } final BigDecimal qtyInProductPriceUom = getQtyInProductPriceUOM(productPrice, qty); final I_M_ProductScalePrice scalePrice = productPA.retrieveScalePrices(productPrice.getM_ProductPrice_ID(), qtyInProductPriceUom, ITrx.TRXNAME_None); if (scalePrice != null) { return ProductPriceSettings.of(scalePrice); } else if (scalePriceUsage.allowFallbackToProductPrice()) { return ProductPriceSettings.of(productPrice); } else { return null; } } @NonNull
private BigDecimal getQtyInProductPriceUOM(@NonNull final I_M_ProductPrice productPrice, @NonNull final Quantity quantity) { final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID()); final UomId productPriceUomId = UomId.ofRepoId(productPrice.getC_UOM_ID()); return uomConversionBL.convertQty(productId, quantity.toBigDecimal(), quantity.getUomId(), productPriceUomId); } @Value public static class ProductPriceSettings { @NonNull BigDecimal priceStd; @NonNull BigDecimal priceLimit; @NonNull BigDecimal priceList; public static ProductPriceSettings of(@NonNull final I_M_ProductPrice productPrice) { return new ProductPriceSettings(productPrice.getPriceStd(), productPrice.getPriceLimit(), productPrice.getPriceList()); } public static ProductPriceSettings of(@NonNull final I_M_ProductScalePrice productScalePrice) { return new ProductPriceSettings(productScalePrice.getPriceStd(), productScalePrice.getPriceLimit(), productScalePrice.getPriceList()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductScalePriceService.java
2
请在Spring Boot框架中完成以下Java代码
private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientService( B builder) { OAuth2AuthorizedClientService authorizedClientService = getAuthorizedClientServiceBean(builder); if (authorizedClientService == null) { authorizedClientService = new InMemoryOAuth2AuthorizedClientService( getClientRegistrationRepository(builder)); } return authorizedClientService; } private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean( B builder) { Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils .beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class), OAuth2AuthorizedClientService.class); if (authorizedClientServiceMap.size() > 1) { throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class, authorizedClientServiceMap.size(), "Expected single matching bean of type '" + OAuth2AuthorizedClientService.class.getName() + "' but found " + authorizedClientServiceMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(authorizedClientServiceMap.keySet())); } return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
} static <B extends HttpSecurityBuilder<B>> OidcSessionRegistry getOidcSessionRegistry(B builder) { OidcSessionRegistry sessionRegistry = builder.getSharedObject(OidcSessionRegistry.class); if (sessionRegistry != null) { return sessionRegistry; } ApplicationContext context = builder.getSharedObject(ApplicationContext.class); if (context.getBeanNamesForType(OidcSessionRegistry.class).length == 1) { sessionRegistry = context.getBean(OidcSessionRegistry.class); } else { sessionRegistry = new InMemoryOidcSessionRegistry(); } builder.setSharedObject(OidcSessionRegistry.class, sessionRegistry); return sessionRegistry; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OAuth2ClientConfigurerUtils.java
2
请在Spring Boot框架中完成以下Java代码
public static String convertToBase64(VariableInstanceEntity variable) { byte[] bytes = variable.getBytes(); if (bytes != null) { return new String(Base64.getEncoder().encode(variable.getBytes()), StandardCharsets.US_ASCII); } else { return null; } } public static String getStringFromJson(ObjectNode objectNode, String fieldName) { if (objectNode.has(fieldName)) { return objectNode.get(fieldName).asString(); } return null; } public static Date getDateFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); return AsyncHistoryDateUtil.parseDate(s); } public static Integer getIntegerFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Integer.valueOf(s); } return null; }
public static Double getDoubleFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Double.valueOf(s); } return null; } public static Long getLongFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Long.valueOf(s); } return null; } public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName, Boolean defaultValue) { Boolean value = getBooleanFromJson(objectNode, fieldName); return value != null ? value : defaultValue; } public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName) { String s = getStringFromJson(objectNode, fieldName); if (StringUtils.isNotEmpty(s)) { return Boolean.valueOf(s); } return null; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\history\async\util\AsyncHistoryJsonUtil.java
2
请在Spring Boot框架中完成以下Java代码
public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Pointcut that matches all Spring beans in the application's main packages. */ @Pointcut("within(com.cars.app.repository..*)" + " || within(com.cars.app.service..*)" + " || within(com.cars.app.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Retrieves the {@link Logger} associated to the given {@link JoinPoint}. * * @param joinPoint join point we want the logger for. * @return {@link Logger} associated to the given {@link JoinPoint}. */ private Logger logger(JoinPoint joinPoint) { return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName()); } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice. * @param e exception. */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { logger(joinPoint).error( "Exception in {}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e );
} else { logger(joinPoint).error( "Exception in {}() with cause = {}", joinPoint.getSignature().getName(), e.getCause() != null ? String.valueOf(e.getCause()) : "NULL" ); } } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice. * @return result. * @throws Throwable throws {@link IllegalArgumentException}. */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Logger log = logger(joinPoint); if (log.isDebugEnabled()) { log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); throw e; } } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\aop\logging\LoggingAspect.java
2
请完成以下Java代码
public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } @Nullable public String getChatId() { return chatId; } public void setChatId(@Nullable String chatId) { this.chatId = chatId; } @Nullable public String getAuthToken() { return authToken; } public void setAuthToken(@Nullable String authToken) { this.authToken = authToken;
} public boolean isDisableNotify() { return disableNotify; } public void setDisableNotify(boolean disableNotify) { this.disableNotify = disableNotify; } public String getParseMode() { return parseMode; } public void setParseMode(String parseMode) { this.parseMode = parseMode; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java
1
请在Spring Boot框架中完成以下Java代码
public void init() throws Exception { camelContext.addRoutes(new RouteBuilder() { @Override public void configure() { JacksonDataFormat jacksonDataFormat = new JacksonDataFormat(); jacksonDataFormat.setPrettyPrint(true); from("direct:sendWhatsAppMessage") .setHeader("Authorization", constant("Bearer " + apiToken)) .setHeader("Content-Type", constant("application/json")) .marshal(jacksonDataFormat) .process(exchange -> { logger.debug("Sending JSON: {}", exchange.getIn().getBody(String.class)); }).to(apiUrl).process(exchange -> { logger.debug("Response: {}", exchange.getIn().getBody(String.class)); }); } }); } public void sendWhatsAppMessage(String toNumber, String message) { Map<String, Object> body = new HashMap<>(); body.put("messaging_product", "whatsapp"); body.put("to", toNumber); body.put("type", "text");
Map<String, String> text = new HashMap<>(); text.put("body", message); body.put("text", text); producerTemplate.sendBody("direct:sendWhatsAppMessage", body); } public void processIncomingMessage(String payload) { try { JsonNode jsonNode = objectMapper.readTree(payload); JsonNode messages = jsonNode.at("/entry/0/changes/0/value/messages"); if (messages.isArray() && messages.size() > 0) { String receivedText = messages.get(0).at("/text/body").asText(); String fromNumber = messages.get(0).at("/from").asText(); logger.debug(fromNumber + " sent the message: " + receivedText); this.sendWhatsAppMessage(fromNumber, chatbotService.getResponse(receivedText)); } } catch (Exception e) { logger.error("Error processing incoming payload: {} ", payload, e); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-3\src\main\java\com\baeldung\chatbot\service\WhatsAppService.java
2
请在Spring Boot框架中完成以下Java代码
public class PMESU1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "MEASUREQUAL", required = true) protected String measurequal; @XmlElement(name = "MEASUREATTR", required = true) protected String measureattr; @XmlElement(name = "MEASUREUNIT", required = true) protected String measureunit; @XmlElement(name = "MEASUREVALUE", required = true) protected String measurevalue; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the measurequal property. * * @return * possible object is * {@link String } * */ public String getMEASUREQUAL() { return measurequal; } /** * Sets the value of the measurequal property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREQUAL(String value) { this.measurequal = value; } /** * Gets the value of the measureattr property. * * @return * possible object is * {@link String } * */ public String getMEASUREATTR() { return measureattr; } /** * Sets the value of the measureattr property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREATTR(String value) { this.measureattr = value; } /** * Gets the value of the measureunit property. * * @return * possible object is * {@link String } *
*/ public String getMEASUREUNIT() { return measureunit; } /** * Sets the value of the measureunit property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREUNIT(String value) { this.measureunit = value; } /** * Gets the value of the measurevalue property. * * @return * possible object is * {@link String } * */ public String getMEASUREVALUE() { return measurevalue; } /** * Sets the value of the measurevalue property. * * @param value * allowed object is * {@link String } * */ public void setMEASUREVALUE(String value) { this.measurevalue = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PMESU1.java
2
请完成以下Java代码
public PageData<TbPair<UUID, String>> getAllAssetTypes(PageLink pageLink) { log.debug("Try to find all asset types and pageLink [{}]", pageLink); return DaoUtil.pageToPageData(assetRepository.getAllAssetTypes( DaoUtil.toPageable(pageLink, Arrays.asList(new SortOrder("tenantId"), new SortOrder("type"))))); } @Override public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(PageLink pageLink) { log.debug("Find profile asset id infos by pageLink [{}]", pageLink); return nativeAssetRepository.findProfileEntityIdInfos(DaoUtil.toPageable(pageLink)); } @Override public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, PageLink pageLink) { log.debug("Find profile asset id infos by pageLink [{}]", pageLink); return nativeAssetRepository.findProfileEntityIdInfosByTenantId(tenantId, DaoUtil.toPageable(pageLink)); } @Override public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) { log.debug("Find asset entity infos by name [{}]", name); return assetRepository.findEntityInfosByNamePrefix(tenantId.getId(), name); } @Override public Long countByTenantId(TenantId tenantId) { return assetRepository.countByTenantId(tenantId.getId()); } @Override public Asset findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(assetRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public Asset findByTenantIdAndName(UUID tenantId, String name) { return findAssetsByTenantIdAndName(tenantId, name).orElse(null); } @Override public PageData<Asset> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAssetsByTenantId(tenantId, pageLink); } @Override public AssetId getExternalIdByInternal(AssetId internalId) { return Optional.ofNullable(assetRepository.getExternalIdById(internalId.getId())) .map(AssetId::new).orElse(null); } @Override public PageData<Asset> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<AssetFields> findNextBatch(UUID uuid, int batchSize) { return assetRepository.findAllFields(uuid, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.ASSET; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetDao.java
1
请完成以下Java代码
public static PickingJobQuery.Facets retainFacetsOfGroups( @NonNull final PickingJobQuery.Facets queryFacets, @NonNull final Collection<PickingJobFacetGroup> groups) { if (groups.isEmpty()) { return PickingJobQuery.Facets.EMPTY; } final PickingJobQuery.Facets.FacetsBuilder builder = PickingJobQuery.Facets.builder(); for (final PickingJobFacetGroup group : groups) { PickingJobFacetHandlers.getBy(group).collectHandled(builder, queryFacets); } final PickingJobQuery.Facets queryFacetsNew = builder.build(); if (queryFacetsNew.isEmpty()) { return PickingJobQuery.Facets.EMPTY; } else if (queryFacetsNew.equals(queryFacets)) { return queryFacets; } else { return queryFacetsNew; } } public static boolean isMatching(@NonNull PickingJobFacet facet, @NonNull PickingJobQuery.Facets queryFacets) { final PickingJobFacetGroup group = facet.getGroup(); return getBy(group).isMatching(facet, queryFacets); } public static PickingJobQuery.Facets toPickingJobFacetsQuery(@Nullable final Set<WorkflowLaunchersFacetId> facetIds) { if (facetIds == null || facetIds.isEmpty()) { return PickingJobQuery.Facets.EMPTY; }
final PickingJobQuery.Facets.FacetsBuilder builder = PickingJobQuery.Facets.builder(); facetIds.forEach(facetId -> collectFromFacetId(builder, facetId)); return builder.build(); } private static void collectFromFacetId(@NonNull PickingJobQuery.Facets.FacetsBuilder collector, @NonNull WorkflowLaunchersFacetId facetId) { final PickingJobFacetGroup group = PickingJobFacetGroup.of(facetId.getGroupId()); getBy(group).collectFromFacetId(collector, facetId); } public static WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList( @NonNull final PickingJobFacets pickingFacets, @NonNull final MobileUIPickingUserProfile profile) { final ArrayList<WorkflowLaunchersFacetGroup> groups = new ArrayList<>(); for (final PickingJobFacetGroup filterOption : profile.getFilterGroupsInOrder()) { final WorkflowLaunchersFacetGroup group = PickingJobFacetHandlers.getBy(filterOption).toWorkflowLaunchersFacetGroup(pickingFacets); // NOTE: if a group has only one facet that's like not filtering at all, so having that facet in the result is pointless. if (group != null && !group.isEmpty()) { groups.add(group); } } return WorkflowLaunchersFacetGroupList.ofList(groups); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\PickingJobFacetHandlers.java
1
请在Spring Boot框架中完成以下Java代码
public Future<ResponseTransfer> getBlock() { ResponseTransfer responseTransfer = new ResponseTransfer(); Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { EthBlockNumber result = web3Service.getBlockNumber(); responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } return responseTransfer; }).thenApplyAsync(result -> { result.setPerformance(TimeHelper.stop(start)); return result; }); } @RequestMapping(value = Constants.API_ACCOUNTS, method = RequestMethod.GET) public Future<ResponseTransfer> getAccounts() { ResponseTransfer responseTransfer = new ResponseTransfer(); Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { EthAccounts result = web3Service.getEthAccounts(); responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } return responseTransfer; }).thenApplyAsync(result -> { result.setPerformance(TimeHelper.stop(start)); return result; }); } @RequestMapping(value = Constants.API_TRANSACTIONS, method = RequestMethod.GET) public Future<ResponseTransfer> getTransactions() { ResponseTransfer responseTransfer = new ResponseTransfer(); Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { EthGetTransactionCount result = web3Service.getTransactionCount(); responseTransfer.setMessage(result.toString()); } catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION); } return responseTransfer; }).thenApplyAsync(result -> { result.setPerformance(TimeHelper.stop(start)); return result; }); } @RequestMapping(value = Constants.API_BALANCE, method = RequestMethod.GET) public Future<ResponseTransfer> getBalance() { ResponseTransfer responseTransfer = new ResponseTransfer(); Instant start = TimeHelper.start(); return CompletableFuture.supplyAsync(() -> { try { EthGetBalance result = web3Service.getEthBalance(); responseTransfer.setMessage(result.toString()); } catch (Exception e) { responseTransfer.setMessage(GENERIC_EXCEPTION); } return responseTransfer; }).thenApplyAsync(result -> { result.setPerformance(TimeHelper.stop(start)); return result; }); } }
repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\controllers\EthereumRestController.java
2
请在Spring Boot框架中完成以下Java代码
public class RevolutExportCsvRow { @NonNull RevolutPaymentExport row; @NonNull public static String getCSVHeader() { return Stream.of(RevolutExportCSVColumn.Name, RevolutExportCSVColumn.RecipientType, RevolutExportCSVColumn.AccountNo, RevolutExportCSVColumn.RoutingNo, RevolutExportCSVColumn.IBAN, RevolutExportCSVColumn.BIC, RevolutExportCSVColumn.RecipientBankCountryName, RevolutExportCSVColumn.Currency, RevolutExportCSVColumn.Amount, RevolutExportCSVColumn.PaymentReference, RevolutExportCSVColumn.RecipientCountryName, RevolutExportCSVColumn.RegionName, RevolutExportCSVColumn.AddressLine1, RevolutExportCSVColumn.AddressLine2, RevolutExportCSVColumn.City, RevolutExportCSVColumn.PostalCode) .map(RevolutExportCSVColumn::getValue) .collect(Collectors.joining(",")); } @NonNull public String toCSVRow(@NonNull final ICountryDAO countryDAO) { final String recipientBankCountryName = row.getRecipientBankCountryId() != null ? countryDAO.getById(row.getRecipientBankCountryId()).getName() : null; final String recipientCountryName = row.getRecipientCountryId() != null ? countryDAO.getById(row.getRecipientCountryId()).getName() : null; return Stream.of(row.getName(), row.getRecipientType().getCode(), row.getAccountNo(), row.getRoutingNo(), row.getIBAN(),
row.getSwiftCode(), recipientBankCountryName, row.getAmount().getCurrencyCode().toThreeLetterCode(), String.valueOf(row.getAmount().getAsBigDecimal()), row.getPaymentReference(), recipientCountryName, row.getRegionName(), row.getAddressLine1(), row.getAddressLine2(), row.getCity(), row.getPostalCode()) .map(this::escapeCSV) .collect(Collectors.joining(",")); } @NonNull private String escapeCSV(@Nullable final String valueToEscape) { final String escapedQuote = "\""; return escapedQuote + StringUtils.nullToEmpty(valueToEscape).replace(escapedQuote, escapedQuote + escapedQuote) + escapedQuote; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\model\RevolutExportCsvRow.java
2
请在Spring Boot框架中完成以下Java代码
public String getJobType() { return job.getJobType(); } @Override public String getElementId() { return job.getElementId(); } @Override public String getElementName() { return job.getElementName(); } @Override public String getScopeId() { return job.getScopeId(); } @Override public String getSubScopeId() { return job.getSubScopeId(); } @Override public String getScopeType() { return job.getScopeType(); } @Override public String getScopeDefinitionId() { return job.getScopeDefinitionId(); } @Override public String getCorrelationId() { return job.getCorrelationId(); } @Override public boolean isExclusive() { return job.isExclusive(); } @Override public Date getCreateTime() { return job.getCreateTime(); } @Override public String getId() { return job.getId(); } @Override public int getRetries() { return job.getRetries(); } @Override public String getExceptionMessage() { return job.getExceptionMessage(); }
@Override public String getTenantId() { return job.getTenantId(); } @Override public String getJobHandlerType() { return job.getJobHandlerType(); } @Override public String getJobHandlerConfiguration() { return job.getJobHandlerConfiguration(); } @Override public String getCustomValues() { return job.getCustomValues(); } @Override public String getLockOwner() { return job.getLockOwner(); } @Override public Date getLockExpirationTime() { return job.getLockExpirationTime(); } @Override public String toString() { return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]") .add("job=" + job) .toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
2